inherit_from: .rubocop_todo.yml
+
+Style/BracesAroundHashParameters:
+ EnforcedStyle: context_dependent
# This configuration was generated by `rubocop --auto-gen-config`
-# on 2015-02-16 18:44:13 +0000 using RuboCop version 0.29.1.
+# on 2015-02-16 19:20:52 +0000 using RuboCop version 0.29.1.
# The point is for the user to remove these configuration records
# one by one as the offenses are removed from the code base.
# Note that changes in the inspected code, or installation of new
Lint/AssignmentInCondition:
Enabled: false
-# Offense count: 4
-# Cop supports --auto-correct.
-Lint/BlockAlignment:
- Enabled: false
-
# Offense count: 1
# Configuration parameters: AlignWith, SupportedStyles.
Lint/DefEndAlignment:
Enabled: false
-# Offense count: 4
-# Cop supports --auto-correct.
-Lint/DeprecatedClassMethods:
- Enabled: false
-
# Offense count: 2
Lint/DuplicateMethods:
Enabled: false
Lint/ShadowingOuterLocalVariable:
Enabled: false
-# Offense count: 9
-# Cop supports --auto-correct.
-Lint/SpaceBeforeFirstArg:
- Enabled: false
-
-# Offense count: 21
-# Cop supports --auto-correct.
-Lint/StringConversionInInterpolation:
- Enabled: false
-
-# Offense count: 17
-# Cop supports --auto-correct.
-Lint/UnusedBlockArgument:
- Enabled: false
-
-# Offense count: 16
-# Cop supports --auto-correct.
-Lint/UnusedMethodArgument:
- Enabled: false
-
# Offense count: 2
Lint/UselessAccessModifier:
Enabled: false
Metrics/CyclomaticComplexity:
Max: 21
-# Offense count: 2076
+# Offense count: 2112
# Configuration parameters: AllowURI, URISchemes.
Metrics/LineLength:
- Max: 253
+ Max: 520
# Offense count: 520
# Configuration parameters: CountComments.
Metrics/PerceivedComplexity:
Max: 24
-# Offense count: 46
-# Cop supports --auto-correct.
-# Configuration parameters: EnforcedStyle, SupportedStyles.
-Style/AccessModifierIndentation:
- Enabled: false
-
# Offense count: 5
Style/AccessorMethodName:
Enabled: false
-# Offense count: 6
-# Cop supports --auto-correct.
-Style/Alias:
- Enabled: false
-
-# Offense count: 9
-# Cop supports --auto-correct.
-Style/AlignArray:
- Enabled: false
-
-# Offense count: 6
-# Cop supports --auto-correct.
-# Configuration parameters: EnforcedHashRocketStyle, EnforcedColonStyle, EnforcedLastArgumentHashStyle, SupportedLastArgumentHashStyles.
-Style/AlignHash:
- Enabled: false
-
-# Offense count: 159
-# Cop supports --auto-correct.
-# Configuration parameters: EnforcedStyle, SupportedStyles.
-Style/AlignParameters:
- Enabled: false
-
-# Offense count: 217
-# Cop supports --auto-correct.
-# Configuration parameters: EnforcedStyle, SupportedStyles.
-Style/AndOr:
- Enabled: false
-
# Offense count: 1
Style/AsciiComments:
Enabled: false
-# Offense count: 87
-# Cop supports --auto-correct.
-Style/Blocks:
- Enabled: false
-
-# Offense count: 636
-# Cop supports --auto-correct.
-# Configuration parameters: EnforcedStyle, SupportedStyles.
-Style/BracesAroundHashParameters:
- Enabled: false
-
# Offense count: 21
# Configuration parameters: IndentWhenRelativeTo, SupportedStyles, IndentOneStep.
Style/CaseIndentation:
Style/ClassAndModuleChildren:
Enabled: false
-# Offense count: 3
-# Cop supports --auto-correct.
-# Configuration parameters: EnforcedStyle, SupportedStyles.
-Style/ClassCheck:
- Enabled: false
-
# Offense count: 9
Style/ClassVars:
Enabled: false
-# Offense count: 12
-# Cop supports --auto-correct.
-Style/ColonMethodCall:
- Enabled: false
-
# Offense count: 12
# Configuration parameters: Keywords.
Style/CommentAnnotation:
Enabled: false
-# Offense count: 25
-# Cop supports --auto-correct.
-Style/CommentIndentation:
- Enabled: false
-
# Offense count: 9
Style/ConstantName:
Enabled: false
-# Offense count: 17
-# Cop supports --auto-correct.
-Style/DeprecatedHashMethods:
- Enabled: false
-
# Offense count: 306
Style/Documentation:
Enabled: false
-# Offense count: 14
-# Cop supports --auto-correct.
-# Configuration parameters: EnforcedStyle, SupportedStyles.
-Style/DotPosition:
- Enabled: false
-
# Offense count: 2
Style/EachWithObject:
Enabled: false
-# Offense count: 5
-# Cop supports --auto-correct.
-Style/ElseAlignment:
- Enabled: false
-
# Offense count: 3
Style/EmptyElse:
Enabled: false
-# Offense count: 8
-# Cop supports --auto-correct.
-# Configuration parameters: AllowAdjacentOneLineDefs.
-Style/EmptyLineBetweenDefs:
- Enabled: false
-
-# Offense count: 16
-# Cop supports --auto-correct.
-Style/EmptyLines:
- Enabled: false
-
-# Offense count: 15
-# Cop supports --auto-correct.
-Style/EmptyLinesAroundAccessModifier:
- Enabled: false
-
-# Offense count: 9
-# Cop supports --auto-correct.
-# Configuration parameters: EnforcedStyle, SupportedStyles.
-Style/EmptyLinesAroundBlockBody:
- Enabled: false
-
-# Offense count: 28
-# Cop supports --auto-correct.
-# Configuration parameters: EnforcedStyle, SupportedStyles.
-Style/EmptyLinesAroundClassBody:
- Enabled: false
-
-# Offense count: 8
-# Cop supports --auto-correct.
-Style/EmptyLinesAroundMethodBody:
- Enabled: false
-
-# Offense count: 8
-# Cop supports --auto-correct.
-# Configuration parameters: EnforcedStyle, SupportedStyles.
-Style/EmptyLinesAroundModuleBody:
- Enabled: false
-
-# Offense count: 45
-# Cop supports --auto-correct.
-Style/EmptyLiteral:
- Enabled: false
-
# Offense count: 3
# Configuration parameters: Exclude.
Style/FileName:
Enabled: false
-# Offense count: 4
-# Cop supports --auto-correct.
-# Configuration parameters: EnforcedStyle, SupportedStyles.
-Style/FirstParameterIndentation:
- Enabled: false
-
# Offense count: 3
# Configuration parameters: EnforcedStyle, SupportedStyles.
Style/For:
Style/HashSyntax:
Enabled: false
-# Offense count: 42
+# Offense count: 41
# Configuration parameters: MaxLineLength.
Style/IfUnlessModifier:
Enabled: false
-# Offense count: 18
-# Cop supports --auto-correct.
-Style/IndentArray:
- Enabled: false
-
-# Offense count: 15
-# Cop supports --auto-correct.
-# Configuration parameters: EnforcedStyle, SupportedStyles.
-Style/IndentHash:
- Enabled: false
-
-# Offense count: 22
-# Cop supports --auto-correct.
-Style/IndentationConsistency:
- Enabled: false
-
-# Offense count: 40
-# Cop supports --auto-correct.
-# Configuration parameters: Width.
-Style/IndentationWidth:
- Enabled: false
-
-# Offense count: 67
-# Cop supports --auto-correct.
-Style/LeadingCommentSpace:
- Enabled: false
-
-# Offense count: 74
+# Offense count: 60
# Cop supports --auto-correct.
Style/LineEndConcatenation:
Enabled: false
-# Offense count: 17
-# Cop supports --auto-correct.
-Style/MethodCallParentheses:
- Enabled: false
-
-# Offense count: 1
-# Cop supports --auto-correct.
-# Configuration parameters: EnforcedStyle, SupportedStyles.
-Style/MethodDefParentheses:
- Enabled: false
-
# Offense count: 12
# Configuration parameters: EnforcedStyle, SupportedStyles.
Style/MethodName:
Enabled: false
-# Offense count: 28
-# Cop supports --auto-correct.
-Style/MultilineIfThen:
- Enabled: false
-
-# Offense count: 34
-# Cop supports --auto-correct.
-# Configuration parameters: EnforcedStyle, SupportedStyles.
-Style/MultilineOperationIndentation:
- Enabled: false
-
# Offense count: 3
Style/MultilineTernaryOperator:
Enabled: false
-# Offense count: 19
-# Cop supports --auto-correct.
-Style/NegatedIf:
- Enabled: false
-
# Offense count: 1
Style/NestedTernaryOperator:
Enabled: false
Style/Next:
Enabled: false
-# Offense count: 1
-# Cop supports --auto-correct.
-# Configuration parameters: IncludeSemanticChanges.
-Style/NonNilCheck:
- Enabled: false
-
-# Offense count: 32
-# Cop supports --auto-correct.
-Style/Not:
- Enabled: false
-
# Offense count: 53
# Cop supports --auto-correct.
Style/NumericLiterals:
Style/OpMethod:
Enabled: false
-# Offense count: 7
-# Cop supports --auto-correct.
-# Configuration parameters: AllowSafeAssignment.
-Style/ParenthesesAroundCondition:
- Enabled: false
-
-# Offense count: 21
-# Cop supports --auto-correct.
-# Configuration parameters: PreferredDelimiters.
-Style/PercentLiteralDelimiters:
- Enabled: false
-
# Offense count: 44
# Cop supports --auto-correct.
Style/PerlBackrefs:
Style/PredicateName:
Enabled: false
-# Offense count: 8
-# Cop supports --auto-correct.
-Style/Proc:
- Enabled: false
-
# Offense count: 95
# Configuration parameters: EnforcedStyle, SupportedStyles.
Style/RaiseArgs:
Enabled: false
-# Offense count: 11
-# Cop supports --auto-correct.
-Style/RedundantBegin:
- Enabled: false
-
-# Offense count: 113
-# Cop supports --auto-correct.
-# Configuration parameters: AllowMultipleReturnValues.
-Style/RedundantReturn:
- Enabled: false
-
-# Offense count: 200
-# Cop supports --auto-correct.
-Style/RedundantSelf:
- Enabled: false
-
# Offense count: 11
Style/RegexpLiteral:
MaxSlashes: 5
Style/RescueModifier:
Enabled: false
-# Offense count: 7
-# Cop supports --auto-correct.
-Style/SelfAssignment:
- Enabled: false
-
-# Offense count: 60
-# Cop supports --auto-correct.
+# Offense count: 25
# Configuration parameters: AllowAsExpressionSeparator.
Style/Semicolon:
Enabled: false
-# Offense count: 156
-# Cop supports --auto-correct.
-# Configuration parameters: EnforcedStyle, SupportedStyles.
-Style/SignalException:
- Enabled: false
-
# Offense count: 4
# Configuration parameters: Methods.
Style/SingleLineBlockParams:
Enabled: false
-# Offense count: 3
-# Cop supports --auto-correct.
-Style/SingleSpaceBeforeFirstArg:
- Enabled: false
-
-# Offense count: 2
-# Cop supports --auto-correct.
-Style/SpaceAfterColon:
- Enabled: false
-
-# Offense count: 409
-# Cop supports --auto-correct.
-Style/SpaceAfterComma:
- Enabled: false
-
-# Offense count: 1
-# Cop supports --auto-correct.
-Style/SpaceAfterControlKeyword:
- Enabled: false
-
-# Offense count: 3
-# Cop supports --auto-correct.
-Style/SpaceAfterMethodName:
- Enabled: false
-
-# Offense count: 34
-# Cop supports --auto-correct.
-# Configuration parameters: EnforcedStyle, SupportedStyles.
-Style/SpaceAroundEqualsInParameterDefault:
- Enabled: false
-
-# Offense count: 493
-# Cop supports --auto-correct.
-Style/SpaceAroundOperators:
- Enabled: false
-
-# Offense count: 1
-# Cop supports --auto-correct.
-# Configuration parameters: EnforcedStyle, SupportedStyles.
-Style/SpaceBeforeBlockBraces:
- Enabled: false
-
-# Offense count: 13
-# Cop supports --auto-correct.
-Style/SpaceBeforeComma:
- Enabled: false
-
-# Offense count: 2
-# Cop supports --auto-correct.
-Style/SpaceBeforeComment:
- Enabled: false
-
-# Offense count: 76
-# Cop supports --auto-correct.
-# Configuration parameters: EnforcedStyle, SupportedStyles, EnforcedStyleForEmptyBraces, SpaceBeforeBlockParameters.
-Style/SpaceInsideBlockBraces:
- Enabled: false
-
-# Offense count: 133
-# Cop supports --auto-correct.
-Style/SpaceInsideBrackets:
- Enabled: false
-
-# Offense count: 778
-# Cop supports --auto-correct.
-# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces, SupportedStyles.
-Style/SpaceInsideHashLiteralBraces:
- Enabled: false
-
-# Offense count: 9
-# Cop supports --auto-correct.
-Style/SpaceInsideParens:
- Enabled: false
-
-# Offense count: 3
-# Cop supports --auto-correct.
-Style/SpaceInsideRangeLiteral:
- Enabled: false
-
-# Offense count: 2
-# Cop supports --auto-correct.
-Style/SpecialGlobalVars:
- Enabled: false
-
# Offense count: 6639
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
Style/StructInheritance:
Enabled: false
-# Offense count: 38
-# Cop supports --auto-correct.
-# Configuration parameters: IgnoredMethods.
-Style/SymbolProc:
- Enabled: false
-
-# Offense count: 218
-# Cop supports --auto-correct.
-Style/Tab:
- Enabled: false
-
-# Offense count: 4
-# Cop supports --auto-correct.
-# Configuration parameters: EnforcedStyleForMultiline, SupportedStyles.
-Style/TrailingComma:
- Enabled: false
-
-# Offense count: 13
-# Cop supports --auto-correct.
+# Offense count: 3
# Configuration parameters: ExactNameMatch, AllowPredicates, AllowDSLWriters, Whitelist.
Style/TrivialAccessors:
Enabled: false
Style/VariableName:
Enabled: false
-# Offense count: 27
-# Cop supports --auto-correct.
-Style/WhenThen:
- Enabled: false
-
-# Offense count: 3
-# Cop supports --auto-correct.
-Style/WhileUntilDo:
- Enabled: false
-
# Offense count: 1
# Configuration parameters: MaxLineLength.
Style/WhileUntilModifier:
Enabled: false
-
-# Offense count: 85
-# Cop supports --auto-correct.
-# Configuration parameters: WordRegex.
-Style/WordArray:
- MinSize: 14
def amf_read
self.status = :ok
self.content_type = Mime::AMF
- self.response_body = Dispatcher.new(request.raw_post) do |message,*args|
+ self.response_body = Dispatcher.new(request.raw_post) do |message, *args|
logger.info("Executing AMF #{message}(#{args.join(',')})")
case message
- when 'getpresets'; result = getpresets(*args)
- when 'whichways'; result = whichways(*args)
- when 'whichways_deleted'; result = whichways_deleted(*args)
- when 'getway'; result = getway(args[0].to_i)
- when 'getrelation'; result = getrelation(args[0].to_i)
- when 'getway_old'; result = getway_old(args[0].to_i,args[1])
- when 'getway_history'; result = getway_history(args[0].to_i)
- when 'getnode_history'; result = getnode_history(args[0].to_i)
- when 'findgpx'; result = findgpx(*args)
- when 'findrelations'; result = findrelations(*args)
- when 'getpoi'; result = getpoi(*args)
+ when 'getpresets' then result = getpresets(*args)
+ when 'whichways' then result = whichways(*args)
+ when 'whichways_deleted' then result = whichways_deleted(*args)
+ when 'getway' then result = getway(args[0].to_i)
+ when 'getrelation' then result = getrelation(args[0].to_i)
+ when 'getway_old' then result = getway_old(args[0].to_i, args[1])
+ when 'getway_history' then result = getway_history(args[0].to_i)
+ when 'getnode_history' then result = getnode_history(args[0].to_i)
+ when 'findgpx' then result = findgpx(*args)
+ when 'findrelations' then result = findrelations(*args)
+ when 'getpoi' then result = getpoi(*args)
end
result
self.status = :ok
self.content_type = Mime::AMF
- self.response_body = Dispatcher.new(request.raw_post) do |message,*args|
+ self.response_body = Dispatcher.new(request.raw_post) do |message, *args|
logger.info("Executing AMF #{message}")
if err
result = [-5, nil]
else
case message
- when 'putway'; orn = renumberednodes.dup
- result = putway(renumberednodes, *args)
- result[4] = renumberednodes.reject { |k,v| orn.has_key?(k) }
- if result[0] == 0 and result[2] != result[3] then renumberedways[result[2]] = result[3] end
- when 'putrelation'; result = putrelation(renumberednodes, renumberedways, *args)
- when 'deleteway'; result = deleteway(*args)
- when 'putpoi'; result = putpoi(*args)
- if result[0] == 0 and result[2] != result[3] then renumberednodes[result[2]] = result[3] end
- when 'startchangeset'; result = startchangeset(*args)
+ when 'putway' then orn = renumberednodes.dup
+ result = putway(renumberednodes, *args)
+ result[4] = renumberednodes.reject { |k, _v| orn.key?(k) }
+ if result[0] == 0 && result[2] != result[3] then renumberedways[result[2]] = result[3] end
+ when 'putrelation' then result = putrelation(renumberednodes, renumberedways, *args)
+ when 'deleteway' then result = deleteway(*args)
+ when 'putpoi' then result = putpoi(*args)
+ if result[0] == 0 && result[2] != result[3] then renumberednodes[result[2]] = result[3] end
+ when 'startchangeset' then result = startchangeset(*args)
end
err = true if result[0] == -3 # If a conflict is detected, don't execute any more writes
private
- def amf_handle_error(call,rootobj,rootid)
+ def amf_handle_error(call, rootobj, rootid)
yield
rescue OSM::APIAlreadyDeletedError => ex
return [-4, ex.object, ex.object_id]
rescue OSM::APIUserChangesetMismatchError => ex
return [-2, ex.to_s]
rescue OSM::APIBadBoundingBox => ex
- return [-2, "Sorry - I can't get the map for that area. The server said: #{ex.to_s}"]
+ return [-2, "Sorry - I can't get the map for that area. The server said: #{ex}"]
rescue OSM::APIError => ex
return [-1, ex.to_s]
rescue Exception => ex
- return [-2, "An unusual error happened (in #{call}). The server said: #{ex.to_s}"]
+ return [-2, "An unusual error happened (in #{call}). The server said: #{ex}"]
end
- def amf_handle_error_with_timeout(call,rootobj,rootid)
- amf_handle_error(call,rootobj,rootid) do
+ def amf_handle_error_with_timeout(call, rootobj, rootid)
+ amf_handle_error(call, rootobj, rootid) do
OSM::Timer.timeout(API_TIMEOUT, OSM::APITimeoutError) do
yield
end
# Returns success_code,success_message,changeset id
def startchangeset(usertoken, cstags, closeid, closecomment, opennew)
- amf_handle_error("'startchangeset'",nil,nil) do
+ amf_handle_error("'startchangeset'", nil, nil) do
user = getuser(usertoken)
- if !user then return -1,"You are not logged in, so Potlatch can't write any changes to the database." end
- if user.blocks.active.exists? then return -1,t('application.setup_user_auth.blocked') end
- if REQUIRE_TERMS_AGREED and user.terms_agreed.nil? then return -1,"You must accept the contributor terms before you can edit." end
+ unless user then return -1, "You are not logged in, so Potlatch can't write any changes to the database." end
+ if user.blocks.active.exists? then return -1, t('application.setup_user_auth.blocked') end
+ if REQUIRE_TERMS_AGREED && user.terms_agreed.nil? then return -1, "You must accept the contributor terms before you can edit." end
if cstags
- if !tags_ok(cstags) then return -1,"One of the tags is invalid. Linux users may need to upgrade to Flash Player 10.1." end
+ unless tags_ok(cstags) then return -1, "One of the tags is invalid. Linux users may need to upgrade to Flash Player 10.1." end
cstags = strip_non_xml_chars cstags
end
if closeid
cs = Changeset.find(closeid.to_i)
cs.set_closed_time_now
- if cs.user_id!=user.id
- raise OSM::APIUserChangesetMismatchError.new
+ if cs.user_id != user.id
+ fail OSM::APIUserChangesetMismatchError.new
elsif closecomment.empty?
cs.save!
else
- cs.tags['comment']=closecomment
+ cs.tags['comment'] = closecomment
# in case closecomment has chars not allowed in xml
cs.tags = strip_non_xml_chars cs.tags
cs.save_with_tags!
end
# open a new changeset
- if opennew!=0
+ if opennew != 0
cs = Changeset.new
cs.tags = cstags
cs.user_id = user.id
- if !closecomment.empty?
- cs.tags['comment']=closecomment
+ unless closecomment.empty?
+ cs.tags['comment'] = closecomment
# in case closecomment has chars not allowed in xml
cs.tags = strip_non_xml_chars cs.tags
end
cs.created_at = Time.now.getutc
cs.closed_at = cs.created_at + Changeset::IDLE_TIMEOUT
cs.save_with_tags!
- return [0,'',cs.id]
+ return [0, '', cs.id]
else
- return [0,'',nil]
+ return [0, '', nil]
end
end
end
# Return presets (default tags, localisation etc.):
# uses POTLATCH_PRESETS global, set up in OSM::Potlatch.
- def getpresets(usertoken,lang) #:doc:
+ def getpresets(usertoken, lang) #:doc:
user = getuser(usertoken)
if user && !user.languages.empty?
localised.delete("help_html")
# Populate icon names
- POTLATCH_PRESETS[10].each { |id|
+ POTLATCH_PRESETS[10].each do |id|
POTLATCH_PRESETS[11][id] = localised["preset_icon_#{id}"]
localised.delete("preset_icon_#{id}")
- }
+ end
- return POTLATCH_PRESETS+[localised,help]
+ POTLATCH_PRESETS + [localised, help]
end
def getlocalized(lang)
loaded_lang = 'en'
# Load English defaults
- en = YAML::load(File.open("#{Rails.root}/config/potlatch/locales/en.yml"))["en"]
+ en = YAML.load(File.open("#{Rails.root}/config/potlatch/locales/en.yml"))["en"]
if lang == 'en'
return [loaded_lang, en]
else
# Use English as a fallback
begin
- other = YAML::load(File.open("#{Rails.root}/config/potlatch/locales/#{lang}.yml"))[lang]
+ other = YAML.load(File.open("#{Rails.root}/config/potlatch/locales/#{lang}.yml"))[lang]
loaded_lang = lang
rescue
other = en
# used in any way, rel is any relation which refers to either a way
# or node that we're returning.
def whichways(xmin, ymin, xmax, ymax) #:doc:
- amf_handle_error_with_timeout("'whichways'",nil,nil) do
- enlarge = [(xmax-xmin)/8,0.01].min
+ amf_handle_error_with_timeout("'whichways'", nil, nil) do
+ enlarge = [(xmax - xmin) / 8, 0.01].min
xmin -= enlarge; ymin -= enlarge
xmax += enlarge; ymax += enlarge
bbox.check_boundaries
bbox.check_size
- if POTLATCH_USE_SQL then
+ if POTLATCH_USE_SQL
ways = sql_find_ways_in_area(bbox)
points = sql_find_pois_in_area(bbox)
- relations = sql_find_relations_in_area_and_ways(bbox, ways.collect {|x| x[0]})
+ relations = sql_find_relations_in_area_and_ways(bbox, ways.collect { |x| x[0] })
else
# find the way ids in an area
nodes_in_area = Node.bbox(bbox).visible.includes(:ways)
- ways = nodes_in_area.inject([]) { |sum, node|
- visible_ways = node.ways.select { |w| w.visible? }
- sum + visible_ways.collect { |w| [w.id,w.version] }
- }.uniq
+ ways = nodes_in_area.inject([]) do |sum, node|
+ visible_ways = node.ways.select(&:visible?)
+ sum + visible_ways.collect { |w| [w.id, w.version] }
+ end.uniq
ways.delete([])
# find the node ids in an area that aren't part of ways
points = nodes_not_used_in_area.collect { |n| [n.id, n.lon, n.lat, n.tags, n.version] }.uniq
# find the relations used by those nodes and ways
- relations = Relation.nodes(nodes_in_area.collect { |n| n.id }).visible +
+ relations = Relation.nodes(nodes_in_area.collect(&:id)).visible +
Relation.ways(ways.collect { |w| w[0] }).visible
- relations = relations.collect { |relation| [relation.id,relation.version] }.uniq
+ relations = relations.collect { |relation| [relation.id, relation.version] }.uniq
end
[0, '', ways, points, relations]
# with a deleted node only - not POIs or relations).
def whichways_deleted(xmin, ymin, xmax, ymax) #:doc:
- amf_handle_error_with_timeout("'whichways_deleted'",nil,nil) do
- enlarge = [(xmax-xmin)/8,0.01].min
+ amf_handle_error_with_timeout("'whichways_deleted'", nil, nil) do
+ enlarge = [(xmax - xmin) / 8, 0.01].min
xmin -= enlarge; ymin -= enlarge
xmax += enlarge; ymax += enlarge
bbox.check_size
nodes_in_area = Node.bbox(bbox).joins(:ways_via_history).where(:current_ways => { :visible => false })
- way_ids = nodes_in_area.collect { |node| node.ways_via_history.invisible.collect { |way| way.id } }.flatten.uniq
+ way_ids = nodes_in_area.collect { |node| node.ways_via_history.invisible.collect(&:id) }.flatten.uniq
- [0,'',way_ids]
+ [0, '', way_ids]
end
end
# Returns the way id, a Potlatch-style array of points, a hash of tags, the version number, and the user ID.
def getway(wayid) #:doc:
- amf_handle_error_with_timeout("'getway' #{wayid}" ,'way',wayid) do
- if POTLATCH_USE_SQL then
+ amf_handle_error_with_timeout("'getway' #{wayid}", 'way', wayid) do
+ if POTLATCH_USE_SQL
points = sql_get_nodes_in_way(wayid)
tags = sql_get_tags_in_way(wayid)
version = sql_get_way_version(wayid)
way = Way.where(:id => wayid).first
# check case where way has been deleted or doesn't exist
- return [-4, 'way', wayid] if way.nil? or !way.visible
+ return [-4, 'way', wayid] if way.nil? || !way.visible
points = way.nodes.preload(:node_tags).collect do |node|
- nodetags=node.tags
+ nodetags = node.tags
nodetags.delete('created_by')
[node.lon, node.lat, node.id, nodetags, node.version]
end
# 5. is this the current, visible version? (boolean)
def getway_old(id, timestamp) #:doc:
- amf_handle_error_with_timeout("'getway_old' #{id}, #{timestamp}", 'way',id) do
+ amf_handle_error_with_timeout("'getway_old' #{id}, #{timestamp}", 'way', id) do
if timestamp == ''
# undelete
old_way = OldWay.where(:visible => true, :way_id => id).unredacted.order("version DESC").first
old_way = OldWay.where("way_id = ? AND timestamp <= ?", id, timestamp).unredacted.order("timestamp DESC").first
unless old_way.nil?
points = old_way.get_nodes_revert(timestamp)
- if !old_way.visible
+ unless old_way.visible
return [-1, "Sorry, the way was deleted at that time - please revert to a previous version.", id]
end
end
if old_way.nil?
return [-1, "Sorry, the server could not find a way at that time.", id]
else
- curway=Way.find(id)
+ curway = Way.find(id)
old_way.tags['history'] = "Retrieved from v#{old_way.version}"
- return [0, '', id, points, old_way.tags, curway.version, (curway.version==old_way.version and curway.visible)]
+ return [0, '', id, points, old_way.tags, curway.version, (curway.version == old_way.version && curway.visible)]
end
end
end
# start date of the way.
def getway_history(wayid) #:doc:
- begin
- # Find list of revision dates for way and all constituent nodes
- revdates=[]
- revusers={}
- Way.find(wayid).old_ways.unredacted.collect do |a|
- revdates.push(a.timestamp)
- unless revusers.has_key?(a.timestamp.to_i) then revusers[a.timestamp.to_i]=change_user(a) end
- a.nds.each do |n|
- Node.find(n).old_nodes.unredacted.collect do |o|
- revdates.push(o.timestamp)
- unless revusers.has_key?(o.timestamp.to_i) then revusers[o.timestamp.to_i]=change_user(o) end
- end
+ revdates = []
+ revusers = {}
+ Way.find(wayid).old_ways.unredacted.collect do |a|
+ revdates.push(a.timestamp)
+ unless revusers.key?(a.timestamp.to_i) then revusers[a.timestamp.to_i] = change_user(a) end
+ a.nds.each do |n|
+ Node.find(n).old_nodes.unredacted.collect do |o|
+ revdates.push(o.timestamp)
+ unless revusers.key?(o.timestamp.to_i) then revusers[o.timestamp.to_i] = change_user(o) end
end
end
- waycreated=revdates[0]
- revdates.uniq!
- revdates.sort!
- revdates.reverse!
-
- # Remove any dates (from nodes) before first revision date of way
- revdates.delete_if { |d| d<waycreated }
- # Remove any elements where 2 seconds doesn't elapse before next one
- revdates.delete_if { |d| revdates.include?(d+1) or revdates.include?(d+2) }
- # Collect all in one nested array
- revdates.collect! {|d| [(d + 1).strftime("%d %b %Y, %H:%M:%S")] + revusers[d.to_i] }
- revdates.uniq!
-
- return ['way', wayid, revdates]
- rescue ActiveRecord::RecordNotFound
- return ['way', wayid, []]
end
+ waycreated = revdates[0]
+ revdates.uniq!
+ revdates.sort!
+ revdates.reverse!
+
+ # Remove any dates (from nodes) before first revision date of way
+ revdates.delete_if { |d| d < waycreated }
+ # Remove any elements where 2 seconds doesn't elapse before next one
+ revdates.delete_if { |d| revdates.include?(d + 1) || revdates.include?(d + 2) }
+ # Collect all in one nested array
+ revdates.collect! { |d| [(d + 1).strftime("%d %b %Y, %H:%M:%S")] + revusers[d.to_i] }
+ revdates.uniq!
+
+ return ['way', wayid, revdates]
+ rescue ActiveRecord::RecordNotFound
+ return ['way', wayid, []]
end
# Find history of a node. Returns 'node', id, and an array of previous versions as above.
def getnode_history(nodeid) #:doc:
- begin
- history = Node.find(nodeid).old_nodes.unredacted.reverse.collect do |old_node|
- [(old_node.timestamp + 1).strftime("%d %b %Y, %H:%M:%S")] + change_user(old_node)
- end
- return ['node', nodeid, history]
- rescue ActiveRecord::RecordNotFound
- return ['node', nodeid, []]
+ history = Node.find(nodeid).old_nodes.unredacted.reverse.collect do |old_node|
+ [(old_node.timestamp + 1).strftime("%d %b %Y, %H:%M:%S")] + change_user(old_node)
end
+ return ['node', nodeid, history]
+ rescue ActiveRecord::RecordNotFound
+ return ['node', nodeid, []]
end
def change_user(obj)
user_object = obj.changeset.user
user = user_object.data_public? ? user_object.display_name : 'anonymous'
uid = user_object.data_public? ? user_object.id : 0
- [user,uid]
+ [user, uid]
end
# Find GPS traces with specified name/id.
# Returns array listing GPXs, each one comprising id, name and description.
def findgpx(searchterm, usertoken)
- amf_handle_error_with_timeout("'findgpx'" ,nil,nil) do
+ amf_handle_error_with_timeout("'findgpx'", nil, nil) do
user = getuser(usertoken)
- if !user then return -1,"You must be logged in to search for GPX traces." end
- if user.blocks.active.exists? then return -1,t('application.setup_user_auth.blocked') end
+ unless user then return -1, "You must be logged in to search for GPX traces." end
+ if user.blocks.active.exists? then return -1, t('application.setup_user_auth.blocked') end
query = Trace.visible_to(user)
- if searchterm.to_i > 0 then
+ if searchterm.to_i > 0
query = query.where(:id => searchterm.to_i)
else
query = query.where("MATCH(name) AGAINST (?)", searchterm).limit(21)
gpxs = query.collect do |gpx|
[gpx.id, gpx.name, gpx.description]
end
- [0,'',gpxs]
+ [0, '', gpxs]
end
end
# 5. version.
def getrelation(relid) #:doc:
- amf_handle_error("'getrelation' #{relid}" ,'relation',relid) do
+ amf_handle_error("'getrelation' #{relid}", 'relation', relid) do
rel = Relation.where(:id => relid).first
- return [-4, 'relation', relid] if rel.nil? or !rel.visible
+ return [-4, 'relation', relid] if rel.nil? || !rel.visible
[0, '', relid, rel.tags, rel.members, rel.version]
end
end
def findrelations(searchterm)
rels = []
- if searchterm.to_i>0 then
+ if searchterm.to_i > 0
rel = Relation.where(:id => searchterm.to_i).first
- if rel and rel.visible then
+ if rel && rel.visible
rels.push([rel.id, rel.tags, rel.members, rel.version])
end
else
RelationTag.where("v like ?", "%#{searchterm}%").limit(11).each do |t|
- if t.relation.visible then
+ if t.relation.visible
rels.push([t.relation.id, t.relation.tags, t.relation.members, t.relation.version])
end
end
# 3. version.
def putrelation(renumberednodes, renumberedways, usertoken, changeset_id, version, relid, tags, members, visible) #:doc:
- amf_handle_error("'putrelation' #{relid}" ,'relation',relid) do
+ amf_handle_error("'putrelation' #{relid}", 'relation', relid) do
user = getuser(usertoken)
- if !user then return -1,"You are not logged in, so the relation could not be saved." end
- if user.blocks.active.exists? then return -1,t('application.setup_user_auth.blocked') end
- if REQUIRE_TERMS_AGREED and user.terms_agreed.nil? then return -1,"You must accept the contributor terms before you can edit." end
+ unless user then return -1, "You are not logged in, so the relation could not be saved." end
+ if user.blocks.active.exists? then return -1, t('application.setup_user_auth.blocked') end
+ if REQUIRE_TERMS_AGREED && user.terms_agreed.nil? then return -1, "You must accept the contributor terms before you can edit." end
- if !tags_ok(tags) then return -1,"One of the tags is invalid. Linux users may need to upgrade to Flash Player 10.1." end
+ unless tags_ok(tags) then return -1, "One of the tags is invalid. Linux users may need to upgrade to Flash Player 10.1." end
tags = strip_non_xml_chars tags
relid = relid.to_i
else
return [0, '', relid, relid, relation.version]
end
- end
+ end
end
# Save a way to the database, including all nodes. Any nodes in the previous
# 6. hash of node versions (node=>version)
def putway(renumberednodes, usertoken, changeset_id, wayversion, originalway, pointlist, attributes, nodes, deletednodes) #:doc:
- amf_handle_error("'putway' #{originalway}" ,'way',originalway) do
+ amf_handle_error("'putway' #{originalway}", 'way', originalway) do
# -- Initialise
user = getuser(usertoken)
- if !user then return -1,"You are not logged in, so the way could not be saved." end
- if user.blocks.active.exists? then return -1,t('application.setup_user_auth.blocked') end
- if REQUIRE_TERMS_AGREED and user.terms_agreed.nil? then return -1,"You must accept the contributor terms before you can edit." end
+ unless user then return -1, "You are not logged in, so the way could not be saved." end
+ if user.blocks.active.exists? then return -1, t('application.setup_user_auth.blocked') end
+ if REQUIRE_TERMS_AGREED && user.terms_agreed.nil? then return -1, "You must accept the contributor terms before you can edit." end
- if pointlist.length < 2 then return -2,"Server error - way is only #{points.length} points long." end
+ if pointlist.length < 2 then return -2, "Server error - way is only #{points.length} points long." end
- if !tags_ok(attributes) then return -1,"One of the tags is invalid. Linux users may need to upgrade to Flash Player 10.1." end
+ unless tags_ok(attributes) then return -1, "One of the tags is invalid. Linux users may need to upgrade to Flash Player 10.1." end
attributes = strip_non_xml_chars attributes
originalway = originalway.to_i
- pointlist.collect! {|a| a.to_i }
+ pointlist.collect!(&:to_i)
- way=nil # this is returned, so scope it outside the transaction
+ way = nil # this is returned, so scope it outside the transaction
nodeversions = {}
Way.transaction do
-
# -- Update each changed node
nodes.each do |a|
id = a[2].to_i
version = a[3].to_i
- if id == 0 then return -2,"Server error - node with id 0 found in way #{originalway}." end
- if lat== 90 then return -2,"Server error - node with latitude -90 found in way #{originalway}." end
+ if id == 0 then return -2, "Server error - node with id 0 found in way #{originalway}." end
+ if lat == 90 then return -2, "Server error - node with latitude -90 found in way #{originalway}." end
if renumberednodes[id] then id = renumberednodes[id] end
node = Node.new
node.tags = a[4]
# fixup node tags in a way as well
- if !tags_ok(node.tags) then return -1,"One of the tags is invalid. Linux users may need to upgrade to Flash Player 10.1." end
+ unless tags_ok(node.tags) then return -1, "One of the tags is invalid. Linux users may need to upgrade to Flash Player 10.1." end
node.tags = strip_non_xml_chars node.tags
node.tags.delete('created_by')
nodeversions[node.id] = node.version
else
# We're updating an existing node
- previous=Node.find(id)
- node.id=id
+ previous = Node.find(id)
+ node.id = id
previous.update_from(node, user)
nodeversions[previous.id] = previous.version
end
# -- Save revised way
- pointlist.collect! {|a|
- renumberednodes[a] ? renumberednodes[a]:a
- } # renumber nodes
+ pointlist.collect! do|a|
+ renumberednodes[a] ? renumberednodes[a] : a
+ end # renumber nodes
new_way = Way.new
new_way.tags = attributes
new_way.nds = pointlist
new_way.version = wayversion
if originalway <= 0
new_way.create_with_history(user)
- way=new_way # so we can get way.id and way.version
+ way = new_way # so we can get way.id and way.version
else
way = Way.find(originalway)
- if way.tags!=attributes or way.nds!=pointlist or !way.visible?
- new_way.id=originalway
- way.update_from(new_way, user)
+ if way.tags != attributes || way.nds != pointlist || !way.visible?
+ new_way.id = originalway
+ way.update_from(new_way, user)
end
end
# -- Delete unwanted nodes
- deletednodes.each do |id,v|
+ deletednodes.each do |id, v|
node = Node.find(id.to_i)
new_node = Node.new
new_node.changeset_id = changeset_id
# and we don't want to delete it
end
end
-
end # transaction
[0, '', originalway, way.id, renumberednodes, way.version, nodeversions, deletednodes]
# 4. version.
def putpoi(usertoken, changeset_id, version, id, lon, lat, tags, visible) #:doc:
- amf_handle_error("'putpoi' #{id}", 'node',id) do
+ amf_handle_error("'putpoi' #{id}", 'node', id) do
user = getuser(usertoken)
- if !user then return -1,"You are not logged in, so the point could not be saved." end
- if user.blocks.active.exists? then return -1,t('application.setup_user_auth.blocked') end
- if REQUIRE_TERMS_AGREED and user.terms_agreed.nil? then return -1,"You must accept the contributor terms before you can edit." end
+ unless user then return -1, "You are not logged in, so the point could not be saved." end
+ if user.blocks.active.exists? then return -1, t('application.setup_user_auth.blocked') end
+ if REQUIRE_TERMS_AGREED && user.terms_agreed.nil? then return -1, "You must accept the contributor terms before you can edit." end
- if !tags_ok(tags) then return -1,"One of the tags is invalid. Linux users may need to upgrade to Flash Player 10.1." end
+ unless tags_ok(tags) then return -1, "One of the tags is invalid. Linux users may need to upgrade to Flash Player 10.1." end
tags = strip_non_xml_chars tags
id = id.to_i
node = nil
new_node = nil
Node.transaction do
- if id > 0 then
+ if id > 0
node = Node.find(id)
- if !visible then
- unless node.ways.empty? then return -1,"Point #{id} has since become part of a way, so you cannot save it as a POI.",id,id,version end
+ unless visible
+ unless node.ways.empty? then return -1, "Point #{id} has since become part of a way, so you cannot save it as a POI.", id, id, version end
end
end
# We always need a new node, based on the data that has been sent to us
new_node.create_with_history(user)
elsif visible
# We're updating the node
- new_node.id=id
+ new_node.id = id
node.update_from(new_node, user)
else
# We're deleting the node
- new_node.id=id
+ new_node.id = id
node.delete_with_history!(new_node, user)
end
-
end # transaction
if id <= 0
#
# Returns array of id, long, lat, hash of tags, (current) version.
- def getpoi(id,timestamp) #:doc:
- amf_handle_error("'getpoi' #{id}" ,'node',id) do
+ def getpoi(id, timestamp) #:doc:
+ amf_handle_error("'getpoi' #{id}", 'node', id) do
id = id.to_i
n = Node.find(id)
v = n.version
# Returns 0 (success), unchanged way id, new way version, new node versions.
def deleteway(usertoken, changeset_id, way_id, way_version, deletednodes) #:doc:
- amf_handle_error("'deleteway' #{way_id}" ,'way', way_id) do
+ amf_handle_error("'deleteway' #{way_id}", 'way', way_id) do
user = getuser(usertoken)
- unless user then return -1,"You are not logged in, so the way could not be deleted." end
- if user.blocks.active.exists? then return -1,t('application.setup_user_auth.blocked') end
- if REQUIRE_TERMS_AGREED and user.terms_agreed.nil? then return -1,"You must accept the contributor terms before you can edit." end
+ unless user then return -1, "You are not logged in, so the way could not be deleted." end
+ if user.blocks.active.exists? then return -1, t('application.setup_user_auth.blocked') end
+ if REQUIRE_TERMS_AGREED && user.terms_agreed.nil? then return -1, "You must accept the contributor terms before you can edit." end
way_id = way_id.to_i
nodeversions = {}
- old_way=nil # returned, so scope it outside the transaction
+ old_way = nil # returned, so scope it outside the transaction
# Need a transaction so that if one item fails to delete, the whole delete fails.
Way.transaction do
-
# -- Delete the way
old_way = Way.find(way_id)
# -- Delete unwanted nodes
- deletednodes.each do |id,v|
+ deletednodes.each do |id, v|
node = Node.find(id.to_i)
new_node = Node.new
new_node.changeset_id = changeset_id
new_node.id = id.to_i
begin
node.delete_with_history!(new_node, user)
- nodeversions[node.id]=node.version
+ nodeversions[node.id] = node.version
rescue OSM::APIPreconditionFailedError => ex
# We don't do anything with the exception as the node is in use
# elsewhere and we don't want to delete it
end
end
-
end # transaction
[0, '', way_id, old_way.version, nodeversions]
end
end
-
# ====================================================================
# Support functions
# not just the id, hence this abstraction
def getuser(token) #:doc:
- if (token =~ /^(.+)\:(.+)$/) then
+ if token =~ /^(.+)\:(.+)$/
user = User.authenticate(:username => $1, :password => $2)
else
user = User.authenticate(:token => token)
end
- return user
+ user
end
def getlocales
return false unless UTF8.valid? k
return false unless UTF8.valid? v
end
- return true
+ true
end
##
# strip characters which are invalid in XML documents from the strings
# in the +tags+ hash.
def strip_non_xml_chars(tags)
- new_tags = Hash.new
+ new_tags = {}
unless tags.nil?
tags.each do |k, v|
new_k = k.delete "\000-\037\ufffe\uffff", "^\011\012\015"
new_tags[new_k] = new_v
end
end
- return new_tags
+ new_tags
end
# ====================================================================
# Alternative SQL queries for getway/whichways
def sql_find_ways_in_area(bbox)
- sql=<<-EOF
+ sql = <<-EOF
SELECT DISTINCT current_ways.id AS wayid,current_ways.version AS version
FROM current_way_nodes
INNER JOIN current_nodes ON current_nodes.id=current_way_nodes.node_id
AND current_ways.visible=TRUE
AND #{OSM.sql_for_area(bbox, "current_nodes.")}
EOF
- return ActiveRecord::Base.connection.select_all(sql).collect { |a| [a['wayid'].to_i,a['version'].to_i] }
+ ActiveRecord::Base.connection.select_all(sql).collect { |a| [a['wayid'].to_i, a['version'].to_i] }
end
def sql_find_pois_in_area(bbox)
- pois=[]
- sql=<<-EOF
+ pois = []
+ sql = <<-EOF
SELECT current_nodes.id,current_nodes.latitude*0.0000001 AS lat,current_nodes.longitude*0.0000001 AS lon,current_nodes.version
FROM current_nodes
LEFT OUTER JOIN current_way_nodes cwn ON cwn.node_id=current_nodes.id
AND #{OSM.sql_for_area(bbox, "current_nodes.")}
EOF
ActiveRecord::Base.connection.select_all(sql).each do |row|
- poitags={}
+ poitags = {}
ActiveRecord::Base.connection.select_all("SELECT k,v FROM current_node_tags WHERE id=#{row['id']}").each do |n|
- poitags[n['k']]=n['v']
+ poitags[n['k']] = n['v']
end
pois << [row['id'].to_i, row['lon'].to_f, row['lat'].to_f, poitags, row['version'].to_i]
end
pois
end
- def sql_find_relations_in_area_and_ways(bbox,way_ids)
+ def sql_find_relations_in_area_and_ways(bbox, way_ids)
# ** It would be more Potlatchy to get relations for nodes within ways
# during 'getway', not here
- sql=<<-EOF
+ sql = <<-EOF
SELECT DISTINCT cr.id AS relid,cr.version AS version
FROM current_relations cr
INNER JOIN current_relation_members crm ON crm.id=cr.id
WHERE #{OSM.sql_for_area(bbox, "cn.")}
EOF
unless way_ids.empty?
- sql+=<<-EOF
+ sql += <<-EOF
UNION
SELECT DISTINCT cr.id AS relid,cr.version AS version
FROM current_relations cr
AND crm.member_id IN (#{way_ids.join(',')})
EOF
end
- ActiveRecord::Base.connection.select_all(sql).collect { |a| [a['relid'].to_i,a['version'].to_i] }
+ ActiveRecord::Base.connection.select_all(sql).collect { |a| [a['relid'].to_i, a['version'].to_i] }
end
def sql_get_nodes_in_way(wayid)
- points=[]
- sql=<<-EOF
+ points = []
+ sql = <<-EOF
SELECT latitude*0.0000001 AS lat,longitude*0.0000001 AS lon,current_nodes.id,current_nodes.version
FROM current_way_nodes,current_nodes
WHERE current_way_nodes.id=#{wayid.to_i}
ORDER BY sequence_id
EOF
ActiveRecord::Base.connection.select_all(sql).each do |row|
- nodetags={}
+ nodetags = {}
ActiveRecord::Base.connection.select_all("SELECT k,v FROM current_node_tags WHERE id=#{row['id']}").each do |n|
- nodetags[n['k']]=n['v']
+ nodetags[n['k']] = n['v']
end
nodetags.delete('created_by')
- points << [row['lon'].to_f,row['lat'].to_f,row['id'].to_i,nodetags,row['version'].to_i]
+ points << [row['lon'].to_f, row['lat'].to_f, row['id'].to_i, nodetags, row['version'].to_i]
end
points
end
def sql_get_tags_in_way(wayid)
- tags={}
+ tags = {}
ActiveRecord::Base.connection.select_all("SELECT k,v FROM current_way_tags WHERE id=#{wayid.to_i}").each do |row|
- tags[row['k']]=row['v']
+ tags[row['k']] = row['v']
end
tags
end
class ApiController < ApplicationController
-
skip_before_filter :verify_authenticity_token
before_filter :check_api_readable, :except => [:capabilities]
before_filter :setup_user_auth, :only => [:permissions]
# Get an XML response containing a list of tracepoints that have been uploaded
# within the specified bounding box, and in the specified page.
def trackpoints
- #retrieve the page number
+ # retrieve the page number
page = params['page'].to_s.to_i
unless page >= 0
- report_error("Page number must be greater than or equal to 0")
- return
+ report_error("Page number must be greater than or equal to 0")
+ return
end
offset = page * TRACEPOINTS_PER_PAGE
return
end
- @nodes = Node.bbox(bbox).where(:visible => true).includes(:node_tags).limit(MAX_NUMBER_OF_NODES+1)
+ @nodes = Node.bbox(bbox).where(:visible => true).includes(:node_tags).limit(MAX_NUMBER_OF_NODES + 1)
node_ids = @nodes.collect(&:id)
if node_ids.length > MAX_NUMBER_OF_NODES
# get ways
# find which ways are needed
- ways = Array.new
+ ways = []
if node_ids.length > 0
way_nodes = WayNode.where(:node_id => node_ids)
way_ids = way_nodes.collect { |way_node| way_node.id[0] }
ways = Way.preload(:way_nodes, :way_tags).find(way_ids)
- list_of_way_nodes = ways.collect { |way|
- way.way_nodes.collect { |way_node| way_node.node_id }
- }
+ list_of_way_nodes = ways.collect do |way|
+ way.way_nodes.collect(&:node_id)
+ end
list_of_way_nodes.flatten!
else
- list_of_way_nodes = Array.new
+ list_of_way_nodes = []
end
# - [0] in case some thing links to node 0 which doesn't exist. Shouldn't actually ever happen but it does. FIXME: file a ticket for this
end
end
- way_ids = Array.new
+ way_ids = []
ways.each do |way|
if way.visible?
doc.root << way.to_xml_node(visible_nodes, changeset_cache, user_display_name_cache)
# another way B also referenced, that is not returned. But we do make
# an exception for cases where an relation references another *relation*;
# in that case we return that as well (but we don't go recursive here)
- relations += Relation.relations(relations.collect { |r| r.id }).visible
+ relations += Relation.relations(relations.collect(&:id)).visible
# this "uniq" may be slightly inefficient; it may be better to first collect and output
# all node-related relations, then find the *not yet covered* way-related ones etc.
def changes
zoom = (params[:zoom] || '12').to_i
- if params.include?(:start) and params.include?(:end)
+ if params.include?(:start) && params.include?(:end)
starttime = Time.parse(params[:start])
endtime = Time.parse(params[:end])
else
starttime = endtime - hours
end
- if zoom >= 1 and zoom <= 16 and
- endtime > starttime and endtime - starttime <= 24.hours
+ if zoom >= 1 && zoom <= 16 &&
+ endtime > starttime && endtime - starttime <= 24.hours
mask = (1 << zoom) - 1
- tiles = Node.where(:timestamp => starttime .. endtime).group("maptile_for_point(latitude, longitude, #{zoom})").count
+ tiles = Node.where(:timestamp => starttime..endtime).group("maptile_for_point(latitude, longitude, #{zoom})").count
doc = OSM::API.new.get_xml_doc
changes = XML::Node.new 'changes'
api = XML::Node.new 'api'
version = XML::Node.new 'version'
- version['minimum'] = "#{API_VERSION}";
- version['maximum'] = "#{API_VERSION}";
+ version['minimum'] = "#{API_VERSION}"
+ version['maximum'] = "#{API_VERSION}"
api << version
area = XML::Node.new 'area'
- area['maximum'] = MAX_REQUEST_AREA.to_s;
+ area['maximum'] = MAX_REQUEST_AREA.to_s
api << area
tracepoints = XML::Node.new 'tracepoints'
tracepoints['per_page'] = TRACEPOINTS_PER_PAGE.to_s
if session[:user]
@user = User.where(:id => session[:user]).where("status IN ('active', 'confirmed', 'suspended')").first
- if @user.status == "suspended"
+ if @user.status == "suspended"
session.delete(:user)
session_expires_automatically
redirect_to :controller => "user", :action => "suspended"
- # don't allow access to any auth-requiring part of the site unless
- # the new CTs have been seen (and accept/decline chosen).
- elsif !@user.terms_seen and flash[:skip_terms].nil?
+ # don't allow access to any auth-requiring part of the site unless
+ # the new CTs have been seen (and accept/decline chosen).
+ elsif !@user.terms_seen && flash[:skip_terms].nil?
flash[:notice] = t 'user.terms.you need to accept or decline'
if params[:referer]
redirect_to :controller => "user", :action => "terms", :referer => params[:referer]
else
redirect_to :controller => "user", :action => "terms", :referer => request.fullpath
end
- end
+ end
elsif session[:token]
if @user = User.authenticate(:token => session[:token])
session[:user] = @user.id
end
end
rescue Exception => ex
- logger.info("Exception authorizing user: #{ex.to_s}")
+ logger.info("Exception authorizing user: #{ex}")
reset_session
@user = nil
end
end
def require_oauth
- @oauth = @user.access_token(OAUTH_KEY) if @user and defined? OAUTH_KEY
+ @oauth = @user.access_token(OAUTH_KEY) if @user && defined? OAUTH_KEY
end
##
def require_allow_read_prefs
require_capability(:allow_read_prefs)
end
+
def require_allow_write_prefs
require_capability(:allow_write_prefs)
end
+
def require_allow_write_diary
require_capability(:allow_write_diary)
end
+
def require_allow_write_api
require_capability(:allow_write_api)
- if REQUIRE_TERMS_AGREED and @user.terms_agreed.nil?
+ if REQUIRE_TERMS_AGREED && @user.terms_agreed.nil?
report_error "You must accept the contributor terms before you can edit.", :forbidden
return false
end
end
+
def require_allow_read_gpx
require_capability(:allow_read_gpx)
end
+
def require_allow_write_gpx
require_capability(:allow_write_gpx)
end
+
def require_allow_write_notes
require_capability(:allow_write_notes)
end
# is optional.
def setup_user_auth
# try and setup using OAuth
- if not Authenticator.new(self, [:token]).allow?
+ unless Authenticator.new(self, [:token]).allow?
username, passwd = get_auth_data # parse from headers
# authenticate per-scheme
if username.nil?
# if the user hasn't seen the contributor terms then don't
# allow editing - they have to go to the web site and see
# (but can decline) the CTs to continue.
- if REQUIRE_TERMS_SEEN and not @user.terms_seen and flash[:skip_terms].nil?
+ if REQUIRE_TERMS_SEEN && !@user.terms_seen && flash[:skip_terms].nil?
set_locale
report_error t('application.setup_user_auth.need_to_see_terms'), :forbidden
end
end
end
- def authorize(realm='Web Password', errormessage="Couldn't authenticate you")
+ def authorize(realm = 'Web Password', errormessage = "Couldn't authenticate you")
# make the @user object from any auth sources we have
setup_user_auth
# from require_moderator - but what we really need to do is a fairly
# drastic refactoring based on :format and respond_to? but not a
# good idea to do that in this branch.
- def authorize_moderator(errormessage="Access restricted to moderators")
+ def authorize_moderator(errormessage = "Access restricted to moderators")
# check user is a moderator
unless @user.moderator?
render :text => errormessage, :status => :forbidden
end
def check_database_readable(need_api = false)
- if STATUS == :database_offline or (need_api and STATUS == :api_offline)
+ if STATUS == :database_offline || (need_api && STATUS == :api_offline)
if request.xhr?
report_error "Database offline for maintenance", :service_unavailable
else
end
def check_database_writable(need_api = false)
- if STATUS == :database_offline or STATUS == :database_readonly or
- (need_api and (STATUS == :api_offline or STATUS == :api_readonly))
+ if STATUS == :database_offline || STATUS == :database_readonly ||
+ (need_api && (STATUS == :api_offline || STATUS == :api_readonly))
if request.xhr?
report_error "Database offline for maintenance", :service_unavailable
else
status = :readonly
end
end
- return status
+ status
end
def gpx_status
if status == :online
status = :offline if STATUS == :gpx_offline
end
- return status
+ status
end
def require_public_data
# Todo: some sort of escaping of problem characters in the message
response.headers['Error'] = message
- if request.headers['X-Error-Format'] and
+ if request.headers['X-Error-Format'] &&
request.headers['X-Error-Format'].downcase == "xml"
result = OSM::API.new.get_xml_doc
result.root.name = "osmError"
def select_locale(locales = I18n.available_locales)
if params[:locale]
- http_accept_language.user_preferred_languages = [ params[:locale] ]
+ http_accept_language.user_preferred_languages = [params[:locale]]
end
if http_accept_language.compatible_language_from(locales).nil?
http_accept_language.user_preferred_languages = http_accept_language.user_preferred_languages.collect do |pl|
- pls = [ pl ]
+ pls = [pl]
while pl.match(/^(.*)-[^-]+$/)
- pls.push($1) if locales.include?($1) or locales.include?($1.to_sym)
+ pls.push($1) if locales.include?($1) || locales.include?($1.to_sym)
pl = $1
end
helper_method :select_locale
def api_call_handle_error
- begin
- yield
- rescue ActiveRecord::RecordNotFound => ex
- render :text => "", :status => :not_found
- rescue LibXML::XML::Error, ArgumentError => ex
- report_error ex.message, :bad_request
- rescue ActiveRecord::RecordInvalid => ex
- message = "#{ex.record.class} #{ex.record.id}: "
- ex.record.errors.each { |attr,msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
- report_error message, :bad_request
- rescue OSM::APIError => ex
- report_error ex.message, ex.status
- rescue AbstractController::ActionNotFound => ex
- raise
- rescue Exception => ex
- logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
- ex.backtrace.each { |l| logger.info(l) }
- report_error "#{ex.class}: #{ex.message}", :internal_server_error
- end
+ yield
+ rescue ActiveRecord::RecordNotFound => ex
+ render :text => "", :status => :not_found
+ rescue LibXML::XML::Error, ArgumentError => ex
+ report_error ex.message, :bad_request
+ rescue ActiveRecord::RecordInvalid => ex
+ message = "#{ex.record.class} #{ex.record.id}: "
+ ex.record.errors.each { |attr, msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
+ report_error message, :bad_request
+ rescue OSM::APIError => ex
+ report_error ex.message, ex.status
+ rescue AbstractController::ActionNotFound => ex
+ raise
+ rescue Exception => ex
+ logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
+ ex.backtrace.each { |l| logger.info(l) }
+ report_error "#{ex.class}: #{ex.message}", :internal_server_error
end
##
# or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
def assert_method(method)
ok = request.send((method.to_s.downcase + "?").to_sym)
- raise OSM::APIBadMethodError.new(method) unless ok
+ fail OSM::APIBadMethodError.new(method) unless ok
end
##
rescue ActionView::Template::Error => ex
ex = ex.original_exception
- if ex.is_a?(ActiveRecord::StatementInvalid) and ex.message =~ /execution expired/
+ if ex.is_a?(ActiveRecord::StatementInvalid) && ex.message =~ /execution expired/
ex = Timeout::Error.new
end
def preferred_editor
editor = if params[:editor]
- params[:editor]
- elsif @user and @user.preferred_editor
- @user.preferred_editor
- else
- DEFAULT_EDITOR
+ params[:editor]
+ elsif @user && @user.preferred_editor
+ @user.preferred_editor
+ else
+ DEFAULT_EDITOR
end
- if request.env['HTTP_USER_AGENT'] =~ /MSIE|Trident/ and editor == 'id'
+ if request.env['HTTP_USER_AGENT'] =~ /MSIE|Trident/ && editor == 'id'
editor = 'potlatch2'
end
helper_method :preferred_editor
-private
+ private
# extract authorisation credentials from headers, returns user = nil if none
def get_auth_data
- if request.env.has_key? 'X-HTTP_AUTHORIZATION' # where mod_rewrite might have put it
+ if request.env.key? 'X-HTTP_AUTHORIZATION' # where mod_rewrite might have put it
authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split
- elsif request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION' # mod_fcgi
+ elsif request.env.key? 'REDIRECT_X_HTTP_AUTHORIZATION' # mod_fcgi
authdata = request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split
- elsif request.env.has_key? 'HTTP_AUTHORIZATION' # regular location
+ elsif request.env.key? 'HTTP_AUTHORIZATION' # regular location
authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
end
# only basic authentication supported
- if authdata and authdata[0] == 'Basic'
- user, pass = Base64.decode64(authdata[1]).split(':',2)
+ if authdata && authdata[0] == 'Basic'
+ user, pass = Base64.decode64(authdata[1]).split(':', 2)
end
- return [user, pass]
+ [user, pass]
end
# used by oauth plugin to get the current user
# used by oauth plugin to set the current user
def current_user=(user)
- @user=user
+ @user = user
end
# override to stop oauth plugin sending errors
def invalid_oauth_response
end
-
end
before_filter :authorize_web
before_filter :set_locale
- before_filter :except => [ :query ] { |c| c.check_database_readable(true) }
+ before_filter :except => [:query] { |c| c.check_database_readable(true) }
before_filter :require_oauth
around_filter :web_timeout
def changeset
@type = "changeset"
@changeset = Changeset.find(params[:id])
- if @user and @user.moderator?
+ if @user && @user.moderator?
@comments = @changeset.comments.unscope(:where => :visible).includes(:author)
else
@comments = @changeset.comments.includes(:author)
end
- @node_pages, @nodes = paginate(:old_nodes, :conditions => {:changeset_id => @changeset.id}, :per_page => 20, :parameter => 'node_page')
- @way_pages, @ways = paginate(:old_ways, :conditions => {:changeset_id => @changeset.id}, :per_page => 20, :parameter => 'way_page')
- @relation_pages, @relations = paginate(:old_relations, :conditions => {:changeset_id => @changeset.id}, :per_page => 20, :parameter => 'relation_page')
+ @node_pages, @nodes = paginate(:old_nodes, :conditions => { :changeset_id => @changeset.id }, :per_page => 20, :parameter => 'node_page')
+ @way_pages, @ways = paginate(:old_ways, :conditions => { :changeset_id => @changeset.id }, :per_page => 20, :parameter => 'way_page')
+ @relation_pages, @relations = paginate(:old_relations, :conditions => { :changeset_id => @changeset.id }, :per_page => 20, :parameter => 'relation_page')
if @changeset.user.data_public?
@next_by_user = @changeset.user.changesets.where("id > ?", @changeset.id).reorder(:id => :asc).first
@prev_by_user = @changeset.user.changesets.where("id < ?", @changeset.id).reorder(:id => :desc).first
check_changeset_consistency(cs, @user)
# keep an array of lons and lats
- lon = Array.new
- lat = Array.new
+ lon = []
+ lat = []
# the request is in pseudo-osm format... this is kind-of an
# abuse, maybe should change to some other format?
##
# list edits (open changesets) in reverse chronological order
def list
- if request.format == :atom and params[:max_id]
- redirect_to params.merge({ :max_id => nil }), :status => :moved_permanently
+ if request.format == :atom && params[:max_id]
+ redirect_to params.merge(:max_id => nil), :status => :moved_permanently
return
end
return
end
- if request.format == :html and !params[:list]
+ if request.format == :html && !params[:list]
require_oauth
render :action => :history, :layout => map_layout
else
changesets = conditions_nonempty(Changeset.all)
if params[:display_name]
- if user.data_public? or user == @user
+ if user.data_public? || user == @user
changesets = changesets.where(:user_id => user.id)
else
changesets = changesets.where("false")
# Add a comment to a changeset
def comment
# Check the arguments are sane
- raise OSM::APIBadUserInput.new("No id was given") unless params[:id]
- raise OSM::APIBadUserInput.new("No text was given") if params[:text].blank?
+ fail OSM::APIBadUserInput.new("No id was given") unless params[:id]
+ fail OSM::APIBadUserInput.new("No text was given") if params[:text].blank?
# Extract the arguments
id = params[:id].to_i
# Find the changeset and check it is valid
changeset = Changeset.find(id)
- raise OSM::APIChangesetNotYetClosedError.new(changeset) if changeset.is_open?
+ fail OSM::APIChangesetNotYetClosedError.new(changeset) if changeset.is_open?
# Add a comment to the changeset
- comment = changeset.comments.create({
- :changeset => changeset,
- :body => body,
- :author => @user
- })
+ comment = changeset.comments.create(:changeset => changeset,
+ :body => body,
+ :author => @user)
# Notify current subscribers of the new comment
changeset.subscribers.each do |user|
# Adds a subscriber to the changeset
def subscribe
# Check the arguments are sane
- raise OSM::APIBadUserInput.new("No id was given") unless params[:id]
+ fail OSM::APIBadUserInput.new("No id was given") unless params[:id]
# Extract the arguments
id = params[:id].to_i
# Find the changeset and check it is valid
changeset = Changeset.find(id)
- raise OSM::APIChangesetNotYetClosedError.new(changeset) if changeset.is_open?
- raise OSM::APIChangesetAlreadySubscribedError.new(changeset) if changeset.subscribers.exists?(@user.id)
+ fail OSM::APIChangesetNotYetClosedError.new(changeset) if changeset.is_open?
+ fail OSM::APIChangesetAlreadySubscribedError.new(changeset) if changeset.subscribers.exists?(@user.id)
# Add the subscriber
changeset.subscribers << @user
# Removes a subscriber from the changeset
def unsubscribe
# Check the arguments are sane
- raise OSM::APIBadUserInput.new("No id was given") unless params[:id]
+ fail OSM::APIBadUserInput.new("No id was given") unless params[:id]
# Extract the arguments
id = params[:id].to_i
# Find the changeset and check it is valid
changeset = Changeset.find(id)
- raise OSM::APIChangesetNotYetClosedError.new(changeset) if changeset.is_open?
- raise OSM::APIChangesetNotSubscribedError.new(changeset) unless changeset.subscribers.exists?(@user.id)
+ fail OSM::APIChangesetNotYetClosedError.new(changeset) if changeset.is_open?
+ fail OSM::APIChangesetNotSubscribedError.new(changeset) unless changeset.subscribers.exists?(@user.id)
# Remove the subscriber
changeset.subscribers.delete(@user)
# Sets visible flag on comment to false
def hide_comment
# Check the arguments are sane
- raise OSM::APIBadUserInput.new("No id was given") unless params[:id]
+ fail OSM::APIBadUserInput.new("No id was given") unless params[:id]
# Extract the arguments
id = params[:id].to_i
# Sets visible flag on comment to true
def unhide_comment
# Check the arguments are sane
- raise OSM::APIBadUserInput.new("No id was given") unless params[:id]
+ fail OSM::APIBadUserInput.new("No id was given") unless params[:id]
# Extract the arguments
id = params[:id].to_i
end
end
-private
+ private
+
#------------------------------------------------------------
# utility functions below.
#------------------------------------------------------------
##
# restrict changesets to those by a particular user
def conditions_user(changesets, user, name)
- unless user.nil? and name.nil?
+ unless user.nil? && name.nil?
# shouldn't provide both name and UID
- raise OSM::APIBadUserInput.new("provide either the user ID or display name, but not both") if user and name
+ fail OSM::APIBadUserInput.new("provide either the user ID or display name, but not both") if user && name
# use either the name or the UID to find the user which we're selecting on.
u = if name.nil?
# user input checking, we don't have any UIDs < 1
- raise OSM::APIBadUserInput.new("invalid user ID") if user.to_i < 1
+ fail OSM::APIBadUserInput.new("invalid user ID") if user.to_i < 1
u = User.find(user.to_i)
else
u = User.find_by_display_name(name)
end
# make sure we found a user
- raise OSM::APINotFoundError.new if u.nil?
+ fail OSM::APINotFoundError.new if u.nil?
# should be able to get changesets of public users only, or
# our own changesets regardless of public-ness.
# changesets if they're non-public
setup_user_auth
- raise OSM::APINotFoundError if @user.nil? or @user.id != u.id
+ fail OSM::APINotFoundError if @user.nil? || @user.id != u.id
end
return changesets.where(:user_id => u.id)
else
if time.count(',') == 1
# check that we actually have 2 elements in the array
times = time.split(/,/)
- raise OSM::APIBadUserInput.new("bad time range") if times.size != 2
+ fail OSM::APIBadUserInput.new("bad time range") if times.size != 2
from, to = times.collect { |t| DateTime.parse(t) }
return changesets.where("closed_at >= ? and created_at <= ?", from, to)
if ids.nil?
return changesets
elsif ids.empty?
- raise OSM::APIBadUserInput.new("No changesets were given to search for")
+ fail OSM::APIBadUserInput.new("No changesets were given to search for")
else
- ids = ids.split(',').collect { |n| n.to_i }
+ ids = ids.split(',').collect(&:to_i)
return changesets.where(:id => ids)
end
end
# eliminate empty changesets (where the bbox has not been set)
# this should be applied to all changeset list displays
def conditions_nonempty(changesets)
- return changesets.where("num_changes > 0")
+ changesets.where("num_changes > 0")
end
##
# Get the maximum number of comments to return
def comments_limit
if params[:limit]
- if params[:limit].to_i > 0 and params[:limit].to_i <= 10000
+ if params[:limit].to_i > 0 && params[:limit].to_i <= 10000
params[:limit].to_i
else
- raise OSM::APIBadUserInput.new("Comments limit must be between 1 and 10000")
+ fail OSM::APIBadUserInput.new("Comments limit must be between 1 and 10000")
end
else
100
end
def edit
- @title= t 'diary_entry.edit.title'
+ @title = t 'diary_entry.edit.title'
@diary_entry = DiaryEntry.find(params[:id])
if @user != @diary_entry.user
redirect_to :controller => 'diary_entry', :action => 'view', :id => params[:id]
- elsif params[:diary_entry] and @diary_entry.update_attributes(entry_params)
+ elsif params[:diary_entry] && @diary_entry.update_attributes(entry_params)
redirect_to :controller => 'diary_entry', :action => 'view', :id => params[:id]
end
@title = t 'diary_entry.list.title_friends'
@entries = DiaryEntry.where(:user_id => @user.friend_users)
else
- require_user
- return
+ require_user
+ return
end
elsif params[:nearby]
if @user
@title = t 'diary_entry.list.title_nearby'
@entries = DiaryEntry.where(:user_id => @user.nearby)
else
- require_user
- return
+ require_user
+ return
end
else
- @entries = DiaryEntry.joins(:user).where(:users => { :status => ["active", "confirmed"] })
+ @entries = DiaryEntry.joins(:user).where(:users => { :status => %w(active confirmed) })
if params[:language]
@title = t 'diary_entry.list.in_language_title', :language => Language.find(params[:language]).english_name
return
end
else
- @entries = DiaryEntry.joins(:user).where(:users => { :status => ["active", "confirmed"] })
+ @entries = DiaryEntry.joins(:user).where(:users => { :status => %w(active confirmed) })
if params[:language]
@entries = @entries.where(:language_code => params[:language])
:per_page => 20)
@page = (params[:page] || 1).to_i
end
-private
+
+ private
+
##
# return permitted diary entry parameters
def entry_params
##
# is this list user specific?
def user_specific_list?
- params[:friends] or params[:nearby]
+ params[:friends] || params[:nearby]
end
##
# decide on a location for the diary entry map
def set_map_location
- if @diary_entry.latitude and @diary_entry.longitude
+ if @diary_entry.latitude && @diary_entry.longitude
@lon = @diary_entry.longitude
@lat = @diary_entry.latitude
@zoom = 12
- elsif @user.home_lat.nil? or @user.home_lon.nil?
+ elsif @user.home_lat.nil? || @user.home_lon.nil?
@lon = params[:lon] || -0.1
@lat = params[:lat] || 51.5
@zoom = params[:zoom] || 4
class ExportController < ApplicationController
-
before_filter :authorize_web
before_filter :set_locale
caches_page :embed
- #When the user clicks 'Export' we redirect to a URL which generates the export download
+ # When the user clicks 'Export' we redirect to a URL which generates the export download
def finish
bbox = BoundingBox.from_lon_lat_params(params)
format = params[:format]
if format == "osm"
- #redirect to API map get
+ # redirect to API map get
redirect_to "http://api.openstreetmap.org/api/#{API_VERSION}/map?bbox=#{bbox}"
elsif format == "mapnik"
- #redirect to a special 'export' cgi script
+ # redirect to a special 'export' cgi script
format = params[:mapnik_format]
scale = params[:mapnik_scale]
def search_latlon
lat = params[:lat].to_f
lon = params[:lon].to_f
- if lat < -90 or lat > 90
+ if lat < -90 || lat > 90
@error = "Latitude #{lat} out of range"
render :action => "error"
- elsif lon < -180 or lon > 180
+ elsif lon < -180 || lon > 180
@error = "Longitude #{lon} out of range"
render :action => "error"
else
- @results = [{:lat => lat, :lon => lon,
- :zoom => params[:zoom],
- :name => "#{lat}, #{lon}"}]
+ @results = [{ :lat => lat, :lon => lon,
+ :zoom => params[:zoom],
+ :name => "#{lat}, #{lon}" }]
render :action => "results"
end
query = params[:query]
# create result array
- @results = Array.new
+ @results = []
# ask geocoder.us (they have a non-commercial use api)
response = fetch_text("http://rpc.geocoder.us/service/csv?zip=#{escape_query(query)}")
# parse the response
unless response.match(/couldn't find this zip/)
data = response.split(/\s*,\s+/) # lat,long,town,state,zip
- @results.push({:lat => data[0], :lon => data[1],
- :zoom => POSTCODE_ZOOM,
- :prefix => "#{data[2]}, #{data[3]},",
- :name => data[4]})
+ @results.push(:lat => data[0], :lon => data[1],
+ :zoom => POSTCODE_ZOOM,
+ :prefix => "#{data[2]}, #{data[3]},",
+ :name => data[4])
end
render :action => "results"
rescue Exception => ex
- @error = "Error contacting rpc.geocoder.us: #{ex.to_s}"
+ @error = "Error contacting rpc.geocoder.us: #{ex}"
render :action => "error"
end
query = params[:query]
# create result array
- @results = Array.new
+ @results = []
# ask npemap.org.uk to do a combined npemap + freethepostcode search
response = fetch_text("http://www.npemap.org.uk/cgi/geocoder.fcgi?format=text&postcode=#{escape_query(query)}")
data = dataline.split(/,/) # easting,northing,postcode,lat,long
postcode = data[2].gsub(/'/, "")
zoom = POSTCODE_ZOOM - postcode.count("#")
- @results.push({:lat => data[3], :lon => data[4], :zoom => zoom,
- :name => postcode})
+ @results.push(:lat => data[3], :lon => data[4], :zoom => zoom,
+ :name => postcode)
end
render :action => "results"
rescue Exception => ex
- @error = "Error contacting www.npemap.org.uk: #{ex.to_s}"
+ @error = "Error contacting www.npemap.org.uk: #{ex}"
render :action => "error"
end
def search_ca_postcode
# get query parameters
query = params[:query]
- @results = Array.new
+ @results = []
# ask geocoder.ca (note - they have a per-day limit)
response = fetch_xml("http://geocoder.ca/?geoit=XML&postal=#{escape_query(query)}")
# parse the response
if response.get_elements("geodata/error").empty?
- @results.push({:lat => response.get_text("geodata/latt").to_s,
- :lon => response.get_text("geodata/longt").to_s,
- :zoom => POSTCODE_ZOOM,
- :name => query.upcase})
+ @results.push(:lat => response.get_text("geodata/latt").to_s,
+ :lon => response.get_text("geodata/longt").to_s,
+ :zoom => POSTCODE_ZOOM,
+ :name => query.upcase)
end
render :action => "results"
rescue Exception => ex
- @error = "Error contacting geocoder.ca: #{ex.to_s}"
+ @error = "Error contacting geocoder.ca: #{ex}"
render :action => "error"
end
more_url_params = CGI.parse(URI.parse(results.attributes["more_url"]).query)
# create result array
- @results = Array.new
+ @results = []
# create parameter hash for "more results" link
- @more_params = params.merge({
- :exclude => more_url_params["exclude_place_ids"].first
- })
+ @more_params = params.merge(:exclude => more_url_params["exclude_place_ids"].first)
# parse the response
results.elements.each("place") do |place|
klass = place.attributes["class"].to_s
type = place.attributes["type"].to_s
name = place.attributes["display_name"].to_s
- min_lat,max_lat,min_lon,max_lon = place.attributes["boundingbox"].to_s.split(",")
+ min_lat, max_lat, min_lon, max_lon = place.attributes["boundingbox"].to_s.split(",")
if type.empty?
prefix_name = ""
else
prefix_name = t "geocoder.search_osm_nominatim.prefix.#{klass}.#{type}", :default => type.gsub("_", " ").capitalize
end
- if klass == 'boundary' and type == 'administrative'
+ if klass == 'boundary' && type == 'administrative'
rank = (place.attributes["place_rank"].to_i + 1) / 2
prefix_name = t "geocoder.search_osm_nominatim.admin_levels.level#{rank}", :default => prefix_name
end
object_type = place.attributes["osm_type"]
object_id = place.attributes["osm_id"]
- @results.push({:lat => lat, :lon => lon,
- :min_lat => min_lat, :max_lat => max_lat,
- :min_lon => min_lon, :max_lon => max_lon,
- :prefix => prefix, :name => name,
- :type => object_type, :id => object_id})
+ @results.push(:lat => lat, :lon => lon,
+ :min_lat => min_lat, :max_lat => max_lat,
+ :min_lon => min_lon, :max_lon => max_lon,
+ :prefix => prefix, :name => name,
+ :type => object_type, :id => object_id)
end
render :action => "results"
-# rescue Exception => ex
-# @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
-# render :action => "error"
+ # rescue Exception => ex
+ # @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
+ # render :action => "error"
end
def search_geonames
lang = I18n.locale.to_s.split("-").first
# create result array
- @results = Array.new
+ @results = []
# ask geonames.org
response = fetch_xml("http://api.geonames.org/search?q=#{escape_query(query)}&lang=#{lang}&maxRows=20&username=#{GEONAMES_USERNAME}")
lon = geoname.get_text("lng").to_s
name = geoname.get_text("name").to_s
country = geoname.get_text("countryName").to_s
- @results.push({:lat => lat, :lon => lon,
- :zoom => GEONAMES_ZOOM,
- :name => name,
- :suffix => ", #{country}"})
+ @results.push(:lat => lat, :lon => lon,
+ :zoom => GEONAMES_ZOOM,
+ :name => name,
+ :suffix => ", #{country}")
end
render :action => "results"
rescue Exception => ex
- @error = "Error contacting ws.geonames.org: #{ex.to_s}"
+ @error = "Error contacting ws.geonames.org: #{ex}"
render :action => "error"
end
zoom = params[:zoom]
# create result array
- @results = Array.new
+ @results = []
# ask nominatim
response = fetch_xml("http:#{NOMINATIM_URL}reverse?lat=#{lat}&lon=#{lon}&zoom=#{zoom}&accept-language=#{http_accept_language.user_preferred_languages.join(',')}")
object_id = result.attributes["osm_id"]
description = result.get_text.to_s
- @results.push({:lat => lat, :lon => lon,
- :zoom => zoom,
- :name => description,
- :type => object_type, :id => object_id})
+ @results.push(:lat => lat, :lon => lon,
+ :zoom => zoom,
+ :name => description,
+ :type => object_type, :id => object_id)
end
render :action => "results"
rescue Exception => ex
- @error = "Error contacting nominatim.openstreetmap.org: #{ex.to_s}"
+ @error = "Error contacting nominatim.openstreetmap.org: #{ex}"
render :action => "error"
end
lang = I18n.locale.to_s.split("-").first
# create result array
- @results = Array.new
+ @results = []
# ask geonames.org
response = fetch_xml("http://api.geonames.org/countrySubdivision?lat=#{lat}&lng=#{lon}&lang=#{lang}&username=#{GEONAMES_USERNAME}")
response.elements.each("geonames/countrySubdivision") do |geoname|
name = geoname.get_text("adminName1").to_s
country = geoname.get_text("countryName").to_s
- @results.push({:lat => lat, :lon => lon,
- :zoom => GEONAMES_ZOOM,
- :name => name,
- :suffix => ", #{country}"})
+ @results.push(:lat => lat, :lon => lon,
+ :zoom => GEONAMES_ZOOM,
+ :name => name,
+ :suffix => ", #{country}")
end
render :action => "results"
rescue Exception => ex
- @error = "Error contacting ws.geonames.org: #{ex.to_s}"
+ @error = "Error contacting ws.geonames.org: #{ex}"
render :action => "error"
end
-private
+ private
def fetch_text(url)
- return Net::HTTP.get(URI.parse(url))
+ Net::HTTP.get(URI.parse(url))
end
def fetch_xml(url)
- return REXML::Document.new(fetch_text(url))
+ REXML::Document.new(fetch_text(url))
end
def format_distance(distance)
- return t("geocoder.distance", :count => distance)
+ t("geocoder.distance", :count => distance)
end
def format_direction(bearing)
- return t("geocoder.direction.south_west") if bearing >= 22.5 and bearing < 67.5
- return t("geocoder.direction.south") if bearing >= 67.5 and bearing < 112.5
- return t("geocoder.direction.south_east") if bearing >= 112.5 and bearing < 157.5
- return t("geocoder.direction.east") if bearing >= 157.5 and bearing < 202.5
- return t("geocoder.direction.north_east") if bearing >= 202.5 and bearing < 247.5
- return t("geocoder.direction.north") if bearing >= 247.5 and bearing < 292.5
- return t("geocoder.direction.north_west") if bearing >= 292.5 and bearing < 337.5
- return t("geocoder.direction.west")
+ return t("geocoder.direction.south_west") if bearing >= 22.5 && bearing < 67.5
+ return t("geocoder.direction.south") if bearing >= 67.5 && bearing < 112.5
+ return t("geocoder.direction.south_east") if bearing >= 112.5 && bearing < 157.5
+ return t("geocoder.direction.east") if bearing >= 157.5 && bearing < 202.5
+ return t("geocoder.direction.north_east") if bearing >= 202.5 && bearing < 247.5
+ return t("geocoder.direction.north") if bearing >= 247.5 && bearing < 292.5
+ return t("geocoder.direction.north_west") if bearing >= 292.5 && bearing < 337.5
+ t("geocoder.direction.west")
end
def format_name(name)
- return name.gsub(/( *\[[^\]]*\])*$/, "")
+ name.gsub(/( *\[[^\]]*\])*$/, "")
end
def count_results(results)
count += source[:results].length if source[:results]
end
- return count
+ count
end
def escape_query(query)
- return URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, 'N'))
+ URI.escape(query, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]", false, 'N'))
end
def normalize_params
params.merge!(dms_to_decdeg(latlon)).delete(:query)
elsif latlon = query.match(/^\s*([+-]?\d+(\.\d*)?)\s*[\s,]\s*([+-]?\d+(\.\d*)?)\s*$/)
- params.merge!({:lat => latlon[1].to_f, :lon => latlon[3].to_f}).delete(:query)
+ params.merge!(:lat => latlon[1].to_f, :lon => latlon[3].to_f).delete(:query)
end
end
captures[0].downcase != 's' ? lat = captures[1].to_f : lat = -(captures[1].to_f)
captures[3].downcase != 'w' ? lon = captures[4].to_f : lon = -(captures[4].to_f)
end
- {:lat => lat, :lon => lon}
+ { :lat => lat, :lon => lon }
end
def ddm_to_decdeg(captures)
begin
Float(captures[0])
- captures[3].downcase != 's' ? lat = captures[0].to_f + captures[1].to_f/60 : lat = -(captures[0].to_f + captures[1].to_f/60)
- captures[7].downcase != 'w' ? lon = captures[4].to_f + captures[5].to_f/60 : lon = -(captures[4].to_f + captures[5].to_f/60)
+ captures[3].downcase != 's' ? lat = captures[0].to_f + captures[1].to_f / 60 : lat = -(captures[0].to_f + captures[1].to_f / 60)
+ captures[7].downcase != 'w' ? lon = captures[4].to_f + captures[5].to_f / 60 : lon = -(captures[4].to_f + captures[5].to_f / 60)
rescue
- captures[0].downcase != 's' ? lat = captures[1].to_f + captures[2].to_f/60 : lat = -(captures[1].to_f + captures[2].to_f/60)
- captures[4].downcase != 'w' ? lon = captures[5].to_f + captures[6].to_f/60 : lon = -(captures[5].to_f + captures[6].to_f/60)
+ captures[0].downcase != 's' ? lat = captures[1].to_f + captures[2].to_f / 60 : lat = -(captures[1].to_f + captures[2].to_f / 60)
+ captures[4].downcase != 'w' ? lon = captures[5].to_f + captures[6].to_f / 60 : lon = -(captures[5].to_f + captures[6].to_f / 60)
end
- {:lat => lat, :lon => lon}
+ { :lat => lat, :lon => lon }
end
def dms_to_decdeg(captures)
begin
Float(captures[0])
- captures[4].downcase != 's' ? lat = captures[0].to_f + (captures[1].to_f + captures[2].to_f/60)/60 : lat = -(captures[0].to_f + (captures[1].to_f + captures[2].to_f/60)/60)
- captures[9].downcase != 'w' ? lon = captures[5].to_f + (captures[6].to_f + captures[7].to_f/60)/60 : lon = -(captures[5].to_f + (captures[6].to_f + captures[7].to_f/60)/60)
+ captures[4].downcase != 's' ? lat = captures[0].to_f + (captures[1].to_f + captures[2].to_f / 60) / 60 : lat = -(captures[0].to_f + (captures[1].to_f + captures[2].to_f / 60) / 60)
+ captures[9].downcase != 'w' ? lon = captures[5].to_f + (captures[6].to_f + captures[7].to_f / 60) / 60 : lon = -(captures[5].to_f + (captures[6].to_f + captures[7].to_f / 60) / 60)
rescue
- captures[0].downcase != 's' ? lat = captures[1].to_f + (captures[2].to_f + captures[3].to_f/60)/60 : lat = -(captures[1].to_f + (captures[2].to_f + captures[3].to_f/60)/60)
- captures[5].downcase != 'w' ? lon = captures[6].to_f + (captures[7].to_f + captures[8].to_f/60)/60 : lon = -(captures[6].to_f + (captures[7].to_f + captures[8].to_f/60)/60)
+ captures[0].downcase != 's' ? lat = captures[1].to_f + (captures[2].to_f + captures[3].to_f / 60) / 60 : lat = -(captures[1].to_f + (captures[2].to_f + captures[3].to_f / 60) / 60)
+ captures[5].downcase != 'w' ? lon = captures[6].to_f + (captures[7].to_f + captures[8].to_f / 60) / 60 : lon = -(captures[6].to_f + (captures[7].to_f + captures[8].to_f / 60) / 60)
end
- {:lat => lat, :lon => lon}
+ { :lat => lat, :lon => lon }
end
-
end
def reply
message = Message.find(params[:message_id])
- if message.to_user_id == @user.id then
+ if message.to_user_id == @user.id
message.update_attribute(:message_read, true)
@message = Message.new(
:recipient => message.sender,
:title => "Re: #{message.title.sub(/^Re:\s*/, '')}",
- :body => "On #{message.sent_on} #{message.sender.display_name} wrote:\n\n#{message.body.gsub(/^/, '> ')}",
+ :body => "On #{message.sent_on} #{message.sender.display_name} wrote:\n\n#{message.body.gsub(/^/, '> ')}"
)
@title = @message.title
redirect_to :controller => "user", :action => "login", :referer => request.fullpath
end
rescue ActiveRecord::RecordNotFound
- @title = t'message.no_such_message.title'
+ @title = t 'message.no_such_message.title'
render :action => 'no_such_message', :status => :not_found
end
@title = t 'message.read.title'
@message = Message.find(params[:message_id])
- if @message.to_user_id == @user.id or @message.from_user_id == @user.id then
+ if @message.to_user_id == @user.id || @message.from_user_id == @user.id
@message.message_read = true if @message.to_user_id == @user.id
@message.save
else
redirect_to :controller => "user", :action => "login", :referer => request.fullpath
end
rescue ActiveRecord::RecordNotFound
- @title = t'message.no_such_message.title'
+ @title = t 'message.no_such_message.title'
render :action => 'no_such_message', :status => :not_found
end
# Display the list of messages that have been sent to the user.
def inbox
@title = t 'message.inbox.title'
- if @user and params[:display_name] == @user.display_name
+ if @user && params[:display_name] == @user.display_name
else
redirect_to :controller => 'message', :action => 'inbox', :display_name => @user.display_name
end
# Display the list of messages that the user has sent to other users.
def outbox
@title = t 'message.outbox.title'
- if @user and params[:display_name] == @user.display_name
+ if @user && params[:display_name] == @user.display_name
else
redirect_to :controller => 'message', :action => 'outbox', :display_name => @user.display_name
end
notice = t 'message.mark.as_read'
end
@message.message_read = message_read
- if @message.save and not request.xhr?
+ if @message.save && !request.xhr?
flash[:notice] = notice
redirect_to :controller => 'message', :action => 'inbox', :display_name => @user.display_name
end
rescue ActiveRecord::RecordNotFound
- @title = t'message.no_such_message.title'
+ @title = t 'message.no_such_message.title'
render :action => 'no_such_message', :status => :not_found
end
@message = Message.where("to_user_id = ? OR from_user_id = ?", @user.id, @user.id).find(params[:message_id])
@message.from_user_visible = false if @message.sender == @user
@message.to_user_visible = false if @message.recipient == @user
- if @message.save and not request.xhr?
+ if @message.save && !request.xhr?
flash[:notice] = t 'message.delete.deleted'
if params[:referer]
end
end
rescue ActiveRecord::RecordNotFound
- @title = t'message.no_such_message.title'
+ @title = t 'message.no_such_message.title'
render :action => 'no_such_message', :status => :not_found
end
-private
+
+ private
+
##
# return permitted message parameters
def message_params
node = Node.find(params[:id])
new_node = Node.from_xml(request.raw_post)
- unless new_node and new_node.id == node.id
- raise OSM::APIBadUserInput.new("The id in the url (#{node.id}) is not the same as provided in the xml (#{new_node.id})")
+ unless new_node && new_node.id == node.id
+ fail OSM::APIBadUserInput.new("The id in the url (#{node.id}) is not the same as provided in the xml (#{new_node.id})")
end
node.update_from(new_node, @user)
render :text => node.version.to_s, :content_type => "text/plain"
node = Node.find(params[:id])
new_node = Node.from_xml(request.raw_post)
- unless new_node and new_node.id == node.id
- raise OSM::APIBadUserInput.new("The id in the url (#{node.id}) is not the same as provided in the xml (#{new_node.id})")
+ unless new_node && new_node.id == node.id
+ fail OSM::APIBadUserInput.new("The id in the url (#{node.id}) is not the same as provided in the xml (#{new_node.id})")
end
node.delete_with_history!(new_node, @user)
render :text => node.version.to_s, :content_type => "text/plain"
# Dump the details on many nodes whose ids are given in the "nodes" parameter.
def nodes
- if not params['nodes']
- raise OSM::APIBadUserInput.new("The parameter nodes is required, and must be of the form nodes=id[,id[,id...]]")
+ unless params['nodes']
+ fail OSM::APIBadUserInput.new("The parameter nodes is required, and must be of the form nodes=id[,id[,id...]]")
end
- ids = params['nodes'].split(',').collect { |n| n.to_i }
+ ids = params['nodes'].split(',').collect(&:to_i)
if ids.length == 0
- raise OSM::APIBadUserInput.new("No nodes were given to search for")
+ fail OSM::APIBadUserInput.new("No nodes were given to search for")
end
doc = OSM::API.new.get_xml_doc
class NotesController < ApplicationController
-
layout 'site', :only => [:mine]
before_filter :check_api_readable
if params[:bbox]
bbox = BoundingBox.from_bbox_params(params)
else
- raise OSM::APIBadUserInput.new("No l was given") unless params[:l]
- raise OSM::APIBadUserInput.new("No r was given") unless params[:r]
- raise OSM::APIBadUserInput.new("No b was given") unless params[:b]
- raise OSM::APIBadUserInput.new("No t was given") unless params[:t]
+ fail OSM::APIBadUserInput.new("No l was given") unless params[:l]
+ fail OSM::APIBadUserInput.new("No r was given") unless params[:r]
+ fail OSM::APIBadUserInput.new("No b was given") unless params[:b]
+ fail OSM::APIBadUserInput.new("No t was given") unless params[:t]
bbox = BoundingBox.from_lrbt_params(params)
end
# Create a new note
def create
# Check the ACLs
- raise OSM::APIAccessDenied if Acl.no_note_comment(request.remote_ip)
+ fail OSM::APIAccessDenied if Acl.no_note_comment(request.remote_ip)
# Check the arguments are sane
- raise OSM::APIBadUserInput.new("No lat was given") unless params[:lat]
- raise OSM::APIBadUserInput.new("No lon was given") unless params[:lon]
- raise OSM::APIBadUserInput.new("No text was given") if params[:text].blank?
+ fail OSM::APIBadUserInput.new("No lat was given") unless params[:lat]
+ fail OSM::APIBadUserInput.new("No lon was given") unless params[:lon]
+ fail OSM::APIBadUserInput.new("No text was given") if params[:text].blank?
# Extract the arguments
lon = OSM.parse_float(params[:lon], OSM::APIBadUserInput, "lon was not a number")
Note.transaction do
# Create the note
@note = Note.create(:lat => lat, :lon => lon)
- raise OSM::APIBadUserInput.new("The note is outside this world") unless @note.in_world?
+ fail OSM::APIBadUserInput.new("The note is outside this world") unless @note.in_world?
# Save the note
@note.save!
# Add a comment to an existing note
def comment
# Check the ACLs
- raise OSM::APIAccessDenied if Acl.no_note_comment(request.remote_ip)
+ fail OSM::APIAccessDenied if Acl.no_note_comment(request.remote_ip)
# Check the arguments are sane
- raise OSM::APIBadUserInput.new("No id was given") unless params[:id]
- raise OSM::APIBadUserInput.new("No text was given") if params[:text].blank?
+ fail OSM::APIBadUserInput.new("No id was given") unless params[:id]
+ fail OSM::APIBadUserInput.new("No text was given") if params[:text].blank?
# Extract the arguments
id = params[:id].to_i
# Find the note and check it is valid
@note = Note.find(id)
- raise OSM::APINotFoundError unless @note
- raise OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible?
- raise OSM::APINoteAlreadyClosedError.new(@note) if @note.closed?
+ fail OSM::APINotFoundError unless @note
+ fail OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible?
+ fail OSM::APINoteAlreadyClosedError.new(@note) if @note.closed?
# Add a comment to the note
Note.transaction do
# Close a note
def close
# Check the arguments are sane
- raise OSM::APIBadUserInput.new("No id was given") unless params[:id]
+ fail OSM::APIBadUserInput.new("No id was given") unless params[:id]
# Extract the arguments
id = params[:id].to_i
# Find the note and check it is valid
@note = Note.find_by_id(id)
- raise OSM::APINotFoundError unless @note
- raise OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible?
- raise OSM::APINoteAlreadyClosedError.new(@note) if @note.closed?
+ fail OSM::APINotFoundError unless @note
+ fail OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible?
+ fail OSM::APINoteAlreadyClosedError.new(@note) if @note.closed?
# Close the note and add a comment
Note.transaction do
# Reopen a note
def reopen
# Check the arguments are sane
- raise OSM::APIBadUserInput.new("No id was given") unless params[:id]
+ fail OSM::APIBadUserInput.new("No id was given") unless params[:id]
# Extract the arguments
id = params[:id].to_i
# Find the note and check it is valid
@note = Note.find_by_id(id)
- raise OSM::APINotFoundError unless @note
- raise OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible? or @user.moderator?
- raise OSM::APINoteAlreadyOpenError.new(@note) unless @note.closed? or not @note.visible?
+ fail OSM::APINotFoundError unless @note
+ fail OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible? || @user.moderator?
+ fail OSM::APINoteAlreadyOpenError.new(@note) unless @note.closed? || !@note.visible?
# Reopen the note and add a comment
Note.transaction do
# Read a note
def show
# Check the arguments are sane
- raise OSM::APIBadUserInput.new("No id was given") unless params[:id]
+ fail OSM::APIBadUserInput.new("No id was given") unless params[:id]
# Find the note and check it is valid
@note = Note.find(params[:id])
- raise OSM::APINotFoundError unless @note
- raise OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible?
+ fail OSM::APINotFoundError unless @note
+ fail OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible?
# Render the result
respond_to do |format|
# Delete (hide) a note
def destroy
# Check the arguments are sane
- raise OSM::APIBadUserInput.new("No id was given") unless params[:id]
+ fail OSM::APIBadUserInput.new("No id was given") unless params[:id]
# Extract the arguments
id = params[:id].to_i
# Find the note and check it is valid
@note = Note.find(id)
- raise OSM::APINotFoundError unless @note
- raise OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible?
+ fail OSM::APINotFoundError unless @note
+ fail OSM::APIAlreadyDeletedError.new("note", @note.id) unless @note.visible?
# Mark the note as hidden
Note.transaction do
# Return a list of notes matching a given string
def search
# Check the arguments are sane
- raise OSM::APIBadUserInput.new("No query string was given") unless params[:q]
+ fail OSM::APIBadUserInput.new("No query string was given") unless params[:q]
# Get any conditions that need to be applied
@notes = closed_condition(Note.all)
end
end
-private
+ private
+
#------------------------------------------------------------
# utility functions below.
#------------------------------------------------------------
# Get the maximum number of results to return
def result_limit
if params[:limit]
- if params[:limit].to_i > 0 and params[:limit].to_i <= 10000
+ if params[:limit].to_i > 0 && params[:limit].to_i <= 10000
params[:limit].to_i
else
- raise OSM::APIBadUserInput.new("Note limit must be between 1 and 10000")
+ fail OSM::APIBadUserInput.new("Note limit must be between 1 and 10000")
end
else
100
notes = notes.where("status = 'open'")
end
- return notes
+ notes
end
##
comment = note.comments.create(attributes)
- note.comments.map { |c| c.author }.uniq.each do |user|
- if notify and user and user != @user
+ note.comments.map(&:author).uniq.each do |user|
+ if notify && user && user != @user
Notifier.note_comment_notification(comment, user).deliver_now
end
end
def create
@client_application = @user.client_applications.build(application_params)
if @client_application.save
- flash[:notice] = t'oauth_clients.create.flash'
+ flash[:notice] = t 'oauth_clients.create.flash'
redirect_to :action => "show", :id => @client_application.id
else
render :action => "new"
def update
@client_application = @user.client_applications.find(params[:id])
if @client_application.update_attributes(application_params)
- flash[:notice] = t'oauth_clients.update.flash'
+ flash[:notice] = t 'oauth_clients.update.flash'
redirect_to :action => "show", :id => @client_application.id
else
render :action => "edit"
def destroy
@client_application = @user.client_applications.find(params[:id])
@client_application.destroy
- flash[:notice] = t'oauth_clients.destroy.flash'
+ flash[:notice] = t 'oauth_clients.destroy.flash'
redirect_to :action => "index"
rescue ActiveRecord::RecordNotFound
@type = "client application"
render :action => "not_found", :status => :not_found
end
-private
+
+ private
+
def application_params
params.require(:client_application).permit(:name, :url, :callback_url, :support_url, ClientApplication.all_permissions)
end
redirect_to oauth_clients_url(:display_name => @token.user.display_name)
end
-protected
+ protected
def oauth1_authorize
unless @token
- render :action=>"authorize_failure"
+ render :action => "authorize_failure"
return
end
require 'xml/libxml'
skip_before_filter :verify_authenticity_token
- before_filter :setup_user_auth, :only => [ :history, :version ]
- before_filter :authorize, :only => [ :redact ]
- before_filter :authorize_moderator, :only => [ :redact ]
- before_filter :require_allow_write_api, :only => [ :redact ]
+ before_filter :setup_user_auth, :only => [:history, :version]
+ before_filter :authorize, :only => [:redact]
+ before_filter :authorize_moderator, :only => [:redact]
+ before_filter :require_allow_write_api, :only => [:redact]
before_filter :check_api_readable
- before_filter :check_api_writable, :only => [ :redact ]
+ before_filter :check_api_writable, :only => [:redact]
after_filter :compress_output
around_filter :api_call_handle_error, :api_call_timeout
- before_filter :lookup_old_element, :except => [ :history ]
- before_filter :lookup_old_element_versions, :only => [ :history ]
+ before_filter :lookup_old_element, :except => [:history]
+ before_filter :lookup_old_element_versions, :only => [:history]
def history
# the .where() method used in the lookup_old_element_versions
# call won't throw an error if no records are found, so we have
# to do that ourselves.
- raise OSM::APINotFoundError.new if @elements.empty?
+ fail OSM::APINotFoundError.new if @elements.empty?
doc = OSM::API.new.get_xml_doc
end
def version
- if @old_element.redacted? and not show_redactions?
+ if @old_element.redacted? && !show_redactions?
render :text => "", :status => :forbidden
else
private
def show_redactions?
- @user and @user.moderator? and params[:show_redactions] == "true"
+ @user && @user.moderator? && params[:show_redactions] == "true"
end
end
class OldNodeController < OldController
-
private
def lookup_old_element
class OldRelationController < OldController
-
private
def lookup_old_element
class OldWayController < OldController
-
private
def lookup_old_element
end
def destroy
- unless @redaction.old_nodes.empty? and
- @redaction.old_ways.empty? and
- @redaction.old_relations.empty?
+ unless @redaction.old_nodes.empty? &&
+ @redaction.old_ways.empty? &&
+ @redaction.old_relations.empty?
flash[:error] = t('redaction.destroy.not_empty')
redirect_to @redaction
else
# We assume that an exception has been thrown if there was an error
# generating the relation
- #if relation
+ # if relation
relation.create_with_history @user
render :text => relation.id.to_s, :content_type => "text/plain"
- #else
+ # else
# render :text => "Couldn't get turn the input into a relation.", :status => :bad_request
- #end
+ # end
end
def read
relation = Relation.find(params[:id])
new_relation = Relation.from_xml(request.raw_post)
- if new_relation and new_relation.id == relation.id
+ if new_relation && new_relation.id == relation.id
relation.update_from new_relation, @user
render :text => relation.version.to_s, :content_type => "text/plain"
else
def delete
relation = Relation.find(params[:id])
new_relation = Relation.from_xml(request.raw_post)
- if new_relation and new_relation.id == relation.id
+ if new_relation && new_relation.id == relation.id
relation.delete_with_history!(new_relation, @user)
render :text => relation.version.to_s, :content_type => "text/plain"
else
node_ids = relation.members.select { |m| m[0] == 'Node' }.map { |m| m[1] }
way_ids = relation.members.select { |m| m[0] == 'Way' }.map { |m| m[1] }
- relation_ids = relation.members.select { |m| m[0] == 'Relation' and m[1] != relation.id }.map { |m| m[1] }
+ relation_ids = relation.members.select { |m| m[0] == 'Relation' && m[1] != relation.id }.map { |m| m[1] }
# next load the relations and the ways.
# now additionally collect nodes referenced by ways. Note how we
# recursively evaluate ways but NOT relations.
- way_node_ids = ways.collect { |way|
- way.way_nodes.collect { |way_node| way_node.node_id }
- }
+ way_node_ids = ways.collect do |way|
+ way.way_nodes.collect(&:node_id)
+ end
node_ids += way_node_ids.flatten
nodes = Node.where(:id => node_ids.uniq).includes(:node_tags)
end
def relations
- if not params['relations']
- raise OSM::APIBadUserInput.new("The parameter relations is required, and must be of the form relations=id[,id[,id...]]")
+ unless params['relations']
+ fail OSM::APIBadUserInput.new("The parameter relations is required, and must be of the form relations=id[,id[,id...]]")
end
- ids = params['relations'].split(',').collect { |w| w.to_i }
+ ids = params['relations'].split(',').collect(&:to_i)
if ids.length == 0
- raise OSM::APIBadUserInput.new("No relations were given to search for")
+ fail OSM::APIBadUserInput.new("No relations were given to search for")
end
doc = OSM::API.new.get_xml_doc
end
def relations_for_object(objtype)
- relationids = RelationMember.where(:member_type => objtype, :member_id => params[:id]).collect { |ws| ws.relation_id }.uniq
+ relationids = RelationMember.where(:member_type => objtype, :member_id => params[:id]).collect(&:relation_id).uniq
doc = OSM::API.new.get_xml_doc
after_filter :compress_output
def search_all
- do_search(true,true,true)
+ do_search(true, true, true)
end
def search_ways
- do_search(true,false,false)
+ do_search(true, false, false)
end
+
def search_nodes
- do_search(false,true,false)
+ do_search(false, true, false)
end
+
def search_relations
- do_search(false,false,true)
+ do_search(false, false, true)
end
- def do_search(do_ways,do_nodes,do_relations)
+ def do_search(do_ways, do_nodes, do_relations)
type = params['type']
value = params['value']
- unless type or value
+ unless type || value
name = params['name']
if name
type = 'name'
nodes = nodes.where(:current_node_tags => { :v => value }) if value
nodes = nodes.limit(100)
else
- nodes = Array.new
+ nodes = []
end
# Matching for way tags table
ways = ways.where(:current_way_tags => { :v => value }) if value
ways = ways.limit(100)
else
- ways = Array.new
+ ways = []
end
# Matching for relation tags table
relations = relations.where(:current_relation_tags => { :v => value }) if value
relations = relations.limit(2000)
else
- relations = Array.new
+ relations = []
end
# Fetch any node needed for our ways (only have matching nodes so far)
- nodes += Node.find(ways.collect { |w| w.nds }.uniq)
+ nodes += Node.find(ways.collect(&:nds).uniq)
# Print
visible_nodes = {}
before_filter :require_oauth, :only => [:index]
def index
- unless STATUS == :database_readonly or STATUS == :database_offline
+ unless STATUS == :database_readonly || STATUS == :database_offline
session[:location] ||= OSM::IPLocation(request.env['REMOTE_ADDR'])
end
end
def permalink
- lon, lat, zoom = ShortLink::decode(params[:code])
+ lon, lat, zoom = ShortLink.decode(params[:code])
new_params = params.except(:code, :lon, :lat, :zoom, :layers, :node, :way, :relation, :changeset)
- if new_params.has_key? :m
+ if new_params.key? :m
new_params.delete :m
new_params[:mlat] = lat
new_params[:mlon] = lon
end
- if params.has_key? :node
+ if params.key? :node
new_params[:controller] = 'browse'
new_params[:action] = 'node'
new_params[:id] = params[:node]
- elsif params.has_key? :way
+ elsif params.key? :way
new_params[:controller] = 'browse'
new_params[:action] = 'way'
new_params[:id] = params[:way]
- elsif params.has_key? :relation
+ elsif params.key? :relation
new_params[:controller] = 'browse'
new_params[:action] = 'relation'
new_params[:id] = params[:relation]
- elsif params.has_key? :changeset
+ elsif params.key? :changeset
new_params[:controller] = 'browse'
new_params[:action] = 'changeset'
new_params[:id] = params[:changeset]
new_params[:anchor] = "map=#{zoom}/#{lat}/#{lon}"
- if params.has_key? :layers
+ if params.key? :layers
new_params[:anchor] += "&layers=#{params[:layers]}"
end
class SwfController < ApplicationController
- skip_before_filter :verify_authenticity_token
- before_filter :check_api_readable
-
-# to log:
-# RAILS_DEFAULT_LOGGER.error("Args: #{args[0]}, #{args[1]}, #{args[2]}, #{args[3]}")
-# $log.puts Time.new.to_s+','+Time.new.usec.to_s+": started GPS script"
-# http://localhost:3000/api/0.4/swf/trackpoints?xmin=-2.32402605810577&xmax=-2.18386309423859&ymin=52.1546608755772&ymax=52.2272777906895&baselong=-2.25325793066437&basey=61.3948537948532&masterscale=5825.4222222222
-
-
- # ====================================================================
- # Public methods
-
- # ---- trackpoints compile SWF of trackpoints
-
- def trackpoints
-
- # - Initialise
-
- baselong =params['baselong'].to_f
- basey =params['basey'].to_f
- masterscale =params['masterscale'].to_f
-
- bbox = BoundingBox.new(params['xmin'], params['ymin'],
- params['xmax'], params['ymax'])
- start=params['start'].to_i;
-
- # - Begin movie
-
- bounds_left =0
- bounds_right =320*20
- bounds_bottom=0
- bounds_top =240*20
-
- m =''
- m+=swfRecord(9,255.chr + 155.chr + 155.chr) # Background
- absx=0
- absy=0
- xl=yb= 9999999
- xr=yt=-9999999
-
- # - Send SQL for GPS tracks
-
- b=''
- lasttime=0
- lasttrack=lastfile='-1'
-
- if params['token']
- user=User.authenticate(:token => params[:token])
- sql="SELECT gps_points.latitude*0.0000001 AS lat,gps_points.longitude*0.0000001 AS lon,gpx_files.id AS fileid,"+
- " EXTRACT(EPOCH FROM gps_points.timestamp) AS ts, gps_points.trackid AS trackid "+
- " FROM gpx_files,gps_points "+
- "WHERE gpx_files.id=gpx_id "+
- " AND gpx_files.user_id=#{user.id} "+
- " AND "+OSM.sql_for_area(bbox,"gps_points.")+
- " AND (gps_points.timestamp IS NOT NULL) "+
- "ORDER BY fileid DESC,ts "+
- "LIMIT 10000 OFFSET #{start}"
- else
- sql="SELECT latitude*0.0000001 AS lat,longitude*0.0000001 AS lon,gpx_id AS fileid,"+
- " EXTRACT(EPOCH FROM timestamp) AS ts, gps_points.trackid AS trackid "+
- " FROM gps_points "+
- "WHERE "+OSM.sql_for_area(bbox,"gps_points.")+
- " AND (gps_points.timestamp IS NOT NULL) "+
- "ORDER BY fileid DESC,ts "+
- "LIMIT 10000 OFFSET #{start}"
- end
- gpslist=ActiveRecord::Base.connection.select_all sql
-
- # - Draw GPS trace lines
-
- r=startShape()
- gpslist.each do |row|
- xs=(long2coord(row['lon'].to_f,baselong,masterscale)*20).floor
- ys=(lat2coord(row['lat'].to_f ,basey ,masterscale)*20).floor
- xl=[xs,xl].min; xr=[xs,xr].max
- yb=[ys,yb].min; yt=[ys,yt].max
- if row['ts'].to_i-lasttime>180 or row['fileid']!=lastfile or row['trackid']!=lasttrack #or row['ts'].to_i==lasttime
- b+=startAndMove(xs,ys,'01')
- absx=xs.floor; absy=ys.floor
+ skip_before_filter :verify_authenticity_token
+ before_filter :check_api_readable
+
+ # to log:
+ # RAILS_DEFAULT_LOGGER.error("Args: #{args[0]}, #{args[1]}, #{args[2]}, #{args[3]}")
+ # $log.puts Time.new.to_s+','+Time.new.usec.to_s+": started GPS script"
+ # http://localhost:3000/api/0.4/swf/trackpoints?xmin=-2.32402605810577&xmax=-2.18386309423859&ymin=52.1546608755772&ymax=52.2272777906895&baselong=-2.25325793066437&basey=61.3948537948532&masterscale=5825.4222222222
+
+ # ====================================================================
+ # Public methods
+
+ # ---- trackpoints compile SWF of trackpoints
+
+ def trackpoints
+ # - Initialise
+
+ baselong = params['baselong'].to_f
+ basey = params['basey'].to_f
+ masterscale = params['masterscale'].to_f
+
+ bbox = BoundingBox.new(params['xmin'], params['ymin'],
+ params['xmax'], params['ymax'])
+ start = params['start'].to_i
+
+ # - Begin movie
+
+ bounds_left = 0
+ bounds_right = 320 * 20
+ bounds_bottom = 0
+ bounds_top = 240 * 20
+
+ m = ''
+ m += swfRecord(9, 255.chr + 155.chr + 155.chr) # Background
+ absx = 0
+ absy = 0
+ xl = yb = 9999999
+ xr = yt = -9999999
+
+ # - Send SQL for GPS tracks
+
+ b = ''
+ lasttime = 0
+ lasttrack = lastfile = '-1'
+
+ if params['token']
+ user = User.authenticate(:token => params[:token])
+ sql = "SELECT gps_points.latitude*0.0000001 AS lat,gps_points.longitude*0.0000001 AS lon,gpx_files.id AS fileid," + " EXTRACT(EPOCH FROM gps_points.timestamp) AS ts, gps_points.trackid AS trackid " + " FROM gpx_files,gps_points " + "WHERE gpx_files.id=gpx_id " + " AND gpx_files.user_id=#{user.id} " + " AND " + OSM.sql_for_area(bbox, "gps_points.") + " AND (gps_points.timestamp IS NOT NULL) " + "ORDER BY fileid DESC,ts " + "LIMIT 10000 OFFSET #{start}"
+ else
+ sql = "SELECT latitude*0.0000001 AS lat,longitude*0.0000001 AS lon,gpx_id AS fileid," + " EXTRACT(EPOCH FROM timestamp) AS ts, gps_points.trackid AS trackid " + " FROM gps_points " + "WHERE " + OSM.sql_for_area(bbox, "gps_points.") + " AND (gps_points.timestamp IS NOT NULL) " + "ORDER BY fileid DESC,ts " + "LIMIT 10000 OFFSET #{start}"
+ end
+ gpslist = ActiveRecord::Base.connection.select_all sql
+
+ # - Draw GPS trace lines
+
+ r = startShape
+ gpslist.each do |row|
+ xs = (long2coord(row['lon'].to_f, baselong, masterscale) * 20).floor
+ ys = (lat2coord(row['lat'].to_f, basey, masterscale) * 20).floor
+ xl = [xs, xl].min; xr = [xs, xr].max
+ yb = [ys, yb].min; yt = [ys, yt].max
+ if row['ts'].to_i - lasttime > 180 || row['fileid'] != lastfile || row['trackid'] != lasttrack # or row['ts'].to_i==lasttime
+ b += startAndMove(xs, ys, '01')
+ absx = xs.floor; absy = ys.floor
+ end
+ b += drawTo(absx, absy, xs, ys)
+ absx = xs.floor; absy = ys.floor
+ lasttime = row['ts'].to_i
+ lastfile = row['fileid']
+ lasttrack = row['trackid']
+ while b.length > 80
+ r += [b.slice!(0...80)].pack("B*")
end
- b+=drawTo(absx,absy,xs,ys)
- absx=xs.floor; absy=ys.floor
- lasttime=row['ts'].to_i
- lastfile=row['fileid']
- lasttrack=row['trackid']
- while b.length>80 do
- r+=[b.slice!(0...80)].pack("B*")
- end
- end
+ end
- # (Unwayed segments removed)
+ # (Unwayed segments removed)
- # - Write shape
+ # - Write shape
- b+=endShape()
- r+=[b].pack("B*")
- m+=swfRecord(2,packUI16(1) + packRect(xl,xr,yb,yt) + r)
- m+=swfRecord(4,packUI16(1) + packUI16(1))
+ b += endShape
+ r += [b].pack("B*")
+ m += swfRecord(2, packUI16(1) + packRect(xl, xr, yb, yt) + r)
+ m += swfRecord(4, packUI16(1) + packUI16(1))
- # - Create Flash header and write to browser
+ # - Create Flash header and write to browser
- m+=swfRecord(1,'') # Show frame
- m+=swfRecord(0,'') # End
+ m += swfRecord(1, '') # Show frame
+ m += swfRecord(0, '') # End
- m=packRect(bounds_left,bounds_right,bounds_bottom,bounds_top) + 0.chr + 12.chr + packUI16(1) + m
- m='FWS' + 6.chr + packUI32(m.length+8) + m
+ m = packRect(bounds_left, bounds_right, bounds_bottom, bounds_top) + 0.chr + 12.chr + packUI16(1) + m
+ m = 'FWS' + 6.chr + packUI32(m.length + 8) + m
- render :text => m, :content_type => "application/x-shockwave-flash"
- end
+ render :text => m, :content_type => "application/x-shockwave-flash"
+ end
- private
+ private
- # =======================================================================
- # SWF functions
+ # =======================================================================
+ # SWF functions
- # -----------------------------------------------------------------------
- # Line-drawing
+ # -----------------------------------------------------------------------
+ # Line-drawing
- def startShape
- s =0.chr # No fill styles
- s+=2.chr # Two line styles
- s+=packUI16(0) + 0.chr + 255.chr + 255.chr # Width 5, RGB #00FFFF
- s+=packUI16(0) + 255.chr + 0.chr + 255.chr # Width 5, RGB #FF00FF
- s+=34.chr # 2 fill, 2 line index bits
- s
- end
+ def startShape
+ s = 0.chr # No fill styles
+ s += 2.chr # Two line styles
+ s += packUI16(0) + 0.chr + 255.chr + 255.chr # Width 5, RGB #00FFFF
+ s += packUI16(0) + 255.chr + 0.chr + 255.chr # Width 5, RGB #FF00FF
+ s += 34.chr # 2 fill, 2 line index bits
+ s
+ end
- def endShape
- '000000'
- end
+ def endShape
+ '000000'
+ end
- def startAndMove(x,y,col)
- d='001001' # Line style change, moveTo
- l =[lengthSB(x),lengthSB(y)].max
- d+=sprintf("%05b%0#{l}b%0#{l}b",l,x,y)
- d+=col # Select line style
- end
+ def startAndMove(x, y, col)
+ d = '001001' # Line style change, moveTo
+ l = [lengthSB(x), lengthSB(y)].max
+ d += sprintf("%05b%0#{l}b%0#{l}b", l, x, y)
+ d += col # Select line style
+ end
- def drawTo(absx,absy,x,y)
- dx=x-absx
- dy=y-absy
+ def drawTo(absx, absy, x, y)
+ dx = x - absx
+ dy = y - absy
# Split the line up if there's anything>16383, because
# that would overflow the 4 bits allowed for length
- mstep=[dx.abs/16383,dy.abs/16383,1].max.ceil
- xstep=dx/mstep
- ystep=dy/mstep
- d=''
+ mstep = [dx.abs / 16383, dy.abs / 16383, 1].max.ceil
+ xstep = dx / mstep
+ ystep = dy / mstep
+ d = ''
for i in (1..mstep)
- d+=drawSection(x,y,x+xstep,y+ystep)
- x+=xstep
- y+=ystep
+ d += drawSection(x, y, x + xstep, y + ystep)
+ x += xstep
+ y += ystep
end
d
- end
-
- def drawSection(x1,y1,x2,y2)
- d='11' # TypeFlag, EdgeFlag
- dx=x2-x1
- dy=y2-y1
- l =[lengthSB(dx),lengthSB(dy)].max
- d+=sprintf("%04b",l-2)
- d+='1' # GeneralLine
- d+=sprintf("%0#{l}b%0#{l}b",dx,dy)
end
- # -----------------------------------------------------------------------
- # Specific data types
+ def drawSection(x1, y1, x2, y2)
+ d = '11' # TypeFlag, EdgeFlag
+ dx = x2 - x1
+ dy = y2 - y1
+ l = [lengthSB(dx), lengthSB(dy)].max
+ d += sprintf("%04b", l - 2)
+ d += '1' # GeneralLine
+ d += sprintf("%0#{l}b%0#{l}b", dx, dy)
+ end
+
+ # -----------------------------------------------------------------------
+ # Specific data types
# SWF data block type
- def swfRecord(id,r)
- if r.length>62
+ def swfRecord(id, r)
+ if r.length > 62
# Long header: tag id, 0x3F, length
- return packUI16((id<<6)+0x3F) + packUI32(r.length) + r
- else
+ return packUI16((id << 6) + 0x3F) + packUI32(r.length) + r
+ else
# Short header: tag id, length
- return packUI16((id<<6)+r.length) + r
- end
- end
+ return packUI16((id << 6) + r.length) + r
+ end
+ end
# SWF RECT type
- def packRect(a,b,c,d)
- l=[lengthSB(a),
- lengthSB(b),
- lengthSB(c),
- lengthSB(d)].max
+ def packRect(a, b, c, d)
+ l = [lengthSB(a),
+ lengthSB(b),
+ lengthSB(c),
+ lengthSB(d)].max
# create binary string (00111001 etc.) - 5-byte length, then bbox
- n=sprintf("%05b%0#{l}b%0#{l}b%0#{l}b%0#{l}b",l,a,b,c,d)
+ n = sprintf("%05b%0#{l}b%0#{l}b%0#{l}b%0#{l}b", l, a, b, c, d)
# pack into byte string
- [n].pack("B*")
- end
-
- # -----------------------------------------------------------------------
- # Generic pack functions
+ [n].pack("B*")
+ end
- def packUI16(n)
- [n.floor].pack("v")
- end
+ # -----------------------------------------------------------------------
+ # Generic pack functions
- def packUI32(n)
- [n.floor].pack("V")
- end
+ def packUI16(n)
+ [n.floor].pack("v")
+ end
- # Find number of bits required to store arbitrary-length binary
+ def packUI32(n)
+ [n.floor].pack("V")
+ end
- def lengthSB(n)
- Math.frexp(n+ (n==0?1:0) )[1]+1
- end
+ # Find number of bits required to store arbitrary-length binary
- # ====================================================================
- # Co-ordinate conversion
- # (this is duplicated from amf_controller, should probably share)
+ def lengthSB(n)
+ Math.frexp(n + (n == 0 ? 1 : 0))[1] + 1
+ end
- def lat2coord(a,basey,masterscale)
- -(lat2y(a)-basey)*masterscale
- end
+ # ====================================================================
+ # Co-ordinate conversion
+ # (this is duplicated from amf_controller, should probably share)
- def long2coord(a,baselong,masterscale)
- (a-baselong)*masterscale
- end
+ def lat2coord(a, basey, masterscale)
+ -(lat2y(a) - basey) * masterscale
+ end
- def lat2y(a)
- 180/Math::PI * Math.log(Math.tan(Math::PI/4+a*(Math::PI/180)/2))
- end
+ def long2coord(a, baselong, masterscale)
+ (a - baselong) * masterscale
+ end
- def sqlescape(a)
- a.gsub("'","''").gsub(92.chr,92.chr+92.chr)
- end
+ def lat2y(a)
+ 180 / Math::PI * Math.log(Math.tan(Math::PI / 4 + a * (Math::PI / 180) / 2))
+ end
+ def sqlescape(a)
+ a.gsub("'", "''").gsub(92.chr, 92.chr + 92.chr)
+ end
end
def list
# from display name, pick up user id if one user's traces only
display_name = params[:display_name]
- if !display_name.blank?
+ unless display_name.blank?
target_user = User.active.where(:display_name => display_name).first
if target_user.nil?
render_unknown_user display_name
# set title
if target_user.nil?
@title = t 'trace.list.public_traces'
- elsif @user and @user == target_user
+ elsif @user && @user == target_user
@title = t 'trace.list.your_traces'
else
@title = t 'trace.list.public_traces_from', :user => target_user.display_name
# 4 - user's traces, not logged in as that user = all user's public traces
if target_user.nil? # all traces
if @user
- @traces = Trace.visible_to(@user) #1
+ @traces = Trace.visible_to(@user) # 1
else
- @traces = Trace.visible_to_all #2
+ @traces = Trace.visible_to_all # 2
end
else
- if @user and @user == target_user
- @traces = @user.traces #3 (check vs user id, so no join + can't pick up non-public traces by changing name)
+ if @user && @user == target_user
+ @traces = @user.traces # 3 (check vs user id, so no join + can't pick up non-public traces by changing name)
else
- @traces = target_user.traces.visible_to_all #4
+ @traces = target_user.traces.visible_to_all # 4
end
end
@traces = @traces.includes(:user, :tags)
# put together SET of tags across traces, for related links
- tagset = Hash.new
+ tagset = {}
@traces.each do |trace|
trace.tags.reload if params[:tag] # if searched by tag, ActiveRecord won't bring back other tags, so do explicitly here
trace.tags.each do |tag|
def view
@trace = Trace.find(params[:id])
- if @trace and @trace.visible? and
- (@trace.public? or @trace.user == @user)
+ if @trace && @trace.visible? &&
+ (@trace.public? || @trace.user == @user)
@title = t 'trace.view.title', :name => @trace.name
else
flash[:error] = t 'trace.view.trace_not_found'
redirect_to :action => :list, :display_name => @user.display_name
end
else
- @trace = Trace.new({:name => "Dummy",
- :tagstring => params[:trace][:tagstring],
- :description => params[:trace][:description],
- :visibility => params[:trace][:visibility],
- :inserted => false, :user => @user,
- :timestamp => Time.now.getutc})
+ @trace = Trace.new(:name => "Dummy",
+ :tagstring => params[:trace][:tagstring],
+ :description => params[:trace][:description],
+ :visibility => params[:trace][:visibility],
+ :inserted => false, :user => @user,
+ :timestamp => Time.now.getutc)
@trace.valid?
@trace.errors.add(:gpx_file, "can't be blank")
end
def data
trace = Trace.find(params[:id])
- if trace.visible? and (trace.public? or (@user and @user == trace.user))
+ if trace.visible? && (trace.public? || (@user && @user == trace.user))
if Acl.no_trace_download(request.remote_ip)
render :text => "", :status => :forbidden
elsif request.format == Mime::XML
def edit
@trace = Trace.find(params[:id])
- if not @trace.visible?
+ if !@trace.visible?
render :text => "", :status => :not_found
- elsif @user.nil? or @trace.user != @user
+ elsif @user.nil? || @trace.user != @user
render :text => "", :status => :forbidden
else
@title = t 'trace.edit.title', :name => @trace.name
def delete
trace = Trace.find(params[:id])
- if not trace.visible?
+ if !trace.visible?
render :text => "", :status => :not_found
- elsif @user.nil? or trace.user != @user
+ elsif @user.nil? || trace.user != @user
render :text => "", :status => :forbidden
else
trace.visible = false
@traces = Trace.visible_to_all.visible
if params[:display_name]
- @traces = @traces.joins(:user).where(:users => {:display_name => params[:display_name]})
+ @traces = @traces.joins(:user).where(:users => { :display_name => params[:display_name] })
end
if params[:tag]
trace = Trace.find(params[:id])
if trace.inserted?
- if trace.public? or (@user and @user == trace.user)
+ if trace.public? || (@user && @user == trace.user)
expires_in 7.days, :private => !trace.public?, :public => trace.public?
send_file(trace.large_picture_name, :filename => "#{trace.id}.gif", :type => 'image/gif', :disposition => 'inline')
else
trace = Trace.find(params[:id])
if trace.inserted?
- if trace.public? or (@user and @user == trace.user)
+ if trace.public? || (@user && @user == trace.user)
expires_in 7.days, :private => !trace.public?, :public => trace.public?
send_file(trace.icon_picture_name, :filename => "#{trace.id}_icon.gif", :type => 'image/gif', :disposition => 'inline')
else
def api_read
trace = Trace.visible.find(params[:id])
- if trace.public? or trace.user == @user
+ if trace.public? || trace.user == @user
render :text => trace.to_xml.to_s, :content_type => "text/xml"
else
render :text => "", :status => :forbidden
if trace.user == @user
new_trace = Trace.from_xml(request.raw_post)
- unless new_trace and new_trace.id == trace.id
- raise OSM::APIBadUserInput.new("The id in the url (#{trace.id}) is not the same as provided in the xml (#{new_trace.id})")
+ unless new_trace && new_trace.id == trace.id
+ fail OSM::APIBadUserInput.new("The id in the url (#{trace.id}) is not the same as provided in the xml (#{new_trace.id})")
end
trace.description = new_trace.description
def api_data
trace = Trace.find(params[:id])
- if trace.public? or trace.user == @user
- if request.format == Mime::XML or request.format == Mime::GPX
+ if trace.public? || trace.user == @user
+ if request.format == Mime::XML || request.format == Mime::GPX
send_file(trace.xml_file, :filename => "#{trace.id}.xml", :type => request.format.to_s, :disposition => 'attachment')
else
send_file(trace.trace_name, :filename => "#{trace.id}#{trace.extension_name}", :type => trace.mime_type, :disposition => 'attachment')
end
end
-private
+ private
def do_create(file, tags, description, visibility)
# Sanitise the user's filename
else
@user.preferences.create(:k => "gps.trace.visibility", :v => visibility)
end
-
end
def offline_warning
"public"
end
end
-
end
end
def show
- if @user and @user.id == @user_block.user_id
+ if @user && @user.id == @user_block.user_id
@user_block.needs_view = false
@user_block.save!
end
:user_id => @this_user.id,
:creator_id => @user.id,
:reason => params[:user_block][:reason],
- :ends_at => Time.now.getutc() + @block_period.hours,
+ :ends_at => Time.now.getutc + @block_period.hours,
:needs_view => params[:user_block][:needs_view]
)
flash[:error] = t('user_block.update.only_creator_can_edit')
redirect_to :action => "edit"
elsif @user_block.update_attributes(
- :ends_at => Time.now.getutc() + @block_period.hours,
- :reason => params[:user_block][:reason],
- :needs_view => params[:user_block][:needs_view]
+ :ends_at => Time.now.getutc + @block_period.hours,
+ :reason => params[:user_block][:reason],
+ :needs_view => params[:user_block][:needs_view]
)
flash[:notice] = t('user_block.update.success')
redirect_to(@user_block)
def revoke
if params[:confirm]
if @user_block.revoke! @user
- flash[:notice] = t'user_block.revoke.flash'
+ flash[:notice] = t 'user_block.revoke.flash'
redirect_to(@user_block)
end
end
def blocks_on
@user_blocks_pages, @user_blocks = paginate(:user_blocks,
:include => [:user, :creator, :revoker],
- :conditions => {:user_id => @this_user.id},
+ :conditions => { :user_id => @this_user.id },
:order => "user_blocks.ends_at DESC",
:per_page => 20)
end
def blocks_by
@user_blocks_pages, @user_blocks = paginate(:user_blocks,
:include => [:user, :creator, :revoker],
- :conditions => {:creator_id => @this_user.id},
+ :conditions => { :creator_id => @this_user.id },
:order => "user_blocks.ends_at DESC",
:per_page => 20)
end
private
+
##
# ensure that there is a "user_block" instance variable
def lookup_user_block
if !UserBlock::PERIODS.include?(@block_period)
flash[:error] = t('user_block.filter.block_period')
- elsif @user_block and !@user_block.active?
+ elsif @user_block && !@user_block.active?
flash[:error] = t('user_block.filter.block_expired')
else
@valid_params = true
end
end
-
end
else
@title = t 'user.terms.title'
- if @user and @user.terms_agreed?
+ if @user && @user.terms_agreed?
# Already agreed to terms, so just show settings
redirect_to :action => :account, :display_name => @user.display_name
- elsif @user.nil? and session[:new_user].nil?
+ elsif @user.nil? && session[:new_user].nil?
redirect_to :action => :login, :referer => request.fullpath
end
end
redirect_to t('user.terms.declined')
end
elsif @user
- if !@user.terms_agreed?
+ unless @user.terms_agreed?
@user.consider_pd = params[:user][:consider_pd]
@user.terms_agreed = Time.now.getutc
@user.terms_seen = true
@user.languages = http_accept_language.user_preferred_languages
@user.terms_agreed = Time.now.getutc
@user.terms_seen = true
- @user.openid_url = nil if @user.openid_url and @user.openid_url.empty?
+ @user.openid_url = nil if @user.openid_url && @user.openid_url.empty?
if @user.save
flash[:piwik_goal] = PIWIK["goals"]["signup"] if defined?(PIWIK)
uri = URI(session[:referer])
/map=(.*)\/(.*)\/(.*)/.match(uri.fragment) do |m|
editor = Rack::Utils.parse_query(uri.query).slice('editor')
- referer = welcome_path({'zoom' => m[1],
- 'lat' => m[2],
- 'lon' => m[3]}.merge(editor))
+ referer = welcome_path({ 'zoom' => m[1],
+ 'lat' => m[2],
+ 'lon' => m[3] }.merge(editor))
end
rescue
# Use default
@title = t 'user.account.title'
@tokens = @user.oauth_tokens.authorized
- if params[:user] and params[:user][:display_name] and params[:user][:description]
- if params[:user][:openid_url] and
- params[:user][:openid_url].length > 0 and
+ if params[:user] && params[:user][:display_name] && params[:user][:description]
+ if params[:user][:openid_url] &&
+ params[:user][:openid_url].length > 0 &&
params[:user][:openid_url] != @user.openid_url
# If the OpenID has changed, we want to check that it is a
# valid OpenID and one the user has control over before saving
def lost_password
@title = t 'user.lost_password.title'
- if params[:user] and params[:user][:email]
+ if params[:user] && params[:user][:email]
user = User.visible.find_by_email(params[:user][:email])
if user.nil?
user.status = "active" if user.email == verified_email
end
- if @user.openid_url.nil? or @user.invalid?
+ if @user.openid_url.nil? || @user.invalid?
render :action => 'new'
else
session[:new_user] = @user
end
def login
- if params[:username] or using_open_id?
+ if params[:username] || using_open_id?
session[:referer] ||= params[:referer]
if using_open_id?
token = nil
end
- if token.nil? or token.user != user
+ if token.nil? || token.user != user
flash[:notice] = t('user.confirm.success')
redirect_to :action => :login, :referer => referer
else
def confirm_email
if request.post?
token = UserToken.find_by_token(params[:confirm_string])
- if token and token.user.new_email?
+ if token && token.user.new_email?
@user = token.user
@user.email = @user.new_email
@user.new_email = nil
def api_gpx_files
doc = OSM::API.new.get_xml_doc
@user.traces.each do |trace|
- doc.root << trace.to_xml_node() if trace.public? or trace.user == @user
+ doc.root << trace.to_xml_node if trace.public? || trace.user == @user
end
render :text => doc.to_s, :content_type => "text/xml"
end
def view
@this_user = User.find_by_display_name(params[:display_name])
- if @this_user and
- (@this_user.visible? or (@user and @user.administrator?))
+ if @this_user &&
+ (@this_user.visible? || (@user && @user.administrator?))
@title = @this_user.display_name
else
render_unknown_user params[:display_name]
# display a list of users matching specified criteria
def list
if request.post?
- ids = params[:user].keys.collect { |id| id.to_i }
+ ids = params[:user].keys.collect(&:to_i)
User.update_all("status = 'confirmed'", :id => ids) if params[:confirm]
User.update_all("status = 'deleted'", :id => ids) if params[:hide]
redirect_to url_for(:status => params[:status], :ip => params[:ip], :page => params[:page])
else
- conditions = Hash.new
+ conditions = {}
conditions[:status] = params[:status] if params[:status]
conditions[:creation_ip] = params[:ip] if params[:ip]
end
end
-private
+ private
##
# handle password authentication
def openid_authentication(openid_url)
# If we don't appear to have a user for this URL then ask the
# provider for some extra information to help with signup
- if openid_url and User.find_by_openid_url(openid_url)
+ if openid_url && User.find_by_openid_url(openid_url)
required = nil
else
required = [:nickname, :email, "http://axschema.org/namePerson/friendly", "http://axschema.org/contact/email"]
end
else
# Guard against not getting any extension data
- sreg = Hash.new if sreg.nil?
- ax = Hash.new if ax.nil?
+ sreg = {} if sreg.nil?
+ ax = {} if ax.nil?
# We don't have a user registered to this OpenID, so redirect
# to the create account page with username and email filled
# Do we trust the emails this provider returns?
if openid_email_verified(identity_url)
# Guard against not getting any extension data
- sreg = Hash.new if sreg.nil?
- ax = Hash.new if ax.nil?
+ sreg = {} if sreg.nil?
+ ax = {} if ax.nil?
# Get the verified email
verified_email = sreg["email"] || ax["http://axschema.org/contact/email"].first
def openid_expand_url(openid_url)
if openid_url.nil?
return nil
- elsif openid_url.match(/(.*)gmail.com(\/?)$/) or openid_url.match(/(.*)googlemail.com(\/?)$/)
+ elsif openid_url.match(/(.*)gmail.com(\/?)$/) || openid_url.match(/(.*)googlemail.com(\/?)$/)
# Special case gmail.com as it is potentially a popular OpenID
# provider and, unlike yahoo.com, where it works automatically, Google
# have hidden their OpenID endpoint somewhere obscure this making it
# check if we trust an OpenID provider to return a verified
# email, so that we can skpi verifying it ourselves
def openid_email_verified(openid_url)
- openid_url.match(/https:\/\/www.google.com\/accounts\/o8\/id?(.*)/) or
- openid_url.match(/https:\/\/me.yahoo.com\/(.*)/)
+ openid_url.match(/https:\/\/www.google.com\/accounts\/o8\/id?(.*)/) ||
+ openid_url.match(/https:\/\/me.yahoo.com\/(.*)/)
end
##
# - If they have a block on them, show them that.
# - If they were referred to the login, send them back there.
# - Otherwise, send them to the home page.
- if REQUIRE_TERMS_SEEN and not user.terms_seen
+ if REQUIRE_TERMS_SEEN && !user.terms_seen
redirect_to :controller => :user, :action => :terms, :referer => target
elsif user.blocked_on_view
redirect_to user.blocked_on_view, :referer => target
user.display_name = params[:user][:display_name]
user.new_email = params[:user][:new_email]
- if params[:user][:pass_crypt].length > 0 or params[:user][:pass_crypt_confirmation].length > 0
+ if params[:user][:pass_crypt].length > 0 || params[:user][:pass_crypt_confirmation].length > 0
user.pass_crypt = params[:user][:pass_crypt]
user.pass_crypt_confirmation = params[:user][:pass_crypt_confirmation]
end
if user.save
set_locale
- if user.new_email.blank? or user.new_email == user.email
+ if user.new_email.blank? || user.new_email == user.email
flash.now[:notice] = t 'user.account.flash update success'
else
user.email = user.new_email
# require that the user is a administrator, or fill out a helpful error message
# and return them to the user page.
def require_administrator
- if @user and not @user.administrator?
+ if @user && !@user.administrator?
flash[:error] = t('user.filter.not_an_administrator')
if params[:display_name]
else
redirect_to :controller => 'user', :action => 'login', :referer => request.fullpath
end
- elsif not @user
+ elsif !@user
redirect_to :controller => 'user', :action => 'login', :referer => request.fullpath
end
end
render :action => 'blocked'
end
- not blocked
+ !blocked
end
end
# update the entire set of preferences
def update
- old_preferences = @user.preferences.reduce({}) do |preferences,preference|
+ old_preferences = @user.preferences.reduce({}) do |preferences, preference|
preferences[preference.k] = preference
preferences
end
if preference = old_preferences.delete(pt["k"])
preference.v = pt["v"]
elsif new_preferences.include?(pt["k"])
- raise OSM::APIDuplicatePreferenceError.new(pt["k"])
+ fail OSM::APIDuplicatePreferenceError.new(pt["k"])
else
preference = @user.preferences.build(:k => pt["k"], :v => pt["v"])
end
new_preferences[preference.k] = preference
end
- old_preferences.each_value do |preference|
- preference.delete
- end
+ old_preferences.each_value(&:delete)
- new_preferences.each_value do |preference|
- preference.save!
- end
+ new_preferences.each_value(&:save!)
render :text => "", :content_type => "text/plain"
end
end
def revoke
- UserRole.delete_all({:user_id => @this_user.id, :role => @role})
+ UserRole.delete_all(:user_id => @this_user.id, :role => @role)
redirect_to :controller => 'user', :action => 'view', :display_name => @this_user.display_name
end
private
+
##
# require that the user is an administrator, or fill out a helpful error message
# and return them to theuser page.
def require_administrator
unless @user.administrator?
- flash[:error] = t'user_role.filter.not_an_administrator'
+ flash[:error] = t 'user_role.filter.not_an_administrator'
redirect_to :controller => 'user', :action => 'view', :display_name => @this_user.display_name
end
end
way = Way.find(params[:id])
new_way = Way.from_xml(request.raw_post)
- if new_way and new_way.id == way.id
+ if new_way && new_way.id == way.id
way.update_from(new_way, @user)
render :text => way.version.to_s, :content_type => "text/plain"
else
way = Way.find(params[:id])
new_way = Way.from_xml(request.raw_post)
- if new_way and new_way.id == way.id
+ if new_way && new_way.id == way.id
way.delete_with_history!(new_way, @user)
render :text => way.version.to_s, :content_type => "text/plain"
else
end
def ways
- if not params['ways']
- raise OSM::APIBadUserInput.new("The parameter ways is required, and must be of the form ways=id[,id[,id...]]")
+ unless params['ways']
+ fail OSM::APIBadUserInput.new("The parameter ways is required, and must be of the form ways=id[,id[,id...]]")
end
- ids = params['ways'].split(',').collect { |w| w.to_i }
+ ids = params['ways'].split(',').collect(&:to_i)
if ids.length == 0
- raise OSM::APIBadUserInput.new("No ways were given to search for")
+ fail OSM::APIBadUserInput.new("No ways were given to search for")
end
doc = OSM::API.new.get_xml_doc
end
def rss_link_to(*args)
- return link_to(image_tag("RSS.png", :size => "16x16", :border => 0), Hash[*args], { :class => "rsssmall" });
+ link_to(image_tag("RSS.png", :size => "16x16", :border => 0), Hash[*args], :class => "rsssmall")
end
def atom_link_to(*args)
- return link_to(image_tag("RSS.png", :size => "16x16", :border => 0), Hash[*args], { :class => "rsssmall" });
+ link_to(image_tag("RSS.png", :size => "16x16", :border => 0), Hash[*args], :class => "rsssmall")
end
def style_rules
css << ".hide_if_logged_in { display: none !important }" if @user
css << ".hide_if_user_#{@user.id} { display: none !important }" if @user
css << ".show_if_user_#{@user.id} { display: inline !important }" if @user
- css << ".hide_unless_administrator { display: none !important }" unless @user and @user.administrator?
- css << ".hide_unless_moderator { display: none !important }" unless @user and @user.moderator?
+ css << ".hide_unless_administrator { display: none !important }" unless @user && @user.administrator?
+ css << ".hide_unless_moderator { display: none !important }" unless @user && @user.moderator?
- return content_tag(:style, css, :type => "text/css")
+ content_tag(:style, css, :type => "text/css")
end
def if_logged_in(tag = :div, &block)
end
def richtext_area(object_name, method, options = {})
- id = "#{object_name.to_s}_#{method.to_s}"
+ id = "#{object_name}_#{method}"
format = options.delete(:format) || "markdown"
content_tag(:div, :id => "#{id}_container", :class => "richtext_container") do
module BrowseHelper
- def printable_name(object, version=false)
+ def printable_name(object, version = false)
if object.id.is_a?(Array)
id = object.id[0]
else
unless object.redacted?
locale = I18n.locale.to_s
- while locale =~ /-[^-]+/ and not object.tags.include? "name:#{I18n.locale}"
+ while locale =~ /-[^-]+/ && !object.tags.include?("name:#{I18n.locale}")
locale = locale.sub(/-[^-]+/, "")
end
if object.tags.include? "name:#{locale}"
- name = t 'printable_name.with_name_html', :name => content_tag(:bdi, object.tags["name:#{locale}"].to_s ), :id => content_tag(:bdi, name)
+ name = t 'printable_name.with_name_html', :name => content_tag(:bdi, object.tags["name:#{locale}"].to_s), :id => content_tag(:bdi, name)
elsif object.tags.include? 'name'
- name = t 'printable_name.with_name_html', :name => content_tag(:bdi, object.tags['name'].to_s ), :id => content_tag(:bdi, name)
+ name = t 'printable_name.with_name_html', :name => content_tag(:bdi, object.tags['name'].to_s), :id => content_tag(:bdi, name)
end
end
end
def link_class(type, object)
- classes = [ type ]
+ classes = [type]
if object.redacted?
classes << "deleted"
if object.redacted?
""
else
- h(icon_tags(object).map { |k,v| k + '=' + v }.to_sentence)
+ h(icon_tags(object).map { |k, v| k + '=' + v }.to_sentence)
end
end
end
end
-private
+ private
- ICON_TAGS = [
- "aeroway", "amenity", "barrier", "building", "highway", "historic", "landuse",
- "leisure", "man_made", "natural", "railway", "shop", "tourism", "waterway"
- ]
+ ICON_TAGS = %w(aeroway amenity barrier building highway historic landuse leisure man_made natural railway shop tourism waterway)
def icon_tags(object)
- object.tags.find_all { |k,v| ICON_TAGS.include? k }.sort
+ object.tags.find_all { |k, _v| ICON_TAGS.include? k }.sort
end
def wiki_link(type, lookup)
url = "http://wiki.openstreetmap.org/wiki/#{page}?uselang=#{locale}"
end
- return url
+ url
end
def wikipedia_link(key, value)
return nil
end
- if value =~ /^([^#]*)(#.*)/ then
+ if value =~ /^([^#]*)(#.*)/
# Contains a reference to a section of the wikipedia article
# Must break it up to correctly build the url
value = $1
section = ""
end
- return {
+ {
:url => "http://#{lang}.wikipedia.org/wiki/#{value}?uselang=#{I18n.locale}#{section}",
:title => value + section
}
end
def wikidata_link(key, value)
- if key == "wikidata" and value =~ /^[Qq][1-9][0-9]*$/
+ if key == "wikidata" && value =~ /^[Qq][1-9][0-9]*$/
return {
:url => "//www.wikidata.org/wiki/#{value}?uselang=#{I18n.locale}",
:title => value
}
end
- return nil
+ nil
end
- def telephone_link(key, value)
+ def telephone_link(_key, value)
# does it look like a phone number? eg "+1 (234) 567-8901 " ?
return nil unless value =~ /^\s*\+[\d\s\(\)\/\.-]{6,25}\s*$/
# "+1 (234) 567-8901 " -> "+1(234)567-8901"
valueNoWhitespace = value.gsub(/\s+/, '')
- return "tel:#{valueNoWhitespace}"
+ "tel:#{valueNoWhitespace}"
end
end
def result_to_html(result)
html_options = { :class => "set_position", :data => {} }
- if result[:type] and result[:id]
+ if result[:type] && result[:id]
url = url_for(:controller => :browse, :action => result[:type], :id => result[:id])
- elsif result[:min_lon] and result[:min_lat] and result[:max_lon] and result[:max_lat]
+ elsif result[:min_lon] && result[:min_lat] && result[:max_lon] && result[:max_lat]
url = "/?bbox=#{result[:min_lon]},#{result[:min_lat]},#{result[:max_lon]},#{result[:max_lat]}"
else
url = "/#map=#{result[:zoom]}/#{result[:lat]}/#{result[:lon]}"
end
- result.each do |key,value|
+ result.each do |key, value|
html_options[:data][key.to_s.tr('_', '-')] = value
end
html = ""
html << result[:prefix] if result[:prefix]
- html << " " if result[:prefix] and result[:name]
+ html << " " if result[:prefix] && result[:name]
html << link_to(result[:name], url, html_options) if result[:name]
html << result[:suffix] if result[:suffix]
html.html_safe
def note_event(event, at, by)
if by.nil?
I18n.t("browse.note." + event + "_by_anonymous",
- :when => friendly_date(at),
- :exact_time => l(at)
+ :when => friendly_date(at),
+ :exact_time => l(at)
).html_safe
else
I18n.t("browse.note." + event + "_by",
- :when => friendly_date(at),
- :exact_time => l(at),
- :user => note_author(by)
+ :when => friendly_date(at),
+ :exact_time => l(at),
+ :user => note_author(by)
).html_safe
end
end
if author.nil?
""
else
- link_to h(author.display_name), link_options.merge({:controller => "user", :action => "view", :display_name => author.display_name})
+ link_to h(author.display_name), link_options.merge(:controller => "user", :action => "view", :display_name => author.display_name)
end
end
-
end
# See http://en.gravatar.com/site/implement/images/ for details.
def user_gravatar_url(user, options = {})
size = options[:size] || 100
- hash = Digest::MD5::hexdigest(user.email.downcase)
+ hash = Digest::MD5.hexdigest(user.email.downcase)
default_image_url = image_url("users/images/large.png")
url = "#{request.protocol}www.gravatar.com/avatar/#{hash}.jpg?s=#{size}&d=#{u(default_image_url)}"
end
module UserRolesHelper
def role_icons(user)
- UserRole::ALL_ROLES.reduce("".html_safe) { |s,r| s + " " + role_icon(user, r) }
+ UserRole::ALL_ROLES.reduce("".html_safe) { |s, r| s + " " + role_icon(user, r) }
end
def role_icon(user, role)
- if @user and @user.administrator?
+ if @user && @user.administrator?
if user.has_role?(role)
image = "roles/#{role}.png"
alt = t("user.view.role.revoke.#{role}")
before_create :set_authorized_at
-protected
+ protected
def set_authorized_at
self.authorized_at = Time.now
end
def self.no_account_creation(address, domain = nil)
- self.match(address, domain).where(:k => "no_account_creation").exists?
+ match(address, domain).where(:k => "no_account_creation").exists?
end
def self.no_note_comment(address, domain = nil)
- self.match(address, domain).where(:k => "no_note_comment").exists?
+ match(address, domain).where(:k => "no_note_comment").exists?
end
def self.no_trace_download(address, domain = nil)
- self.match(address, domain).where(:k => "no_trace_download").exists?
+ match(address, domain).where(:k => "no_trace_download").exists?
end
end
# note that this may not be a hard limit - due to timing changes and
# concurrency it is possible that some changesets may be slightly
# longer than strictly allowed or have slightly more changes in them.
- return ((closed_at > Time.now.getutc) and (num_changes <= MAX_ELEMENTS))
+ ((closed_at > Time.now.getutc) && (num_changes <= MAX_ELEMENTS))
end
def set_closed_time_now
end
end
- def self.from_xml(xml, create=false)
- begin
- p = XML::Parser.string(xml, :options => XML::Parser::Options::NOERROR)
- doc = p.parse
+ def self.from_xml(xml, create = false)
+ p = XML::Parser.string(xml, :options => XML::Parser::Options::NOERROR)
+ doc = p.parse
- doc.find('//osm/changeset').each do |pt|
- return Changeset.from_xml_node(pt, create)
- end
- raise OSM::APIBadXMLError.new("changeset", xml, "XML doesn't contain an osm/changeset element.")
- rescue LibXML::XML::Error, ArgumentError => ex
- raise OSM::APIBadXMLError.new("changeset", xml, ex.message)
+ doc.find('//osm/changeset').each do |pt|
+ return Changeset.from_xml_node(pt, create)
end
+ fail OSM::APIBadXMLError.new("changeset", xml, "XML doesn't contain an osm/changeset element.")
+ rescue LibXML::XML::Error, ArgumentError => ex
+ raise OSM::APIBadXMLError.new("changeset", xml, ex.message)
end
- def self.from_xml_node(pt, create=false)
+ def self.from_xml_node(pt, create = false)
cs = Changeset.new
if create
cs.created_at = Time.now.getutc
end
pt.find('tag').each do |tag|
- raise OSM::APIBadXMLError.new("changeset", pt, "tag is missing key") if tag['k'].nil?
- raise OSM::APIBadXMLError.new("changeset", pt, "tag is missing value") if tag['v'].nil?
+ fail OSM::APIBadXMLError.new("changeset", pt, "tag is missing key") if tag['k'].nil?
+ fail OSM::APIBadXMLError.new("changeset", pt, "tag is missing value") if tag['v'].nil?
cs.add_tag_keyval(tag['k'], tag['v'])
end
- return cs
+ cs
end
##
end
def tags_as_hash
- return tags
+ tags
end
def tags
unless @tags
@tags = {}
- self.changeset_tags.each do |tag|
+ changeset_tags.each do |tag|
@tags[tag.k] = tag.v
end
end
@tags
end
- def tags=(t)
- @tags = t
- end
+ attr_writer :tags
def add_tag_keyval(k, v)
- @tags = Hash.new unless @tags
+ @tags = {} unless @tags
# duplicate tags are now forbidden, so we can't allow values
# in the hash to be overwritten.
- raise OSM::APIDuplicateTagsError.new("changeset", self.id, k) if @tags.include? k
+ fail OSM::APIDuplicateTagsError.new("changeset", id, k) if @tags.include? k
@tags[k] = v
end
self.save!
tags = self.tags
- ChangesetTag.delete_all(:changeset_id => self.id)
+ ChangesetTag.delete_all(:changeset_id => id)
- tags.each do |k,v|
+ tags.each do |k, v|
tag = ChangesetTag.new
- tag.changeset_id = self.id
+ tag.changeset_id = id
tag.k = k
tag.v = v
tag.save!
def to_xml(include_discussion = false)
doc = OSM::API.new.get_xml_doc
doc.root << to_xml_node(nil, include_discussion)
- return doc
+ doc
end
def to_xml_node(user_display_name_cache = nil, include_discussion = false)
el1 = XML::Node.new 'changeset'
- el1['id'] = self.id.to_s
+ el1['id'] = id.to_s
user_display_name_cache = {} if user_display_name_cache.nil?
- if user_display_name_cache and user_display_name_cache.key?(self.user_id)
+ if user_display_name_cache && user_display_name_cache.key?(user_id)
# use the cache if available
- elsif self.user.data_public?
- user_display_name_cache[self.user_id] = self.user.display_name
+ elsif user.data_public?
+ user_display_name_cache[user_id] = user.display_name
else
- user_display_name_cache[self.user_id] = nil
+ user_display_name_cache[user_id] = nil
end
- el1['user'] = user_display_name_cache[self.user_id] unless user_display_name_cache[self.user_id].nil?
- el1['uid'] = self.user_id.to_s if self.user.data_public?
+ el1['user'] = user_display_name_cache[user_id] unless user_display_name_cache[user_id].nil?
+ el1['uid'] = user_id.to_s if user.data_public?
- self.tags.each do |k,v|
+ tags.each do |k, v|
el2 = XML::Node.new('tag')
el2['k'] = k.to_s
el2['v'] = v.to_s
el1 << el2
end
- el1['created_at'] = self.created_at.xmlschema
- el1['closed_at'] = self.closed_at.xmlschema unless is_open?
+ el1['created_at'] = created_at.xmlschema
+ el1['closed_at'] = closed_at.xmlschema unless is_open?
el1['open'] = is_open?.to_s
if bbox.complete?
bbox.to_unscaled.add_bounds_to(el1, '_')
end
- el1['comments_count'] = self.comments.count.to_s
+ el1['comments_count'] = comments.count.to_s
if include_discussion
el2 = XML::Node.new('discussion')
- self.comments.includes(:author).each do |comment|
+ comments.includes(:author).each do |comment|
el3 = XML::Node.new('comment')
el3['date'] = comment.created_at.xmlschema
el3['uid'] = comment.author.id.to_s if comment.author.data_public?
# they are just structures for tagging. to get the osmChange of a
# changeset, see the download method of the controller.
- return el1
+ el1
end
##
# bounding box, only the tags of the changeset.
def update_from(other, user)
# ensure that only the user who opened the changeset may modify it.
- unless user.id == self.user_id
- raise OSM::APIUserChangesetMismatchError.new
+ unless user.id == user_id
+ fail OSM::APIUserChangesetMismatchError.new
end
# can't change a closed changeset
unless is_open?
- raise OSM::APIChangesetAlreadyClosedError.new(self)
+ fail OSM::APIChangesetAlreadyClosedError.new(self)
end
# copy the other's tags
validates_associated :changeset
validates_presence_of :author
validates_associated :author
- validates :visible, :inclusion => { :in => [true,false] }
+ validates :visible, :inclusion => { :in => [true, false] }
# Return the comment text
def body
validates_presence_of :name, :url, :key, :secret
validates_uniqueness_of :key
validates_format_of :url, :with => /\Ahttp(s?):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/i
- validates_format_of :support_url, :with => /\Ahttp(s?):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/i, :allow_blank=>true
- validates_format_of :callback_url, :with => /\A[a-z][a-z0-9.+-]*:\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/i, :allow_blank=>true
+ validates_format_of :support_url, :with => /\Ahttp(s?):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/i, :allow_blank => true
+ validates_format_of :callback_url, :with => /\A[a-z][a-z0-9.+-]*:\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/i, :allow_blank => true
before_validation :generate_keys, :on => :create
end
def self.verify_request(request, options = {}, &block)
- begin
- signature = OAuth::Signature.build(request, options, &block)
- return false unless OauthNonce.remember(signature.request.nonce, signature.request.timestamp)
- value = signature.verify
- value
- rescue OAuth::Signature::UnknownSignatureMethod => e
- false
- end
+ signature = OAuth::Signature.build(request, options, &block)
+ return false unless OauthNonce.remember(signature.request.nonce, signature.request.timestamp)
+ value = signature.verify
+ value
+ rescue OAuth::Signature::UnknownSignatureMethod => e
+ false
end
def self.all_permissions
@oauth_client ||= OAuth::Consumer.new(key, secret)
end
- def create_request_token(params={})
- params = { :client_application => self, :callback_url => self.token_callback_url }
+ def create_request_token(params = {})
+ params = { :client_application => self, :callback_url => token_callback_url }
permissions.each do |p|
params[p] = true
end
ClientApplication.all_permissions.select { |p| self[p] }
end
-protected
+ protected
# this is the set of permissions that the client can ask for. clients
# have to say up-front what permissions they want and when users sign up they
:allow_write_notes]
def generate_keys
- self.key = OAuth::Helper.generate_key(40)[0,40]
- self.secret = OAuth::Helper.generate_key(40)[0,40]
+ self.key = OAuth::Helper.generate_key(40)[0, 40]
+ self.secret = OAuth::Helper.generate_key(40)[0, 40]
end
end
md5.hexdigest
end
-private
+ private
def spam_check
user.spam_check
belongs_to :language, :foreign_key => 'language_code'
has_many :comments, -> { order(:id).preload(:user) }, :class_name => "DiaryComment"
- has_many :visible_comments, -> { joins(:user).where(:visible => true, :users => { :status => ["active", "confirmed"] }).order(:id) }, :class_name => "DiaryComment"
+ has_many :visible_comments, -> { joins(:user).where(:visible => true, :users => { :status => %w(active confirmed) }).order(:id) }, :class_name => "DiaryComment"
scope :visible, -> { where(:visible => true) }
validates_presence_of :title, :body
validates_length_of :title, :within => 1..255
- #validates_length_of :language, :within => 2..5, :allow_nil => false
+ # validates_length_of :language, :within => 2..5, :allow_nil => false
validates_numericality_of :latitude, :allow_nil => true,
- :greater_than_or_equal_to => -90, :less_than_or_equal_to => 90
+ :greater_than_or_equal_to => -90, :less_than_or_equal_to => 90
validates_numericality_of :longitude, :allow_nil => true,
- :greater_than_or_equal_to => -180, :less_than_or_equal_to => 180
+ :greater_than_or_equal_to => -180, :less_than_or_equal_to => 180
validates_associated :language
after_save :spam_check
RichText.new(read_attribute(:body_format), read_attribute(:body))
end
-private
+ private
def spam_check
user.spam_check
def self.load(file)
Language.transaction do
- YAML.load(File.read(file)).each do |k,v|
+ YAML.load(File.read(file)).each do |k, v|
begin
Language.update(k, :english_name => v["english"], :native_name => v["native"])
rescue ActiveRecord::RecordNotFound
validates_presence_of :title, :body, :sent_on, :sender, :recipient
validates_length_of :title, :within => 1..255
- validates_inclusion_of :message_read, :in => [ true, false ]
+ validates_inclusion_of :message_read, :in => [true, false]
validates_as_utf8 :title
def self.from_mail(mail, from, to)
elsif mail.html_part
body = HTMLEntities.new.decode(Sanitize.clean(mail.html_part.decoded))
end
- elsif mail.text? and mail.sub_type == "html"
+ elsif mail.text? && mail.sub_type == "html"
body = HTMLEntities.new.decode(Sanitize.clean(mail.decoded))
else
body = mail.decoded
has_many :node_tags
has_many :old_way_nodes
- has_many :ways_via_history, :class_name=> "Way", :through => :old_way_nodes, :source => :way
+ has_many :ways_via_history, :class_name => "Way", :through => :old_way_nodes, :source => :way
has_many :containing_relation_members, :class_name => "RelationMember", :as => :member
has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation
validates_presence_of :id, :on => :update
- validates_presence_of :timestamp,:version, :changeset_id
+ validates_presence_of :timestamp, :version, :changeset_id
validates_uniqueness_of :id
- validates_inclusion_of :visible, :in => [ true, false ]
+ validates_inclusion_of :visible, :in => [true, false]
validates_numericality_of :latitude, :longitude, :changeset_id, :version, :integer_only => true
validates_numericality_of :id, :on => :update, :integer_only => true
validate :validate_position
end
# Read in xml as text and return it's Node object representation
- def self.from_xml(xml, create=false)
- begin
- p = XML::Parser.string(xml)
- doc = p.parse
+ def self.from_xml(xml, create = false)
+ p = XML::Parser.string(xml)
+ doc = p.parse
- doc.find('//osm/node').each do |pt|
- return Node.from_xml_node(pt, create)
- end
- raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/node element.")
- rescue LibXML::XML::Error, ArgumentError => ex
- raise OSM::APIBadXMLError.new("node", xml, ex.message)
+ doc.find('//osm/node').each do |pt|
+ return Node.from_xml_node(pt, create)
end
+ fail OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/node element.")
+ rescue LibXML::XML::Error, ArgumentError => ex
+ raise OSM::APIBadXMLError.new("node", xml, ex.message)
end
- def self.from_xml_node(pt, create=false)
+ def self.from_xml_node(pt, create = false)
node = Node.new
- raise OSM::APIBadXMLError.new("node", pt, "lat missing") if pt['lat'].nil?
- raise OSM::APIBadXMLError.new("node", pt, "lon missing") if pt['lon'].nil?
+ fail OSM::APIBadXMLError.new("node", pt, "lat missing") if pt['lat'].nil?
+ fail OSM::APIBadXMLError.new("node", pt, "lon missing") if pt['lon'].nil?
node.lat = OSM.parse_float(pt['lat'], OSM::APIBadXMLError, "node", pt, "lat not a number")
node.lon = OSM.parse_float(pt['lon'], OSM::APIBadXMLError, "node", pt, "lon not a number")
- raise OSM::APIBadXMLError.new("node", pt, "Changeset id is missing") if pt['changeset'].nil?
+ fail OSM::APIBadXMLError.new("node", pt, "Changeset id is missing") if pt['changeset'].nil?
node.changeset_id = pt['changeset'].to_i
- raise OSM::APIBadUserInput.new("The node is outside this world") unless node.in_world?
+ fail OSM::APIBadUserInput.new("The node is outside this world") unless node.in_world?
# version must be present unless creating
- raise OSM::APIBadXMLError.new("node", pt, "Version is required when updating") unless create or not pt['version'].nil?
+ fail OSM::APIBadXMLError.new("node", pt, "Version is required when updating") unless create || !pt['version'].nil?
node.version = create ? 0 : pt['version'].to_i
unless create
- raise OSM::APIBadXMLError.new("node", pt, "ID is required when updating.") if pt['id'].nil?
+ fail OSM::APIBadXMLError.new("node", pt, "ID is required when updating.") if pt['id'].nil?
node.id = pt['id'].to_i
# .to_i will return 0 if there is no number that can be parsed.
# We want to make sure that there is no id with zero anyway
- raise OSM::APIBadUserInput.new("ID of node cannot be zero when updating.") if node.id == 0
+ fail OSM::APIBadUserInput.new("ID of node cannot be zero when updating.") if node.id == 0
end
# We don't care about the time, as it is explicitly set on create/update/delete
node.visible = true
# Start with no tags
- node.tags = Hash.new
+ node.tags = {}
# Add in any tags from the XML
pt.find('tag').each do |tag|
- raise OSM::APIBadXMLError.new("node", pt, "tag is missing key") if tag['k'].nil?
- raise OSM::APIBadXMLError.new("node", pt, "tag is missing value") if tag['v'].nil?
- node.add_tag_key_val(tag['k'],tag['v'])
+ fail OSM::APIBadXMLError.new("node", pt, "tag is missing key") if tag['k'].nil?
+ fail OSM::APIBadXMLError.new("node", pt, "tag is missing value") if tag['v'].nil?
+ node.add_tag_key_val(tag['k'], tag['v'])
end
- return node
+ node
end
##
# Should probably be renamed delete_from to come in line with update
def delete_with_history!(new_node, user)
- unless self.visible
- raise OSM::APIAlreadyDeletedError.new("node", new_node.id)
+ unless visible
+ fail OSM::APIAlreadyDeletedError.new("node", new_node.id)
end
# need to start the transaction here, so that the database can
self.lock!
check_consistency(self, new_node, user)
ways = Way.joins(:way_nodes).where(:visible => true, :current_way_nodes => { :node_id => id }).order(:id)
- raise OSM::APIPreconditionFailedError.new("Node #{self.id} is still used by ways #{ways.collect { |w| w.id }.join(",")}.") unless ways.empty?
+ fail OSM::APIPreconditionFailedError.new("Node #{id} is still used by ways #{ways.collect(&:id).join(",")}.") unless ways.empty?
rels = Relation.joins(:relation_members).where(:visible => true, :current_relation_members => { :member_type => "Node", :member_id => id }).order(:id)
- raise OSM::APIPreconditionFailedError.new("Node #{self.id} is still used by relations #{rels.collect { |r| r.id }.join(",")}.") unless rels.empty?
+ fail OSM::APIPreconditionFailedError.new("Node #{id} is still used by relations #{rels.collect(&:id).join(",")}.") unless rels.empty?
self.changeset_id = new_node.changeset_id
self.tags = {}
self.changeset = new_node.changeset
# update changeset bbox with *old* position first
- changeset.update_bbox!(bbox);
+ changeset.update_bbox!(bbox)
# FIXME logic needs to be double checked
self.latitude = new_node.latitude
self.visible = true
# update changeset bbox with *new* position
- changeset.update_bbox!(bbox);
+ changeset.update_bbox!(bbox)
save_with_history!
end
def to_xml
doc = OSM::API.new.get_xml_doc
- doc.root << to_xml_node()
- return doc
+ doc.root << to_xml_node
+ doc
end
def to_xml_node(changeset_cache = {}, user_display_name_cache = {})
el = XML::Node.new 'node'
- el['id'] = self.id.to_s
+ el['id'] = id.to_s
add_metadata_to_xml_node(el, self, changeset_cache, user_display_name_cache)
if self.visible?
- el['lat'] = self.lat.to_s
- el['lon'] = self.lon.to_s
+ el['lat'] = lat.to_s
+ el['lon'] = lon.to_s
end
- add_tags_to_xml_node(el, self.node_tags)
+ add_tags_to_xml_node(el, node_tags)
- return el
+ el
end
def tags_as_hash
- return tags
+ tags
end
def tags
- @tags ||= Hash[self.node_tags.collect { |t| [t.k, t.v] }]
+ @tags ||= Hash[node_tags.collect { |t| [t.k, t.v] }]
end
- def tags=(t)
- @tags = t
- end
+ attr_writer :tags
- def add_tag_key_val(k,v)
- @tags = Hash.new unless @tags
+ def add_tag_key_val(k, v)
+ @tags = {} unless @tags
# duplicate tags are now forbidden, so we can't allow values
# in the hash to be overwritten.
- raise OSM::APIDuplicateTagsError.new("node", self.id, k) if @tags.include? k
+ fail OSM::APIDuplicateTagsError.new("node", id, k) if @tags.include? k
@tags[k] = v
end
##
# dummy method to make the interfaces of node, way and relation
# more consistent.
- def fix_placeholders!(id_map, placeholder_id = nil)
+ def fix_placeholders!(_id_map, _placeholder_id = nil)
# nodes don't refer to anything, so there is nothing to do here
end
# Create a NodeTag
tags = self.tags
- NodeTag.delete_all(:node_id => self.id)
- tags.each do |k,v|
+ NodeTag.delete_all(:node_id => id)
+ tags.each do |k, v|
tag = NodeTag.new
- tag.node_id = self.id
+ tag.node_id = id
tag.k = k
tag.v = v
tag.save!
changeset.save!
end
end
-
end
validates_numericality_of :latitude, :only_integer => true
validates_numericality_of :longitude, :only_integer => true
validates_presence_of :closed_at if :status == "closed"
- validates_inclusion_of :status, :in => ["open", "closed", "hidden"]
+ validates_inclusion_of :status, :in => %w(open closed hidden)
validate :validate_position
scope :visible, -> { where("status != 'hidden'") }
def close
self.status = "closed"
self.closed_at = Time.now.getutc
- self.save
+ save
end
# Reopen a note
def reopen
self.status = "open"
self.closed_at = nil
- self.save
+ save
end
# Check if a note is visible
# Check if a note is closed
def closed?
- not closed_at.nil?
+ !closed_at.nil?
end
# Return the author object, derived from the first comment
def author
- self.comments.first.author
+ comments.first.author
end
# Return the author IP address, derived from the first comment
def author_ip
- self.comments.first.author_ip
+ comments.first.author_ip
end
-private
+ private
# Fill in default values for new notes
def set_defaults
validates_associated :note
validates_presence_of :visible
validates_associated :author
- validates_inclusion_of :event, :in => [ "opened", "closed", "reopened", "commented", "hidden" ]
+ validates_inclusion_of :event, :in => %w(opened closed reopened commented hidden)
validates_format_of :body, :with => /\A[^\x00-\x08\x0b-\x0c\x0e-\x1f\x7f\ufffe\uffff]*\z/
# Return the comment text
end
end
-private
+ private
def with_recipient_locale(recipient)
old_locale = I18n.locale
end
def from_address(name, type, id, digest)
- if Object.const_defined?(:MESSAGES_DOMAIN) and domain = MESSAGES_DOMAIN
- "#{name} <#{type}-#{id}-#{digest[0,6]}@#{domain}>"
+ if Object.const_defined?(:MESSAGES_DOMAIN) && domain = MESSAGES_DOMAIN
+ "#{name} <#{type}-#{id}-#{digest[0, 6]}@#{domain}>"
else
EMAIL_FROM
end
class Oauth2Token < AccessToken
attr_accessor :state
- def as_json(options={})
- d = {:access_token=>token, :token_type => 'bearer'}
+ def as_json(_options = {})
+ d = { :access_token => token, :token_type => 'bearer' }
d[:expires_in] = expires_in if expires_at
d
end
validates_presence_of :user
attr_accessor :state
- def exchange!(params={})
+ def exchange!(_params = {})
OauthToken.transaction do
- token = Oauth2Token.create! :user=>user,:client_application=>client_application, :scope => scope
+ token = Oauth2Token.create! :user => user, :client_application => client_application, :scope => scope
invalidate!
token
end
protected
def generate_keys
- self.token = OAuth::Helper.generate_key(20)[0,20]
+ self.token = OAuth::Helper.generate_key(20)[0, 20]
self.expires_at = 10.minutes.from_now
self.authorized_at = Time.now
end
end
def authorized?
- authorized_at != nil && !invalidated?
+ !authorized_at.nil? && !invalidated?
end
def to_query
"oauth_token=#{token}&oauth_token_secret=#{secret}"
end
-protected
+ protected
def generate_keys
- self.token = OAuth::Helper.generate_key(40)[0,40]
- self.secret = OAuth::Helper.generate_key(40)[0,40]
+ self.token = OAuth::Helper.generate_key(40)[0, 40]
+ self.secret = OAuth::Helper.generate_key(40)[0, 40]
end
end
include Redactable
validates_presence_of :changeset_id, :timestamp
- validates_inclusion_of :visible, :in => [ true, false ]
+ validates_inclusion_of :visible, :in => [true, false]
validates_numericality_of :latitude, :longitude
validate :validate_position
validates_associated :changeset
old_node.changeset_id = node.changeset_id
old_node.node_id = node.id
old_node.version = node.version
- return old_node
+ old_node
end
def to_xml
doc = OSM::API.new.get_xml_doc
- doc.root << to_xml_node()
- return doc
+ doc.root << to_xml_node
+ doc
end
def to_xml_node(changeset_cache = {}, user_display_name_cache = {})
el = XML::Node.new 'node'
- el['id'] = self.node_id.to_s
+ el['id'] = node_id.to_s
add_metadata_to_xml_node(el, self, changeset_cache, user_display_name_cache)
if self.visible?
- el['lat'] = self.lat.to_s
- el['lon'] = self.lon.to_s
+ el['lat'] = lat.to_s
+ el['lon'] = lon.to_s
end
- add_tags_to_xml_node(el, self.old_tags)
+ add_tags_to_xml_node(el, old_tags)
- return el
+ el
end
def save_with_dependencies!
save!
- self.tags.each do |k,v|
+ tags.each do |k, v|
tag = OldNodeTag.new
tag.k = k
tag.v = v
- tag.node_id = self.node_id
- tag.version = self.version
+ tag.node_id = node_id
+ tag.version = version
tag.save!
end
end
def tags
- @tags ||= Hash[self.old_tags.collect { |t| [t.k, t.v] }]
+ @tags ||= Hash[old_tags.collect { |t| [t.k, t.v] }]
end
- def tags=(t)
- @tags = t
- end
+ attr_writer :tags
def tags_as_hash
- return self.tags
+ tags
end
# Pretend we're not in any ways
def ways
- return []
+ []
end
# Pretend we're not in any relations
def containing_relation_members
- return []
+ []
end
# check whether this element is the latest version - that is,
# has the same version as its "current" counterpart.
def is_latest_version?
- current_node.version == self.version
+ current_node.version == version
end
end
old_relation.version = relation.version
old_relation.members = relation.members
old_relation.tags = relation.tags
- return old_relation
+ old_relation
end
def save_with_dependencies!
save!
- self.tags.each do |k,v|
+ tags.each do |k, v|
tag = OldRelationTag.new
tag.k = k
tag.v = v
- tag.relation_id = self.relation_id
- tag.version = self.version
+ tag.relation_id = relation_id
+ tag.version = version
tag.save!
end
- self.members.each_with_index do |m,i|
+ members.each_with_index do |m, i|
member = OldRelationMember.new
- member.id = [self.relation_id, self.version, i]
+ member.id = [relation_id, version, i]
member.member_type = m[0].classify
member.member_id = m[1]
member.member_role = m[2]
end
def members
- @members ||= self.old_members.collect do |member|
+ @members ||= old_members.collect do |member|
[member.member_type, member.member_id, member.member_role]
end
end
def tags
- @tags ||= Hash[self.old_tags.collect { |t| [t.k, t.v] }]
+ @tags ||= Hash[old_tags.collect { |t| [t.k, t.v] }]
end
- def members=(s)
- @members = s
- end
+ attr_writer :members
- def tags=(t)
- @tags = t
- end
+ attr_writer :tags
def to_xml
doc = OSM::API.new.get_xml_doc
- doc.root << to_xml_node()
- return doc
+ doc.root << to_xml_node
+ doc
end
def to_xml_node(changeset_cache = {}, user_display_name_cache = {})
el = XML::Node.new 'relation'
- el['id'] = self.relation_id.to_s
+ el['id'] = relation_id.to_s
add_metadata_to_xml_node(el, self, changeset_cache, user_display_name_cache)
- self.old_members.each do |member|
+ old_members.each do |member|
member_el = XML::Node.new 'member'
member_el['type'] = member.member_type.to_s.downcase
member_el['ref'] = member.member_id.to_s # "id" is considered uncool here as it should be unique in XML
el << member_el
end
- add_tags_to_xml_node(el, self.old_tags)
+ add_tags_to_xml_node(el, old_tags)
- return el
+ el
end
# Temporary method to match interface to nodes
def tags_as_hash
- return self.tags
+ tags
end
# Temporary method to match interface to relations
def relation_members
- return self.old_members
+ old_members
end
# Pretend we're not in any relations
def containing_relation_members
- return []
+ []
end
# check whether this element is the latest version - that is,
# has the same version as its "current" counterpart.
def is_latest_version?
- current_relation.version == self.version
+ current_relation.version == version
end
end
old_way.version = way.version
old_way.nds = way.nds
old_way.tags = way.tags
- return old_way
+ old_way
end
def save_with_dependencies!
save!
- self.tags.each do |k,v|
+ tags.each do |k, v|
tag = OldWayTag.new
tag.k = k
tag.v = v
- tag.way_id = self.way_id
- tag.version = self.version
+ tag.way_id = way_id
+ tag.version = version
tag.save!
end
sequence = 1
- self.nds.each do |n|
+ nds.each do |n|
nd = OldWayNode.new
- nd.id = [self.way_id, self.version, sequence]
+ nd.id = [way_id, version, sequence]
nd.node_id = n
nd.save!
sequence += 1
end
def nds
- @nds ||= self.old_nodes.order(:sequence_id).collect { |n| n.node_id }
+ @nds ||= old_nodes.order(:sequence_id).collect(&:node_id)
end
def tags
- @tags ||= Hash[self.old_tags.collect { |t| [t.k, t.v] }]
+ @tags ||= Hash[old_tags.collect { |t| [t.k, t.v] }]
end
- def nds=(s)
- @nds = s
- end
+ attr_writer :nds
- def tags=(t)
- @tags = t
- end
+ attr_writer :tags
def to_xml_node(changeset_cache = {}, user_display_name_cache = {})
el = XML::Node.new 'way'
- el['id'] = self.way_id.to_s
+ el['id'] = way_id.to_s
add_metadata_to_xml_node(el, self, changeset_cache, user_display_name_cache)
- self.old_nodes.each do |nd| # FIXME need to make sure they come back in the right order
+ old_nodes.each do |nd| # FIXME need to make sure they come back in the right order
node_el = XML::Node.new 'nd'
node_el['ref'] = nd.node_id.to_s
el << node_el
end
- add_tags_to_xml_node(el, self.old_tags)
+ add_tags_to_xml_node(el, old_tags)
- return el
+ el
end
# Read full version of old way
# (i.e. is it visible? are we actually reverting to an earlier version?)
def get_nodes_undelete
- self.nds.collect do |n|
+ nds.collect do |n|
node = Node.find(n)
[node.lon, node.lat, n, node.version, node.tags_as_hash, node.visible]
end
end
def get_nodes_revert(timestamp)
- points=[]
- self.nds.each do |n|
+ points = []
+ nds.each do |n|
oldnode = OldNode.where('node_id = ? AND timestamp <= ?', n, timestamp).unredacted.order("timestamp DESC").first
curnode = Node.find(n)
id = n; reuse = curnode.visible
- if oldnode.lat != curnode.lat or oldnode.lon != curnode.lon or oldnode.tags != curnode.tags then
+ if oldnode.lat != curnode.lat || oldnode.lon != curnode.lon || oldnode.tags != curnode.tags
# node has changed: if it's in other ways, give it a new id
- if curnode.ways-[self.way_id] then id=-1; reuse=false end
+ if curnode.ways - [way_id] then id = -1; reuse = false end
end
points << [oldnode.lon, oldnode.lat, id, curnode.version, oldnode.tags_as_hash, reuse]
end
# Temporary method to match interface to nodes
def tags_as_hash
- return self.tags
+ tags
end
# Temporary method to match interface to ways
def way_nodes
- return self.old_nodes
+ old_nodes
end
# Pretend we're not in any relations
def containing_relation_members
- return []
+ []
end
# check whether this element is the latest version - that is,
# has the same version as its "current" counterpart.
def is_latest_version?
- current_way.version == self.version
+ current_way.version == version
end
end
has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation
validates_presence_of :id, :on => :update
- validates_presence_of :timestamp,:version, :changeset_id
+ validates_presence_of :timestamp, :version, :changeset_id
validates_uniqueness_of :id
- validates_inclusion_of :visible, :in => [ true, false ]
+ validates_inclusion_of :visible, :in => [true, false]
validates_numericality_of :id, :on => :update, :integer_only => true
validates_numericality_of :changeset_id, :version, :integer_only => true
validates_associated :changeset
scope :ways, ->(*ids) { joins(:relation_members).where(:current_relation_members => { :member_type => "Way", :member_id => ids.flatten }) }
scope :relations, ->(*ids) { joins(:relation_members).where(:current_relation_members => { :member_type => "Relation", :member_id => ids.flatten }) }
- TYPES = ["node", "way", "relation"]
+ TYPES = %w(node way relation)
- def self.from_xml(xml, create=false)
- begin
- p = XML::Parser.string(xml)
- doc = p.parse
+ def self.from_xml(xml, create = false)
+ p = XML::Parser.string(xml)
+ doc = p.parse
- doc.find('//osm/relation').each do |pt|
- return Relation.from_xml_node(pt, create)
- end
- raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/relation element.")
- rescue LibXML::XML::Error, ArgumentError => ex
- raise OSM::APIBadXMLError.new("relation", xml, ex.message)
+ doc.find('//osm/relation').each do |pt|
+ return Relation.from_xml_node(pt, create)
end
+ fail OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/relation element.")
+ rescue LibXML::XML::Error, ArgumentError => ex
+ raise OSM::APIBadXMLError.new("relation", xml, ex.message)
end
- def self.from_xml_node(pt, create=false)
+ def self.from_xml_node(pt, create = false)
relation = Relation.new
- raise OSM::APIBadXMLError.new("relation", pt, "Version is required when updating") unless create or not pt['version'].nil?
+ fail OSM::APIBadXMLError.new("relation", pt, "Version is required when updating") unless create || !pt['version'].nil?
relation.version = pt['version']
- raise OSM::APIBadXMLError.new("relation", pt, "Changeset id is missing") if pt['changeset'].nil?
+ fail OSM::APIBadXMLError.new("relation", pt, "Changeset id is missing") if pt['changeset'].nil?
relation.changeset_id = pt['changeset']
unless create
- raise OSM::APIBadXMLError.new("relation", pt, "ID is required when updating") if pt['id'].nil?
+ fail OSM::APIBadXMLError.new("relation", pt, "ID is required when updating") if pt['id'].nil?
relation.id = pt['id'].to_i
# .to_i will return 0 if there is no number that can be parsed.
# We want to make sure that there is no id with zero anyway
- raise OSM::APIBadUserInput.new("ID of relation cannot be zero when updating.") if relation.id == 0
+ fail OSM::APIBadUserInput.new("ID of relation cannot be zero when updating.") if relation.id == 0
end
# We don't care about the timestamp nor the visibility as these are either
relation.visible = true
# Start with no tags
- relation.tags = Hash.new
+ relation.tags = {}
# Add in any tags from the XML
pt.find('tag').each do |tag|
- raise OSM::APIBadXMLError.new("relation", pt, "tag is missing key") if tag['k'].nil?
- raise OSM::APIBadXMLError.new("relation", pt, "tag is missing value") if tag['v'].nil?
+ fail OSM::APIBadXMLError.new("relation", pt, "tag is missing key") if tag['k'].nil?
+ fail OSM::APIBadXMLError.new("relation", pt, "tag is missing value") if tag['v'].nil?
relation.add_tag_keyval(tag['k'], tag['v'])
end
# isn't done for a new relation then @members attribute will be nil,
# and the members will be loaded from the database instead of being
# empty, as intended.
- relation.members = Array.new
+ relation.members = []
pt.find('member').each do |member|
- #member_type =
+ # member_type =
logger.debug "each member"
- raise OSM::APIBadXMLError.new("relation", pt, "The #{member['type']} is not allowed only, #{TYPES.inspect} allowed") unless TYPES.include? member['type']
+ fail OSM::APIBadXMLError.new("relation", pt, "The #{member['type']} is not allowed only, #{TYPES.inspect} allowed") unless TYPES.include? member['type']
logger.debug "after raise"
- #member_ref = member['ref']
- #member_role
+ # member_ref = member['ref']
+ # member_role
member['role'] ||= "" # Allow the upload to not include this, in which case we default to an empty string.
logger.debug member['role']
relation.add_member(member['type'].classify, member['ref'], member['role'])
end
- raise OSM::APIBadUserInput.new("Some bad xml in relation") if relation.nil?
+ fail OSM::APIBadUserInput.new("Some bad xml in relation") if relation.nil?
- return relation
+ relation
end
def to_xml
doc = OSM::API.new.get_xml_doc
- doc.root << to_xml_node()
- return doc
+ doc.root << to_xml_node
+ doc
end
def to_xml_node(visible_members = nil, changeset_cache = {}, user_display_name_cache = {})
el = XML::Node.new 'relation'
- el['id'] = self.id.to_s
+ el['id'] = id.to_s
add_metadata_to_xml_node(el, self, changeset_cache, user_display_name_cache)
- self.relation_members.each do |member|
- p=0
+ relation_members.each do |member|
+ p = 0
if visible_members
# if there is a list of visible members then use that to weed out deleted segments
if visible_members[member.member_type][member.member_id]
- p=1
+ p = 1
end
else
# otherwise, manually go to the db to check things
if member.member.visible?
- p=1
+ p = 1
end
end
if p
end
end
- add_tags_to_xml_node(el, self.relation_tags)
+ add_tags_to_xml_node(el, relation_tags)
- return el
+ el
end
# FIXME is this really needed?
def members
- @members ||= self.relation_members.map do |member|
+ @members ||= relation_members.map do |member|
[member.member_type, member.member_id, member.member_role]
end
end
def tags
- @tags ||= Hash[self.relation_tags.collect { |t| [t.k, t.v] }]
+ @tags ||= Hash[relation_tags.collect { |t| [t.k, t.v] }]
end
- def members=(m)
- @members = m
- end
+ attr_writer :members
- def tags=(t)
- @tags = t
- end
+ attr_writer :tags
def add_member(type, id, role)
@members ||= []
end
def add_tag_keyval(k, v)
- @tags = Hash.new unless @tags
+ @tags = {} unless @tags
# duplicate tags are now forbidden, so we can't allow values
# in the hash to be overwritten.
- raise OSM::APIDuplicateTagsError.new("relation", self.id, k) if @tags.include? k
+ fail OSM::APIDuplicateTagsError.new("relation", id, k) if @tags.include? k
@tags[k] = v
end
end
def delete_with_history!(new_relation, user)
- unless self.visible
- raise OSM::APIAlreadyDeletedError.new("relation", new_relation.id)
+ unless visible
+ fail OSM::APIAlreadyDeletedError.new("relation", new_relation.id)
end
# need to start the transaction here, so that the database can
self.lock!
check_consistency(self, new_relation, user)
# This will check to see if this relation is used by another relation
- rel = RelationMember.joins(:relation).where("visible = ? AND member_type = 'Relation' and member_id = ? ", true, self.id).first
- raise OSM::APIPreconditionFailedError.new("The relation #{new_relation.id} is used in relation #{rel.relation.id}.") unless rel.nil?
+ rel = RelationMember.joins(:relation).where("visible = ? AND member_type = 'Relation' and member_id = ? ", true, id).first
+ fail OSM::APIPreconditionFailedError.new("The relation #{new_relation.id} is used in relation #{rel.relation.id}.") unless rel.nil?
self.changeset_id = new_relation.changeset_id
self.tags = {}
Relation.transaction do
self.lock!
check_consistency(self, new_relation, user)
- unless new_relation.preconditions_ok?(self.members)
- raise OSM::APIPreconditionFailedError.new("Cannot update relation #{self.id}: data or member data is invalid.")
+ unless new_relation.preconditions_ok?(members)
+ fail OSM::APIPreconditionFailedError.new("Cannot update relation #{id}: data or member data is invalid.")
end
self.changeset_id = new_relation.changeset_id
self.changeset = new_relation.changeset
def create_with_history(user)
check_create_consistency(self, user)
unless self.preconditions_ok?
- raise OSM::APIPreconditionFailedError.new("Cannot create relation: data or member data is invalid.")
+ fail OSM::APIPreconditionFailedError.new("Cannot create relation: data or member data is invalid.")
end
self.version = 0
self.visible = true
# Thus if you have nodes with the ids of 50 and 1 already in the
# relation, then the hash table nodes would contain:
# => {50=>true, 1=>true}
- elements = { :node => Hash.new, :way => Hash.new, :relation => Hash.new }
+ elements = { :node => {}, :way => {}, :relation => {} }
# pre-set all existing members to good
good_members.each { |m| elements[m[0].downcase.to_sym][m[1]] = true }
- self.members.each do |m|
+ members.each do |m|
# find the hash for the element type or die
- hash = elements[m[0].downcase.to_sym] or return false
+ hash = elements[m[0].downcase.to_sym]
+ return false unless hash
# unless its in the cache already
unless hash.key? m[1]
# use reflection to look up the appropriate class
element = model.where(:id => m[1]).first
# and check that it is OK to use.
- unless element and element.visible? and element.preconditions_ok?
- raise OSM::APIPreconditionFailedError.new("Relation with id #{self.id} cannot be saved due to #{m[0]} with id #{m[1]}")
+ unless element && element.visible? && element.preconditions_ok?
+ fail OSM::APIPreconditionFailedError.new("Relation with id #{id} cannot be saved due to #{m[0]} with id #{m[1]}")
end
hash[m[1]] = true
end
end
- return true
+ true
end
# Temporary method to match interface to nodes
def tags_as_hash
- return self.tags
+ tags
end
##
# this calling this method will fix them using the map from placeholders
# to IDs +id_map+.
def fix_placeholders!(id_map, placeholder_id = nil)
- self.members.map! do |type, id, role|
+ members.map! do |type, id, role|
old_id = id.to_i
if old_id < 0
new_id = id_map[type.downcase.to_sym][old_id]
- raise OSM::APIBadUserInput.new("Placeholder #{type} not found for reference #{old_id} in relation #{self.id.nil? ? placeholder_id : self.id}.") if new_id.nil?
+ fail OSM::APIBadUserInput.new("Placeholder #{type} not found for reference #{old_id} in relation #{self.id.nil? ? placeholder_id : self.id}.") if new_id.nil?
[type, new_id, role]
else
[type, id, role]
self.save!
tags = self.tags.clone
- self.relation_tags.each do |old_tag|
+ relation_tags.each do |old_tag|
key = old_tag.k
# if we can match the tags we currently have to the list
# of old tags, then we never set the tags_changed flag. but
# if any are different then set the flag and do the DB
# update.
- if tags.has_key? key
+ if tags.key? key
tags_changed |= (old_tag.v != tags[key])
# remove from the map, so that we can expect an empty map
end
# if there are left-over tags then they are new and will have to
# be added.
- tags_changed |= (not tags.empty?)
- RelationTag.delete_all(:relation_id => self.id)
- self.tags.each do |k,v|
+ tags_changed |= (!tags.empty?)
+ RelationTag.delete_all(:relation_id => id)
+ self.tags.each do |k, v|
tag = RelationTag.new
- tag.relation_id = self.id
+ tag.relation_id = id
tag.k = k
tag.v = v
tag.save!
# same pattern as before, but this time we're collecting the
# changed members in an array, as the bounding box updates for
# elements are per-element, not blanked on/off like for tags.
- changed_members = Array.new
+ changed_members = []
members = self.members.clone
- self.relation_members.each do |old_member|
+ relation_members.each do |old_member|
key = [old_member.member_type, old_member.member_id, old_member.member_role]
i = members.index key
if i.nil?
# members may be in a different order and i don't feel like implementing
# a longest common subsequence algorithm to optimise this.
members = self.members
- RelationMember.delete_all(:relation_id => self.id)
- members.each_with_index do |m,i|
+ RelationMember.delete_all(:relation_id => id)
+ members.each_with_index do |m, i|
mem = RelationMember.new
- mem.relation_id = self.id
+ mem.relation_id = id
mem.sequence_id = i
mem.member_type = m[0]
mem.member_id = m[1]
# reasonable on the assumption that adding or removing members doesn't
# materially change the rest of the relation.
any_relations =
- changed_members.collect { |id,type| type == "relation" }.
- inject(false) { |b,s| b or s }
+ changed_members.collect { |_id, type| type == "relation" }
+ .inject(false) { |b, s| b || s }
- update_members = if tags_changed or any_relations
+ update_members = if tags_changed || any_relations
# add all non-relation bounding boxes to the changeset
# FIXME: check for tag changes along with element deletions and
# make sure that the deleted element's bounding box is hit.
else
changed_members
end
- update_members.each do |type, id, role|
+ update_members.each do |type, id, _role|
if type != "Relation"
update_changeset_element(type, id)
end
changeset.save!
end
end
-
end
class RequestToken < OauthToken
-
attr_accessor :provided_oauth_verifier
def authorize!(user)
return false if authorized?
self.user = user
self.authorized_at = Time.now
- self.verifier = OAuth::Helper.generate_key(20)[0,20] unless oauth10?
- self.save
+ self.verifier = OAuth::Helper.generate_key(20)[0, 20] unless oauth10?
+ save
end
def exchange!
RequestToken.transaction do
params = { :user => user, :client_application => client_application }
# copy the permissions from the authorised request token to the access token
- client_application.permissions.each { |p|
+ client_application.permissions.each do |p|
params[p] = read_attribute(p)
- }
+ end
access_token = AccessToken.create(params)
invalidate!
end
def oauth10?
- (defined? OAUTH_10_SUPPORT) && OAUTH_10_SUPPORT && self.callback_url.blank?
+ (defined? OAUTH_10_SUPPORT) && OAUTH_10_SUPPORT && callback_url.blank?
end
-
end
scope :visible, -> { where(:visible => true) }
scope :visible_to, ->(u) { visible.where("visibility IN ('public', 'identifiable') OR user_id = ?", u) }
- scope :visible_to_all, -> { where(:visibility => ["public", "identifiable"]) }
+ scope :visible_to_all, -> { where(:visibility => %w(public identifiable)) }
scope :tagged, ->(t) { joins(:tags).where(:gpx_file_tags => { :tag => t }) }
validates_presence_of :user_id, :name, :timestamp
validates_presence_of :description, :on => :create
validates_length_of :name, :maximum => 255
validates_length_of :description, :maximum => 255
-# validates_numericality_of :latitude, :longitude
- validates_inclusion_of :inserted, :in => [ true, false ]
- validates_inclusion_of :visibility, :in => ["private", "public", "trackable", "identifiable"]
+ # validates_numericality_of :latitude, :longitude
+ validates_inclusion_of :inserted, :in => [true, false]
+ validates_inclusion_of :visibility, :in => %w(private public trackable identifiable)
def destroy
super
end
def tagstring
- return tags.collect {|tt| tt.tag}.join(", ")
+ tags.collect(&:tag).join(", ")
end
def tagstring=(s)
if s.include? ','
- self.tags = s.split(/\s*,\s*/).select {|tag| tag !~ /^\s*$/}.collect {|tag|
+ self.tags = s.split(/\s*,\s*/).select { |tag| tag !~ /^\s*$/ }.collect {|tag|
tt = Tracetag.new
tt.tag = tag
tt
}
else
- #do as before for backwards compatibility:
- self.tags = s.split().collect {|tag|
+ # do as before for backwards compatibility:
+ self.tags = s.split.collect {|tag|
tt = Tracetag.new
tt.tag = tag
tt
visibility == "identifiable"
end
- def large_picture= (data)
+ def large_picture=(data)
f = File.new(large_picture_name, "wb")
f.syswrite(data)
f.close
end
- def icon_picture= (data)
+ def icon_picture=(data)
f = File.new(icon_picture_name, "wb")
f.syswrite(data)
f.close
bzipped = filetype =~ /bzip2 compressed/
zipped = filetype =~ /Zip archive/
- if gzipped then
+ if gzipped
mimetype = "application/x-gzip"
- elsif bzipped then
+ elsif bzipped
mimetype = "application/x-bzip2"
elsif zipped
mimetype = "application/x-zip"
mimetype = "application/gpx+xml"
end
- return mimetype
+ mimetype
end
def extension_name
zipped = filetype =~ /Zip archive/
tarred = filetype =~ /tar archive/
- if tarred and gzipped then
+ if tarred && gzipped
extension = ".tar.gz"
- elsif tarred and bzipped then
+ elsif tarred && bzipped
extension = ".tar.bz2"
elsif tarred
extension = ".tar"
extension = ".gpx"
end
- return extension
+ extension
end
def to_xml
doc = OSM::API.new.get_xml_doc
- doc.root << to_xml_node()
- return doc
+ doc.root << to_xml_node
+ doc
end
def to_xml_node
el1 = XML::Node.new 'gpx_file'
- el1['id'] = self.id.to_s
- el1['name'] = self.name.to_s
- el1['lat'] = self.latitude.to_s if self.inserted
- el1['lon'] = self.longitude.to_s if self.inserted
- el1['user'] = self.user.display_name
- el1['visibility'] = self.visibility
- el1['pending'] = (!self.inserted).to_s
- el1['timestamp'] = self.timestamp.xmlschema
+ el1['id'] = id.to_s
+ el1['name'] = name.to_s
+ el1['lat'] = latitude.to_s if inserted
+ el1['lon'] = longitude.to_s if inserted
+ el1['user'] = user.display_name
+ el1['visibility'] = visibility
+ el1['pending'] = (!inserted).to_s
+ el1['timestamp'] = timestamp.xmlschema
el2 = XML::Node.new 'description'
- el2 << self.description
+ el2 << description
el1 << el2
- self.tags.each do |tag|
+ tags.each do |tag|
el2 = XML::Node.new('tag')
el2 << tag.tag
el1 << el2
end
- return el1
+ el1
end
# Read in xml as text and return it's Node object representation
- def self.from_xml(xml, create=false)
- begin
- p = XML::Parser.string(xml)
- doc = p.parse
-
- doc.find('//osm/gpx_file').each do |pt|
- return Trace.from_xml_node(pt, create)
- end
+ def self.from_xml(xml, create = false)
+ p = XML::Parser.string(xml)
+ doc = p.parse
- raise OSM::APIBadXMLError.new("trace", xml, "XML doesn't contain an osm/gpx_file element.")
- rescue LibXML::XML::Error, ArgumentError => ex
- raise OSM::APIBadXMLError.new("trace", xml, ex.message)
+ doc.find('//osm/gpx_file').each do |pt|
+ return Trace.from_xml_node(pt, create)
end
+
+ fail OSM::APIBadXMLError.new("trace", xml, "XML doesn't contain an osm/gpx_file element.")
+ rescue LibXML::XML::Error, ArgumentError => ex
+ raise OSM::APIBadXMLError.new("trace", xml, ex.message)
end
- def self.from_xml_node(pt, create=false)
+ def self.from_xml_node(pt, create = false)
trace = Trace.new
- raise OSM::APIBadXMLError.new("trace", pt, "visibility missing") if pt['visibility'].nil?
+ fail OSM::APIBadXMLError.new("trace", pt, "visibility missing") if pt['visibility'].nil?
trace.visibility = pt['visibility']
unless create
- raise OSM::APIBadXMLError.new("trace", pt, "ID is required when updating.") if pt['id'].nil?
+ fail OSM::APIBadXMLError.new("trace", pt, "ID is required when updating.") if pt['id'].nil?
trace.id = pt['id'].to_i
# .to_i will return 0 if there is no number that can be parsed.
# We want to make sure that there is no id with zero anyway
- raise OSM::APIBadUserInput.new("ID of trace cannot be zero when updating.") if trace.id == 0
+ fail OSM::APIBadUserInput.new("ID of trace cannot be zero when updating.") if trace.id == 0
end
# We don't care about the time, as it is explicitly set on create/update/delete
trace.visible = true
description = pt.find('description').first
- raise OSM::APIBadXMLError.new("trace", pt, "description missing") if description.nil?
+ fail OSM::APIBadXMLError.new("trace", pt, "description missing") if description.nil?
trace.description = description.content
pt.find('tag').each do |tag|
trace.tags.build(:tag => tag.content)
end
- return trace
+ trace
end
def xml_file
zipped = filetype =~ /Zip archive/
tarred = filetype =~ /tar archive/
- if gzipped or bzipped or zipped or tarred then
- tmpfile = Tempfile.new("trace.#{id}");
+ if gzipped || bzipped || zipped || tarred
+ tmpfile = Tempfile.new("trace.#{id}")
- if tarred and gzipped then
+ if tarred && gzipped
system("tar -zxOf #{trace_name} > #{tmpfile.path}")
- elsif tarred and bzipped then
+ elsif tarred && bzipped
system("tar -jxOf #{trace_name} > #{tmpfile.path}")
elsif tarred
system("tar -xOf #{trace_name} > #{tmpfile.path}")
file = File.open(trace_name)
end
- return file
+ file
end
def import
logger.info("GPX Import importing #{name} (#{id}) from #{user.email}")
- gpx = GPX::File.new(self.xml_file)
+ gpx = GPX::File.new(xml_file)
f_lat = 0
f_lon = 0
# If there are any existing points for this trace then delete
# them - we check for existing points first to avoid locking
# the table in the common case where there aren't any.
- if Tracepoint.where(:gpx_id => self.id).exists?
- Tracepoint.delete_all(:gpx_id => self.id)
+ if Tracepoint.where(:gpx_id => id).exists?
+ Tracepoint.delete_all(:gpx_id => id)
end
gpx.points do |point|
logger.info "done trace #{id}"
- return gpx
+ gpx
end
end
def to_xml_node(print_timestamp = false)
el1 = XML::Node.new 'trkpt'
- el1['lat'] = self.lat.to_s
- el1['lon'] = self.lon.to_s
- el1 << (XML::Node.new("time") << self.timestamp.xmlschema) if print_timestamp
- return el1
+ el1['lat'] = lat.to_s
+ el1['lon'] = lon.to_s
+ el1 << (XML::Node.new("time") << timestamp.xmlschema) if print_timestamp
+ el1
end
end
has_many :messages, -> { where(:to_user_visible => true).order(:sent_on => :desc).preload(:sender, :recipient) }, :foreign_key => :to_user_id
has_many :new_messages, -> { where(:to_user_visible => true, :message_read => false).order(:sent_on => :desc) }, :class_name => "Message", :foreign_key => :to_user_id
has_many :sent_messages, -> { where(:from_user_visible => true).order(:sent_on => :desc).preload(:sender, :recipient) }, :class_name => "Message", :foreign_key => :from_user_id
- has_many :friends, -> { joins(:befriendee).where(:users => { :status => ["active", "confirmed"] }) }
+ has_many :friends, -> { joins(:befriendee).where(:users => { :status => %w(active confirmed) }) }
has_many :friend_users, :through => :friends, :source => :befriendee
has_many :tokens, :class_name => "UserToken"
has_many :preferences, :class_name => "UserPreference"
has_many :roles, :class_name => "UserRole"
- scope :visible, -> { where(:status => ["pending", "active", "confirmed"]) }
- scope :active, -> { where(:status => ["active", "confirmed"]) }
+ scope :visible, -> { where(:status => %w(pending active confirmed)) }
+ scope :active, -> { where(:status => %w(active confirmed)) }
scope :identifiable, -> { where(:data_public => true) }
has_attached_file :image,
- :default_url => "/assets/:class/:attachment/:style.png",
- :styles => { :large => "100x100>", :small => "50x50>" }
+ :default_url => "/assets/:class/:attachment/:style.png",
+ :styles => { :large => "100x100>", :small => "50x50>" }
validates_presence_of :email, :display_name
- validates_confirmation_of :email#, :message => ' addresses must match'
- validates_confirmation_of :pass_crypt#, :message => ' must match the confirmation password'
- validates_uniqueness_of :display_name, :allow_nil => true, :case_sensitive => false, :if => Proc.new { |u| u.display_name_changed? }
- validates_uniqueness_of :email, :case_sensitive => false, :if => Proc.new { |u| u.email_changed? }
+ validates_confirmation_of :email # , :message => ' addresses must match'
+ validates_confirmation_of :pass_crypt # , :message => ' must match the confirmation password'
+ validates_uniqueness_of :display_name, :allow_nil => true, :case_sensitive => false, :if => proc { |u| u.display_name_changed? }
+ validates_uniqueness_of :email, :case_sensitive => false, :if => proc { |u| u.email_changed? }
validates_uniqueness_of :openid_url, :allow_nil => true
validates_length_of :pass_crypt, :within => 8..255
validates_length_of :display_name, :within => 3..255, :allow_nil => true
- validates_email_format_of :email, :if => Proc.new { |u| u.email_changed? }
- validates_email_format_of :new_email, :allow_blank => true, :if => Proc.new { |u| u.new_email_changed? }
- validates_format_of :display_name, :with => /\A[^\x00-\x1f\x7f\ufffe\uffff\/;.,?%#]*\z/, :if => Proc.new { |u| u.display_name_changed? }
- validates_format_of :display_name, :with => /\A\S/, :message => "has leading whitespace", :if => Proc.new { |u| u.display_name_changed? }
- validates_format_of :display_name, :with => /\S\z/, :message => "has trailing whitespace", :if => Proc.new { |u| u.display_name_changed? }
+ validates_email_format_of :email, :if => proc { |u| u.email_changed? }
+ validates_email_format_of :new_email, :allow_blank => true, :if => proc { |u| u.new_email_changed? }
+ validates_format_of :display_name, :with => /\A[^\x00-\x1f\x7f\ufffe\uffff\/;.,?%#]*\z/, :if => proc { |u| u.display_name_changed? }
+ validates_format_of :display_name, :with => /\A\S/, :message => "has leading whitespace", :if => proc { |u| u.display_name_changed? }
+ validates_format_of :display_name, :with => /\S\z/, :message => "has trailing whitespace", :if => proc { |u| u.display_name_changed? }
validates_exclusion_of :display_name, :in => %w(new terms save confirm confirm-email go_public reset-password forgot-password suspended)
validates_numericality_of :home_lat, :allow_nil => true
validates_numericality_of :home_lon, :allow_nil => true
after_save :spam_check
def self.authenticate(options)
- if options[:username] and options[:password]
+ if options[:username] && options[:password]
user = where("email = ? OR display_name = ?", options[:username], options[:username]).first
if user.nil?
end
end
- if user and PasswordHash.check(user.pass_crypt, user.pass_salt, options[:password])
+ if user && PasswordHash.check(user.pass_crypt, user.pass_salt, options[:password])
if PasswordHash.upgrade?(user.pass_crypt, user.pass_salt)
user.pass_crypt, user.pass_salt = PasswordHash.create(options[:password])
user.save
user = token.user if token
end
- if user and
- ( user.status == "deleted" or
- ( user.status == "pending" and not options[:pending] ) or
- ( user.status == "suspended" and not options[:suspended] ) )
+ if user &&
+ (user.status == "deleted" ||
+ (user.status == "pending" && !options[:pending]) ||
+ (user.status == "suspended" && !options[:suspended]))
user = nil
end
- token.update_column(:expiry, 1.week.from_now) if token and user
+ token.update_column(:expiry, 1.week.from_now) if token && user
- return user
+ user
end
def to_xml
doc = OSM::API.new.get_xml_doc
- doc.root << to_xml_node()
- return doc
+ doc.root << to_xml_node
+ doc
end
def to_xml_node
el1 = XML::Node.new 'user'
- el1['display_name'] = self.display_name.to_s
- el1['account_created'] = self.creation_time.xmlschema
- if self.home_lat and self.home_lon
+ el1['display_name'] = display_name.to_s
+ el1['account_created'] = creation_time.xmlschema
+ if home_lat && home_lon
home = XML::Node.new 'home'
- home['lat'] = self.home_lat.to_s
- home['lon'] = self.home_lon.to_s
- home['zoom'] = self.home_zoom.to_s
+ home['lat'] = home_lat.to_s
+ home['lon'] = home_lon.to_s
+ home['zoom'] = home_zoom.to_s
el1 << home
end
- return el1
+ el1
end
def description
end
def preferred_language_from(array)
- (languages & array.collect { |i| i.to_s }).first
+ (languages & array.collect(&:to_s)).first
end
def nearby(radius = NEARBY_RADIUS, num = NEARBY_USERS)
- if self.home_lon and self.home_lat
- gc = OSM::GreatCircle.new(self.home_lat, self.home_lon)
+ if home_lon && home_lat
+ gc = OSM::GreatCircle.new(home_lat, home_lon)
bounds = gc.bounds(radius)
sql_for_distance = gc.sql_for_distance("home_lat", "home_lon")
nearby = User.where("id != ? AND status IN (\'active\', \'confirmed\') AND data_public = ? AND #{sql_for_distance} <= ?", id, true, radius).order(sql_for_distance).limit(num)
else
nearby = []
end
- return nearby
+ nearby
end
def distance(nearby_user)
- return OSM::GreatCircle.new(self.home_lat, self.home_lon).distance(nearby_user.home_lat, nearby_user.home_lon)
+ OSM::GreatCircle.new(home_lat, home_lon).distance(nearby_user.home_lat, nearby_user.home_lon)
end
def is_friends_with?(new_friend)
- self.friends.where(:friend_user_id => new_friend.id).exists?
+ friends.where(:friend_user_id => new_friend.id).exists?
end
##
# returns true if a user is visible
def visible?
- ["pending","active","confirmed"].include? self.status
+ %w(pending active confirmed).include? status
end
##
# returns true if a user is active
def active?
- ["active","confirmed"].include? self.status
+ %w(active confirmed).include? status
end
##
# returns the first active block which would require users to view
# a message, or nil if there are none.
def blocked_on_view
- blocks.active.detect { |b| b.needs_view? }
+ blocks.active.detect(&:needs_view?)
end
##
# delete a user - leave the account but purge most personal data
def delete
- self.display_name = "user_#{self.id}"
+ self.display_name = "user_#{id}"
self.description = ""
self.home_lat = nil
self.home_lon = nil
self.new_email = nil
self.openid_url = nil
self.status = "deleted"
- self.save
+ save
end
##
# return a spam score for a user
def spam_score
- changeset_score = self.changesets.size * 50
- trace_score = self.traces.size * 50
- diary_entry_score = self.diary_entries.inject(0) { |s,e| s += e.body.spam_score }
- diary_comment_score = self.diary_comments.inject(0) { |s,c| s += c.body.spam_score }
-
- score = self.description.spam_score / 4.0
- score += self.diary_entries.where("created_at > ?", 1.day.ago).count * 10
- score += diary_entry_score / self.diary_entries.length if self.diary_entries.length > 0
- score += diary_comment_score / self.diary_comments.length if self.diary_comments.length > 0
+ changeset_score = changesets.size * 50
+ trace_score = traces.size * 50
+ diary_entry_score = diary_entries.inject(0) { |s, e| s += e.body.spam_score }
+ diary_comment_score = diary_comments.inject(0) { |s, c| s += c.body.spam_score }
+
+ score = description.spam_score / 4.0
+ score += diary_entries.where("created_at > ?", 1.day.ago).count * 10
+ score += diary_entry_score / diary_entries.length if diary_entries.length > 0
+ score += diary_comment_score / diary_comments.length if diary_comments.length > 0
score -= changeset_score
score -= trace_score
- return score.to_i
+ score.to_i
end
##
# perform a spam check on a user
def spam_check
- if status == "active" and spam_score > SPAM_THRESHOLD
+ if status == "active" && spam_score > SPAM_THRESHOLD
update_column(:status, "suspended")
end
end
##
# return an oauth access token for a specified application
def access_token(application_key)
- return ClientApplication.find_by_key(application_key).access_token_for_user(self)
+ ClientApplication.find_by_key(application_key).access_token_for_user(self)
end
-private
+ private
def set_defaults
self.creation_time = Time.now.getutc unless self.attribute_present?(:creation_time)
##
# scope to match active blocks
def self.active
- self.where("needs_view or ends_at > ?", Time.now.getutc)
+ where("needs_view or ends_at > ?", Time.now.getutc)
end
##
# returns true if the block is currently active (i.e: the user can't
# use the API).
def active?
- needs_view or ends_at > Time.now.getutc
+ needs_view || ends_at > Time.now.getutc
end
##
# is the user object who is revoking the ban.
def revoke!(revoker)
update_attributes(
- :ends_at => Time.now.getutc(),
+ :ends_at => Time.now.getutc,
:revoker_id => revoker.id,
:needs_view => false
)
end
-private
+ private
##
# validate that only moderators are allowed to change the
# block. this should be caught and dealt with in the controller,
# but i've also included it here just in case.
def moderator_permissions
- errors.add(:base, I18n.t('user_block.model.non_moderator_update')) if creator_id_changed? and !creator.moderator?
- errors.add(:base, I18n.t('user_block.model.non_moderator_revoke')) unless revoker_id.nil? or revoker.moderator?
+ errors.add(:base, I18n.t('user_block.model.non_moderator_update')) if creator_id_changed? && !creator.moderator?
+ errors.add(:base, I18n.t('user_block.model.non_moderator_revoke')) unless revoker_id.nil? || revoker.moderator?
end
end
# Turn this Node in to an XML Node without the <osm> wrapper.
def to_xml_node
el1 = XML::Node.new 'preference'
- el1['k'] = self.k
- el1['v'] = self.v
+ el1['k'] = k
+ el1['v'] = v
- return el1
+ el1
end
-
end
class UserRole < ActiveRecord::Base
belongs_to :user
- ALL_ROLES = ['administrator', 'moderator']
+ ALL_ROLES = %w(administrator moderator)
validates_inclusion_of :role, :in => ALL_ROLES
validates_uniqueness_of :role, :scope => :user_id
expiry < Time.now
end
-private
+ private
def set_defaults
- self.token = OSM::make_token() if self.token.blank?
- self.expiry = 1.week.from_now if self.expiry.blank?
+ self.token = OSM.make_token if token.blank?
+ self.expiry = 1.week.from_now if expiry.blank?
end
end
has_many :containing_relations, :class_name => "Relation", :through => :containing_relation_members, :source => :relation
validates_presence_of :id, :on => :update
- validates_presence_of :changeset_id,:version, :timestamp
+ validates_presence_of :changeset_id, :version, :timestamp
validates_uniqueness_of :id
- validates_inclusion_of :visible, :in => [ true, false ]
+ validates_inclusion_of :visible, :in => [true, false]
validates_numericality_of :changeset_id, :version, :integer_only => true
validates_numericality_of :id, :on => :update, :integer_only => true
validates_associated :changeset
scope :invisible, -> { where(:visible => false) }
# Read in xml as text and return it's Way object representation
- def self.from_xml(xml, create=false)
- begin
- p = XML::Parser.string(xml)
- doc = p.parse
+ def self.from_xml(xml, create = false)
+ p = XML::Parser.string(xml)
+ doc = p.parse
- doc.find('//osm/way').each do |pt|
- return Way.from_xml_node(pt, create)
- end
- raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/way element.")
- rescue LibXML::XML::Error, ArgumentError => ex
- raise OSM::APIBadXMLError.new("way", xml, ex.message)
+ doc.find('//osm/way').each do |pt|
+ return Way.from_xml_node(pt, create)
end
+ fail OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/way element.")
+ rescue LibXML::XML::Error, ArgumentError => ex
+ raise OSM::APIBadXMLError.new("way", xml, ex.message)
end
- def self.from_xml_node(pt, create=false)
+ def self.from_xml_node(pt, create = false)
way = Way.new
- raise OSM::APIBadXMLError.new("way", pt, "Version is required when updating") unless create or not pt['version'].nil?
+ fail OSM::APIBadXMLError.new("way", pt, "Version is required when updating") unless create || !pt['version'].nil?
way.version = pt['version']
- raise OSM::APIBadXMLError.new("way", pt, "Changeset id is missing") if pt['changeset'].nil?
+ fail OSM::APIBadXMLError.new("way", pt, "Changeset id is missing") if pt['changeset'].nil?
way.changeset_id = pt['changeset']
unless create
- raise OSM::APIBadXMLError.new("way", pt, "ID is required when updating") if pt['id'].nil?
+ fail OSM::APIBadXMLError.new("way", pt, "ID is required when updating") if pt['id'].nil?
way.id = pt['id'].to_i
# .to_i will return 0 if there is no number that can be parsed.
# We want to make sure that there is no id with zero anyway
- raise OSM::APIBadUserInput.new("ID of way cannot be zero when updating.") if way.id == 0
+ fail OSM::APIBadUserInput.new("ID of way cannot be zero when updating.") if way.id == 0
end
# We don't care about the timestamp nor the visibility as these are either
way.visible = true
# Start with no tags
- way.tags = Hash.new
+ way.tags = {}
# Add in any tags from the XML
pt.find('tag').each do |tag|
- raise OSM::APIBadXMLError.new("way", pt, "tag is missing key") if tag['k'].nil?
- raise OSM::APIBadXMLError.new("way", pt, "tag is missing value") if tag['v'].nil?
+ fail OSM::APIBadXMLError.new("way", pt, "tag is missing key") if tag['k'].nil?
+ fail OSM::APIBadXMLError.new("way", pt, "tag is missing value") if tag['v'].nil?
way.add_tag_keyval(tag['k'], tag['v'])
end
way.add_nd_num(nd['ref'])
end
- return way
+ way
end
# Find a way given it's ID, and in a single SQL call also grab its nodes
# You can't pull in all the tags too unless we put a sequence_id on the way_tags table and have a multipart key
def self.find_eager(id)
- way = Way.find(id, :include => {:way_nodes => :node})
- #If waytag had a multipart key that was real, you could do this:
- #way = Way.find(id, :include => [:way_tags, {:way_nodes => :node}])
+ way = Way.find(id, :include => { :way_nodes => :node })
+ # If waytag had a multipart key that was real, you could do this:
+ # way = Way.find(id, :include => [:way_tags, {:way_nodes => :node}])
end
# Find a way given it's ID, and in a single SQL call also grab its nodes and tags
def to_xml
doc = OSM::API.new.get_xml_doc
- doc.root << to_xml_node()
- return doc
+ doc.root << to_xml_node
+ doc
end
def to_xml_node(visible_nodes = nil, changeset_cache = {}, user_display_name_cache = {})
el = XML::Node.new 'way'
- el['id'] = self.id.to_s
+ el['id'] = id.to_s
add_metadata_to_xml_node(el, self, changeset_cache, user_display_name_cache)
# make sure nodes are output in sequence_id order
ordered_nodes = []
- self.way_nodes.each do |nd|
+ way_nodes.each do |nd|
if visible_nodes
# if there is a list of visible nodes then use that to weed out deleted nodes
if visible_nodes[nd.node_id]
end
else
# otherwise, manually go to the db to check things
- if nd.node and nd.node.visible?
+ if nd.node && nd.node.visible?
ordered_nodes[nd.sequence_id] = nd.node_id.to_s
end
end
end
ordered_nodes.each do |nd_id|
- if nd_id and nd_id != '0'
+ if nd_id && nd_id != '0'
node_el = XML::Node.new 'nd'
node_el['ref'] = nd_id
el << node_el
end
end
- add_tags_to_xml_node(el, self.way_tags)
+ add_tags_to_xml_node(el, way_tags)
- return el
+ el
end
def nds
- @nds ||= self.way_nodes.collect { |n| n.node_id }
+ @nds ||= way_nodes.collect(&:node_id)
end
def tags
- @tags ||= Hash[self.way_tags.collect { |t| [t.k, t.v] }]
+ @tags ||= Hash[way_tags.collect { |t| [t.k, t.v] }]
end
- def nds=(s)
- @nds = s
- end
+ attr_writer :nds
- def tags=(t)
- @tags = t
- end
+ attr_writer :tags
def add_nd_num(n)
- @nds = Array.new unless @nds
+ @nds = [] unless @nds
@nds << n.to_i
end
def add_tag_keyval(k, v)
- @tags = Hash.new unless @tags
+ @tags = {} unless @tags
# duplicate tags are now forbidden, so we can't allow values
# in the hash to be overwritten.
- raise OSM::APIDuplicateTagsError.new("way", self.id, k) if @tags.include? k
+ fail OSM::APIDuplicateTagsError.new("way", id, k) if @tags.include? k
@tags[k] = v
end
# the integer coords (i.e: unscaled) bounding box of the way, assuming
# straight line segments.
def bbox
- lons = nodes.collect { |n| n.longitude }
- lats = nodes.collect { |n| n.latitude }
+ lons = nodes.collect(&:longitude)
+ lats = nodes.collect(&:latitude)
BoundingBox.new(lons.min, lats.min, lons.max, lats.max)
end
Way.transaction do
self.lock!
check_consistency(self, new_way, user)
- unless new_way.preconditions_ok?(self.nds)
- raise OSM::APIPreconditionFailedError.new("Cannot update way #{self.id}: data is invalid.")
+ unless new_way.preconditions_ok?(nds)
+ fail OSM::APIPreconditionFailedError.new("Cannot update way #{id}: data is invalid.")
end
self.changeset_id = new_way.changeset_id
def create_with_history(user)
check_create_consistency(self, user)
unless self.preconditions_ok?
- raise OSM::APIPreconditionFailedError.new("Cannot create way: data is invalid.")
+ fail OSM::APIPreconditionFailedError.new("Cannot create way: data is invalid.")
end
self.version = 0
self.visible = true
end
def preconditions_ok?(old_nodes = [])
- return false if self.nds.empty?
- if self.nds.length > MAX_NUMBER_OF_WAY_NODES
- raise OSM::APITooManyWayNodesError.new(self.id, self.nds.length, MAX_NUMBER_OF_WAY_NODES)
+ return false if nds.empty?
+ if nds.length > MAX_NUMBER_OF_WAY_NODES
+ fail OSM::APITooManyWayNodesError.new(id, nds.length, MAX_NUMBER_OF_WAY_NODES)
end
# check only the new nodes, for efficiency - old nodes having been checked last time and can't
# be deleted when they're in-use.
- new_nds = (self.nds - old_nodes).sort.uniq
+ new_nds = (nds - old_nodes).sort.uniq
unless new_nds.empty?
db_nds = Node.where(:id => new_nds, :visible => true)
if db_nds.length < new_nds.length
- missing = new_nds - db_nds.collect { |n| n.id }
- raise OSM::APIPreconditionFailedError.new("Way #{self.id} requires the nodes with id in (#{missing.join(',')}), which either do not exist, or are not visible.")
+ missing = new_nds - db_nds.collect(&:id)
+ fail OSM::APIPreconditionFailedError.new("Way #{id} requires the nodes with id in (#{missing.join(',')}), which either do not exist, or are not visible.")
end
end
- return true
+ true
end
def delete_with_history!(new_way, user)
- unless self.visible
- raise OSM::APIAlreadyDeletedError.new("way", new_way.id)
+ unless visible
+ fail OSM::APIAlreadyDeletedError.new("way", new_way.id)
end
# need to start the transaction here, so that the database can
self.lock!
check_consistency(self, new_way, user)
rels = Relation.joins(:relation_members).where(:visible => true, :current_relation_members => { :member_type => "Way", :member_id => id }).order(:id)
- raise OSM::APIPreconditionFailedError.new("Way #{self.id} is still used by relations #{rels.collect { |r| r.id }.join(",")}.") unless rels.empty?
+ fail OSM::APIPreconditionFailedError.new("Way #{id} is still used by relations #{rels.collect(&:id).join(",")}.") unless rels.empty?
self.changeset_id = new_way.changeset_id
self.changeset = new_way.changeset
# Temporary method to match interface to nodes
def tags_as_hash
- return self.tags
+ tags
end
##
# this calling this method will fix them using the map from placeholders
# to IDs +id_map+.
def fix_placeholders!(id_map, placeholder_id = nil)
- self.nds.map! do |node_id|
+ nds.map! do |node_id|
if node_id < 0
new_id = id_map[:node][node_id]
- raise OSM::APIBadUserInput.new("Placeholder node not found for reference #{node_id} in way #{self.id.nil? ? placeholder_id : self.id}") if new_id.nil?
+ fail OSM::APIBadUserInput.new("Placeholder node not found for reference #{node_id} in way #{id.nil? ? placeholder_id : id}") if new_id.nil?
new_id
else
node_id
# and after the save, so that nodes from both versions are included in the
# bbox. we use a copy of the changeset so that it isn't reloaded
# later in the save.
- cs = self.changeset
+ cs = changeset
cs.update_bbox!(bbox) unless nodes.empty?
Way.transaction do
self.save!
tags = self.tags
- WayTag.delete_all(:way_id => self.id)
- tags.each do |k,v|
+ WayTag.delete_all(:way_id => id)
+ tags.each do |k, v|
tag = WayTag.new
- tag.way_id = self.id
+ tag.way_id = id
tag.k = k
tag.v = v
tag.save!
end
nds = self.nds
- WayNode.delete_all(:way_id => self.id)
+ WayNode.delete_all(:way_id => id)
sequence = 1
nds.each do |n|
nd = WayNode.new
- nd.id = [self.id, sequence]
+ nd.id = [id, sequence]
nd.node_id = n
nd.save!
sequence += 1
# reload the way so that the nodes array points to the correct
# new set of nodes.
- self.reload
+ reload
# update and commit the bounding box, now that way nodes
# have been updated and we're in a transaction.
require File.expand_path('../preinitializer', __FILE__)
if STATUS == :database_offline
-require "action_controller/railtie"
-require "action_mailer/railtie"
-require "active_model/railtie"
-require "sprockets/railtie"
-require "rails/test_unit/railtie"
+ require "action_controller/railtie"
+ require "action_mailer/railtie"
+ require "active_model/railtie"
+ require "sprockets/railtie"
+ require "rails/test_unit/railtie"
else
-require 'rails/all'
+ require 'rails/all'
end
# Require the gems listed in Gemfile, including any gems
module ActiveRecord
module ConnectionAdapters
class AbstractAdapter
- protected
+ protected
+
alias_method :old_log, :log
def log(sql, name)
-ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
+ActionView::Base.field_error_proc = proc do |html_tag, _instance|
class_attr_index = html_tag.index 'class="'
if class_attr_index
- html_tag.insert class_attr_index+7, 'field_with_errors '
+ html_tag.insert class_attr_index + 7, 'field_with_errors '
else
html_tag.insert html_tag.index(/\/?>/), ' class="field_with_errors"'
end
def pluralize(locale, entry, count)
super
rescue InvalidPluralizationData => ex
- raise ex unless ex.entry.has_key?(:other)
+ raise ex unless ex.entry.key?(:other)
ex.entry[:other]
end
end
def make_ordered(unordered)
ordered = ActiveSupport::OrderedHash.new
- unordered.keys.sort { |a,b| a.to_s <=> b.to_s }.each do |key|
+ unordered.keys.sort { |a, b| a.to_s <=> b.to_s }.each do |key|
value = unordered[key]
if value.is_a?(Hash)
# This is required otherwise libxml writes out memory errors to
# the standard output and exits uncleanly
LibXML::XML::Error.set_handler do |message|
- raise message
+ fail message
end
# Setup any specified hard limit on the virtual size of the process
-if defined?(HARD_MEMORY_LIMIT) and defined?(PhusionPassenger) and Process.const_defined?(:RLIMIT_AS)
- Process.setrlimit Process::RLIMIT_AS, HARD_MEMORY_LIMIT*1024*1024, Process::RLIM_INFINITY
+if defined?(HARD_MEMORY_LIMIT) && defined?(PhusionPassenger) && Process.const_defined?(:RLIMIT_AS)
+ Process.setrlimit Process::RLIMIT_AS, HARD_MEMORY_LIMIT * 1024 * 1024, Process::RLIM_INFINITY
end
# If we're running under passenger and a soft memory limit is
# configured then setup some rack middleware to police the limit
-if defined?(SOFT_MEMORY_LIMIT) and defined?(PhusionPassenger)
+if defined?(SOFT_MEMORY_LIMIT) && defined?(PhusionPassenger)
# Define some rack middleware to police the soft memory limit
class MemoryLimit
def initialize(app)
# Return the result of this request
[status, headers, body]
end
- private
+
+ private
+
def resident_size
# Read statm to get process sizes. Format is
# Size RSS Shared Text Lib Data
end
# Return resident size in megabytes
- return fields[1].to_i / 256
+ fields[1].to_i / 256
end
end
end
end
-Rails.application.config.after_initialize do |app|
+Rails.application.config.after_initialize do |_app|
Paperclip::AssetUrlGenerator::VIEW_ACCESSORS.each do |attr|
Paperclip::AssetUrlGenerator.send("#{attr}=", ActionView::Base.send(attr))
end
require "yaml"
-if File.exists?(piwik_file = File.expand_path("../../piwik.yml", __FILE__))
+if File.exist?(piwik_file = File.expand_path("../../piwik.yml", __FILE__))
PIWIK = YAML.load_file(piwik_file)
end
# Load presets
-POTLATCH_PRESETS = Potlatch::Potlatch.get_presets()
+POTLATCH_PRESETS = Potlatch::Potlatch.get_presets
# Use SQL (faster) or Rails (more elegant) for common Potlatch reads
# getway speedup is approximately x2, whichways approximately x7
@output = R2.r2(data)
end
- def evaluate(scope, locals, &block)
+ def evaluate(_scope, _locals, &_block)
@output
end
end
class Router
class Utils
def self.normalize_path_with_encoding(path)
- self.normalize_path_without_encoding(path).force_encoding("UTF-8")
+ normalize_path_without_encoding(path).force_encoding("UTF-8")
end
class << self
Sanitize::Config::OSM = Sanitize::Config::RELAXED.dup
-Sanitize::Config::OSM[:elements] -= [ 'div', 'style' ]
+Sanitize::Config::OSM[:elements] -= %w(div style)
Sanitize::Config::OSM[:add_attributes] = { 'a' => { 'rel' => 'nofollow' } }
-Sanitize::Config::OSM[:remove_contents] = [ 'script', 'style' ]
+Sanitize::Config::OSM[:remove_contents] = %w(script style)
alias_method :old_send_file, :send_file
def send_file(file, options = {})
- if file.is_a? File or file.is_a? Tempfile
+ if file.is_a?(File) || file.is_a?(Tempfile)
headers["Content-Length"] ||= file.size.to_s
options[:filename] ||= File.basename(file.path) unless options[:url_based_filename]
# does a half assed job of making TempFile act as a File
class Tempfile
def file
- return @tmpfile
+ @tmpfile
end
end
config = YAML.load_file(File.expand_path(env == "test" ? "../example.application.yml" : "../application.yml", __FILE__))
-ENV.each do |key,value|
+ENV.each do |key, value|
if key.match(/^OSM_(.*)$/)
Object.const_set(Regexp.last_match(1).upcase, value)
end
end
-config[env].each do |key,value|
+config[env].each do |key, value|
unless Object.const_defined?(key.upcase)
Object.const_set(key.upcase, value)
end
# Map notes API
scope "api/0.6" do
- resources :notes, :except => [ :new, :edit, :update ], :constraints => { :id => /\d+/ }, :defaults => { :format => "xml" } do
+ resources :notes, :except => [:new, :edit, :update], :constraints => { :id => /\d+/ }, :defaults => { :format => "xml" } do
collection do
get 'search'
get 'feed', :defaults => { :format => "rss" }
end
add_index "current_nodes", ["id"], :name => "current_nodes_id_idx"
- add_index "current_nodes", ["latitude", "longitude"], :name => "current_nodes_lat_lon_idx"
+ add_index "current_nodes", %w(latitude longitude), :name => "current_nodes_lat_lon_idx"
add_index "current_nodes", ["timestamp"], :name => "current_nodes_timestamp_idx"
create_table "current_segments", :id => false do |t|
t.column "timestamp", :datetime
end
- add_index "current_segments", ["id", "visible"], :name => "current_segments_id_visible_idx"
+ add_index "current_segments", %w(id visible), :name => "current_segments_id_visible_idx"
add_index "current_segments", ["node_a"], :name => "current_segments_a_idx"
add_index "current_segments", ["node_b"], :name => "current_segments_b_idx"
t.column "timestamp", :datetime
end
- add_index "gps_points", ["latitude", "longitude", "user_id"], :name => "points_idx"
+ add_index "gps_points", %w(latitude longitude user_id), :name => "points_idx"
add_index "gps_points", ["user_id"], :name => "points_uid_idx"
add_index "gps_points", ["gpx_id"], :name => "points_gpxid_idx"
end
add_index "gpx_files", ["timestamp"], :name => "gpx_files_timestamp_idx"
- add_index "gpx_files", ["visible", "public"], :name => "gpx_files_visible_public_idx"
+ add_index "gpx_files", %w(visible public), :name => "gpx_files_visible_public_idx"
create_table "gpx_pending_files", :id => false do |t|
t.column "originalname", :string
end
add_index "nodes", ["id"], :name => "nodes_uid_idx"
- add_index "nodes", ["latitude", "longitude"], :name => "nodes_latlon_idx"
+ add_index "nodes", %w(latitude longitude), :name => "nodes_latlon_idx"
create_table "segments", :id => false do |t|
t.column "id", :bigint
t.column "sequence_id", :bigint, :null => false
end
- add_primary_key "way_segments", ["id", "version", "sequence_id"]
+ add_primary_key "way_segments", %w(id version sequence_id)
create_table "way_tags", :id => false do |t|
t.column "id", :bigint, :default => 0, :null => false
t.column "version", :bigint
end
- add_index "way_tags", ["id", "version"], :name => "way_tags_id_version_idx"
+ add_index "way_tags", %w(id version), :name => "way_tags_id_version_idx"
create_table "ways", :id => false do |t|
t.column "id", :bigint, :default => 0, :null => false
t.column "visible", :boolean, :default => true
end
- add_primary_key "ways", ["id", "version"]
+ add_primary_key "ways", %w(id version)
add_index "ways", ["id"], :name => "ways_id_version_idx"
end
def self.down
-
end
end
change_column "current_way_segments", "id", :bigint, :null => false
change_column "current_way_segments", "segment_id", :bigint, :null => false
change_column "current_way_segments", "sequence_id", :bigint, :null => false
- add_primary_key "current_way_segments", ["id", "sequence_id"]
+ add_primary_key "current_way_segments", %w(id sequence_id)
remove_index "current_way_segments", :name => "current_way_segments_id_idx"
change_column "current_way_tags", "id", :bigint, :null => false
remove_index "gps_points", :name => "points_uid_idx"
remove_index "gps_points", :name => "points_idx"
remove_column "gps_points", "user_id"
- add_index "gps_points", ["latitude", "longitude"], :name => "points_idx"
+ add_index "gps_points", %w(latitude longitude), :name => "points_idx"
change_column "gps_points", "trackid", :integer, :null => false
change_column "gps_points", "latitude", :integer, :null => false
change_column "gps_points", "longitude", :integer, :null => false
change_column "current_way_segments", "segment_id", :bigint
change_column "current_way_segments", "id", :bigint
- add_index "current_segments", ["id", "visible"], :name => "current_segments_id_visible_idx"
+ add_index "current_segments", %w(id visible), :name => "current_segments_id_visible_idx"
remove_primary_key "current_segments"
change_column "current_segments", "timestamp", :datetime
change_column "current_segments", "visible", :boolean
t.column "v", :string, :null => false
end
- add_primary_key "user_preferences", ["user_id", "k"]
+ add_primary_key "user_preferences", %w(user_id k)
create_table "user_tokens", :id => false do |t|
t.column "id", :bigserial, :primary_key => true, :null => false
add_column "users", "nearby", :integer, :default => 50
add_column "users", "pass_salt", :string
- User.update_all("nearby = 50");
+ User.update_all("nearby = 50")
end
def self.down
def self.down
Tracepoint.update_all("latitude = latitude / 10, longitude = longitude / 10")
- add_index "gps_points", ["latitude", "longitude"], :name => "points_idx"
+ add_index "gps_points", %w(latitude longitude), :name => "points_idx"
remove_index "gps_points", :name => "points_tile_idx"
remove_column "gps_points", "tile"
end
FROM #{from_table}
END_SQL
- model.all.each do |n|
- n.save!
- end
+ model.all.each(&:save!)
end
end
drop_table "current_nodes_v5"
- remove_index "nodes", :name=> "nodes_uid_idx"
- remove_index "nodes", :name=> "nodes_timestamp_idx"
+ remove_index "nodes", :name => "nodes_uid_idx"
+ remove_index "nodes", :name => "nodes_timestamp_idx"
rename_table "nodes", "nodes_v5"
create_table "nodes", :id => false do |t|
t.column "timestamp", :datetime, :null => false
end
- add_index "current_nodes", ["latitude", "longitude"], :name => "current_nodes_lat_lon_idx"
+ add_index "current_nodes", %w(latitude longitude), :name => "current_nodes_lat_lon_idx"
add_index "current_nodes", ["timestamp"], :name => "current_nodes_timestamp_idx"
downgrade_table "current_nodes_v6", "current_nodes"
end
add_index "nodes", ["id"], :name => "nodes_uid_idx"
- add_index "nodes", ["latitude", "longitude"], :name => "nodes_latlon_idx"
+ add_index "nodes", %w(latitude longitude), :name => "nodes_latlon_idx"
add_index "nodes", ["timestamp"], :name => "nodes_timestamp_idx"
downgrade_table "nodes_v6", "nodes"
class AddRelations < ActiveRecord::Migration
def self.up
# enums work like strings but are more efficient
- create_enumeration :nwr_enum, ["Node", "Way", "Relation"]
+ create_enumeration :nwr_enum, %w(Node Way Relation)
# a relation can have members much like a way can have nodes.
# differences:
t.column "member_role", :string
end
- add_primary_key "current_relation_members", ["id", "member_type", "member_id", "member_role"]
- add_index "current_relation_members", ["member_type", "member_id"], :name => "current_relation_members_member_idx"
+ add_primary_key "current_relation_members", %w(id member_type member_id member_role)
+ add_index "current_relation_members", %w(member_type member_id), :name => "current_relation_members_member_idx"
# the following is obsolete given the primary key, is it not?
# add_index "current_relation_members", ["id"], :name => "current_relation_members_id_idx"
create_table "current_relation_tags", :id => false do |t|
t.column "version", :bigint, :default => 0, :null => false
end
- add_primary_key "relation_members", ["id", "version", "member_type", "member_id", "member_role"]
- add_index "relation_members", ["member_type", "member_id"], :name => "relation_members_member_idx"
+ add_primary_key "relation_members", %w(id version member_type member_id member_role)
+ add_index "relation_members", %w(member_type member_id), :name => "relation_members_member_idx"
create_table "relation_tags", :id => false do |t|
t.column "id", :bigint, :default => 0, :null => false
t.column "version", :bigint, :null => false
end
- add_index "relation_tags", ["id", "version"], :name => "relation_tags_id_version_idx"
+ add_index "relation_tags", %w(id version), :name => "relation_tags_id_version_idx"
create_table "relations", :id => false do |t|
t.column "id", :bigint, :null => false, :default => 0
t.column "visible", :boolean, :null => false, :default => true
end
- add_primary_key "relations", ["id", "version"]
+ add_primary_key "relations", %w(id version)
add_index "relations", ["timestamp"], :name => "relations_timestamp_idx"
end
have_segs = select_value("SELECT count(*) FROM current_segments").to_i != 0
if have_segs
- prefix = File.join Dir.tmpdir, "008_remove_segments.#{$$}."
+ prefix = File.join Dir.tmpdir, "008_remove_segments.#{$PROCESS_ID}."
cmd = "db/migrate/008_remove_segments_helper"
src = "#{cmd}.cc"
- if not File.exists? cmd or File.mtime(cmd) < File.mtime(src) then
- system 'c++ -O3 -Wall `mysql_config --cflags --libs` ' +
- "#{src} -o #{cmd}" or fail
+ if !File.exist?(cmd) || File.mtime(cmd) < File.mtime(src)
+ system('c++ -O3 -Wall `mysql_config --cflags --libs` ' +
+ "#{src} -o #{cmd}") || fail
end
- conn_opts = ActiveRecord::Base.connection.
- instance_eval { @connection_options }
- args = conn_opts.map { |arg| arg.to_s } + [prefix]
+ conn_opts = ActiveRecord::Base.connection
+ .instance_eval { @connection_options }
+ args = conn_opts.map(&:to_s) + [prefix]
fail "#{cmd} failed" unless system cmd, *args
- tempfiles = ['ways', 'way_nodes', 'way_tags',
- 'relations', 'relation_members', 'relation_tags'].
- map { |base| prefix + base }
+ tempfiles = %w(ways way_nodes way_tags relations relation_members relation_tags)
+ .map { |base| prefix + base }
ways, way_nodes, way_tags,
- relations, relation_members, relation_tags = tempfiles
+ relations, relation_members, relation_tags = tempfiles
end
drop_table :segments
end
def self.down
- raise ActiveRecord::IrreversibleMigration
+ fail ActiveRecord::IrreversibleMigration
end
end
t.column "updated_at", :datetime, :null => false
end
- add_index "diary_comments", ["diary_entry_id", "id"], :name => "diary_comments_entry_id_idx", :unique => true
-
+ add_index "diary_comments", %w(diary_entry_id id), :name => "diary_comments_entry_id_idx", :unique => true
end
def self.down
class AddEmailValid < ActiveRecord::Migration
def self.up
add_column "users", "email_valid", :boolean, :default => false, :null => false
- User.update_all("email_valid = (active != 0)") #email_valid is :boolean, but active is :integer. "email_valid = active" (see r11802 or earlier) will fail for stricter dbs than mysql
+ User.update_all("email_valid = (active != 0)") # email_valid is :boolean, but active is :integer. "email_valid = active" (see r11802 or earlier) will fail for stricter dbs than mysql
end
def self.down
have_nodes = select_value("SELECT count(*) FROM current_nodes").to_i != 0
if have_nodes
- prefix = File.join Dir.tmpdir, "020_populate_node_tags_and_remove.#{$$}."
+ prefix = File.join Dir.tmpdir, "020_populate_node_tags_and_remove.#{$PROCESS_ID}."
cmd = "db/migrate/020_populate_node_tags_and_remove_helper"
src = "#{cmd}.c"
- if not File.exists? cmd or File.mtime(cmd) < File.mtime(src) then
- system 'cc -O3 -Wall `mysql_config --cflags --libs` ' +
- "#{src} -o #{cmd}" or fail
+ if !File.exist?(cmd) || File.mtime(cmd) < File.mtime(src)
+ system('cc -O3 -Wall `mysql_config --cflags --libs` ' +
+ "#{src} -o #{cmd}") || fail
end
conn_opts = ActiveRecord::Base.connection.instance_eval { @connection_options }
- args = conn_opts.map { |arg| arg.to_s } + [prefix]
+ args = conn_opts.map(&:to_s) + [prefix]
fail "#{cmd} failed" unless system cmd, *args
- tempfiles = ['nodes', 'node_tags', 'current_nodes', 'current_node_tags'].
- map { |base| prefix + base }
+ tempfiles = %w(nodes node_tags current_nodes current_node_tags)
+ .map { |base| prefix + base }
nodes, node_tags, current_nodes, current_node_tags = tempfiles
end
csvopts = "FIELDS TERMINATED BY ',' ENCLOSED BY '\"' ESCAPED BY '\"' LINES TERMINATED BY '\\n'"
if have_nodes
- execute "LOAD DATA INFILE '#{nodes}' INTO TABLE nodes #{csvopts} (id, latitude, longitude, user_id, visible, timestamp, tile, version)";
+ execute "LOAD DATA INFILE '#{nodes}' INTO TABLE nodes #{csvopts} (id, latitude, longitude, user_id, visible, timestamp, tile, version)"
execute "LOAD DATA INFILE '#{node_tags}' INTO TABLE node_tags #{csvopts} (id, version, k, v)"
execute "LOAD DATA INFILE '#{current_node_tags}' INTO TABLE current_node_tags #{csvopts} (id, k, v)"
end
end
def self.down
- raise ActiveRecord::IrreversibleMigration
-# add_column :nodes, "tags", :text, :default => "", :null => false
-# add_column :current_nodes, "tags", :text, :default => "", :null => false
+ fail ActiveRecord::IrreversibleMigration
+ # add_column :nodes, "tags", :text, :default => "", :null => false
+ # add_column :current_nodes, "tags", :text, :default => "", :null => false
end
end
require 'migrate'
class MoveToInnodb < ActiveRecord::Migration
- @@conv_tables = ['nodes', 'ways', 'way_tags', 'way_nodes',
- 'current_way_tags', 'relation_members',
- 'relations', 'relation_tags', 'current_relation_tags']
+ @@conv_tables = %w(nodes ways way_tags way_nodes current_way_tags relation_members relations relation_tags current_relation_tags)
- @@ver_tbl = ['nodes', 'ways', 'relations']
+ @@ver_tbl = %w(nodes ways relations)
def self.up
- remove_index :current_way_tags, :name=> :current_way_tags_v_idx
- remove_index :current_relation_tags, :name=> :current_relation_tags_v_idx
+ remove_index :current_way_tags, :name => :current_way_tags_v_idx
+ remove_index :current_relation_tags, :name => :current_relation_tags_v_idx
- @@ver_tbl.each { |tbl|
+ @@ver_tbl.each do |tbl|
change_column tbl, "version", :bigint, :null => false
- }
+ end
- @@ver_tbl.each { |tbl|
+ @@ver_tbl.each do |tbl|
add_column "current_#{tbl}", "version", :bigint, :null => false
# As the initial version of all nodes, ways and relations is 0, we set the
# current version to something less so that we can update the version in
# batches of 10000
tbl.classify.constantize.update_all("version=-1")
- while tbl.classify.constantize.count(:conditions => {:version => -1}) > 0
- tbl.classify.constantize.update_all("version=(SELECT max(version) FROM #{tbl} WHERE #{tbl}.id = current_#{tbl}.id)", {:version => -1}, :limit => 10000)
+ while tbl.classify.constantize.count(:conditions => { :version => -1 }) > 0
+ tbl.classify.constantize.update_all("version=(SELECT max(version) FROM #{tbl} WHERE #{tbl}.id = current_#{tbl}.id)", { :version => -1 }, { :limit => 10000 })
end
- # execute "UPDATE current_#{tbl} SET version = " +
+ # execute "UPDATE current_#{tbl} SET version = " +
# "(SELECT max(version) FROM #{tbl} WHERE #{tbl}.id = current_#{tbl}.id)"
- # The above update causes a MySQL error:
- # -- add_column("current_nodes", "version", :bigint, {:null=>false, :limit=>20})
- # -> 1410.9152s
- # -- execute("UPDATE current_nodes SET version = (SELECT max(version) FROM nodes WHERE nodes.id = current_nodes.id)")
- # rake aborted!
- # Mysql::Error: The total number of locks exceeds the lock table size: UPDATE current_nodes SET version = (SELECT max(version) FROM nodes WHERE nodes.id = current_nodes.id)
+ # The above update causes a MySQL error:
+ # -- add_column("current_nodes", "version", :bigint, {:null=>false, :limit=>20})
+ # -> 1410.9152s
+ # -- execute("UPDATE current_nodes SET version = (SELECT max(version) FROM nodes WHERE nodes.id = current_nodes.id)")
+ # rake aborted!
+ # Mysql::Error: The total number of locks exceeds the lock table size: UPDATE current_nodes SET version = (SELECT max(version) FROM nodes WHERE nodes.id = current_nodes.id)
- # The above rails version will take longer, however will no run out of locks
- }
+ # The above rails version will take longer, however will no run out of locks
+ end
end
def self.down
- raise ActiveRecord::IrreversibleMigration
+ fail ActiveRecord::IrreversibleMigration
end
end
end
def self.down
- raise ActiveRecord::IrreversibleMigration
+ fail ActiveRecord::IrreversibleMigration
end
end
require 'migrate'
class AddChangesets < ActiveRecord::Migration
- @@conv_user_tables = ['current_nodes',
- 'current_relations', 'current_ways', 'nodes', 'relations', 'ways' ]
+ @@conv_user_tables = %w(current_nodes current_relations current_ways nodes relations ways)
def self.up
create_table "changesets", :id => false do |t|
execute "INSERT INTO changesets (id, user_id, created_at, open)" +
"SELECT id, id, creation_time, false from users;"
- @@conv_user_tables.each { |tbl|
+ @@conv_user_tables.each do |tbl|
rename_column tbl, :user_id, :changeset_id
- #foreign keys too
+ # foreign keys too
add_foreign_key tbl, :changesets, :name => "#{tbl}_changeset_id_fkey"
- }
+ end
end
def self.down
# It's not easy to generate the user ids from the changesets
- raise ActiveRecord::IrreversibleMigration
- #drop_table "changesets"
- #drop_table "changeset_tags"
+ fail ActiveRecord::IrreversibleMigration
+ # drop_table "changesets"
+ # drop_table "changeset_tags"
end
end
def self.up
add_index "changesets", ["created_at"], :name => "changesets_created_at_idx"
add_index "changesets", ["closed_at"], :name => "changesets_closed_at_idx"
- add_index "changesets", ["min_lat","max_lat","min_lon","max_lon"], :name => "changesets_bbox_idx", :using => "GIST"
+ add_index "changesets", %w(min_lat max_lat min_lon max_lon), :name => "changesets_bbox_idx", :using => "GIST"
end
def self.down
end
def self.down
- raise ActiveRecord::IrreversibleMigration
+ fail ActiveRecord::IrreversibleMigration
end
end
Language.load("#{Rails.root}/config/languages.yml")
add_foreign_key :users, :languages, :column => :locale, :primary_key => :code, :name => "users_locale_fkey"
- add_foreign_key :diary_entries, :languages, :column => :language_code , :primary_key => :code, :name => "diary_entries_language_code_fkey"
+ add_foreign_key :diary_entries, :languages, :column => :language_code, :primary_key => :code, :name => "diary_entries_language_code_fkey"
end
end
class AddMessageSenderIndex < ActiveRecord::Migration
def self.up
- add_index :messages, [:from_user_id], :name=> "messages_from_user_id_idx"
+ add_index :messages, [:from_user_id], :name => "messages_from_user_id_idx"
end
def self.down
- remove_index :messages, :name=> "messages_from_user_id_idx"
+ remove_index :messages, :name => "messages_from_user_id_idx"
end
end
class AddMoreControlsToGpxFiles < ActiveRecord::Migration
def self.up
- create_enumeration :gpx_visibility_enum, ["private", "public", "trackable", "identifiable"]
+ create_enumeration :gpx_visibility_enum, %w(private public trackable identifiable)
add_column :gpx_files, :visibility, :gpx_visibility_enum, :default => "public", :null => false
Trace.where(:public => false).update_all(:visibility => "private")
add_index :gpx_files, [:visible, :visibility], :name => "gpx_files_visible_visibility_idx"
t.timestamps
end
add_index :oauth_nonces, [:nonce, :timestamp], :unique => true
-
end
def self.down
drop_table :oauth_tokens
drop_table :oauth_nonces
end
-
end
class AddFineOAuthPermissions < ActiveRecord::Migration
PERMISSIONS = [:allow_read_prefs, :allow_write_prefs, :allow_write_diary,
- :allow_write_api, :allow_read_gpx, :allow_write_gpx ]
+ :allow_write_api, :allow_read_gpx, :allow_write_gpx]
def self.up
PERMISSIONS.each do |perm|
class CreateUserRoles < ActiveRecord::Migration
def self.up
- create_enumeration :user_role_enum, ["administrator", "moderator"]
+ create_enumeration :user_role_enum, %w(administrator moderator)
create_table :user_roles do |t|
t.column :user_id, :bigint, :null => false
class AddStatusToUser < ActiveRecord::Migration
def self.up
- create_enumeration :user_status_enum, ["pending","active","confirmed","suspended","deleted"]
+ create_enumeration :user_status_enum, %w(pending active confirmed suspended deleted)
add_column :users, :status, :user_status_enum, :null => false, :default => "pending"
class AddMapBugTables < ActiveRecord::Migration
def self.up
- create_enumeration :map_bug_status_enum, ["open", "closed", "hidden"]
+ create_enumeration :map_bug_status_enum, %w(open closed hidden)
create_table :map_bugs do |t|
t.integer :latitude, :null => false
class AddMapBugCommentEvent < ActiveRecord::Migration
def self.up
- create_enumeration :map_bug_event_enum, ["opened", "closed", "reopened", "commented", "hidden"]
+ create_enumeration :map_bug_event_enum, %w(opened closed reopened commented hidden)
add_column :map_bug_comment, :event, :map_bug_event_enum
end
while netmask != "0.0.0.0"
netmask = netmask << 1
- prefix = prefix + 1
+ prefix += 1
end
acl.address = "#{address.mask(prefix)}/#{prefix}"
class AddTextFormat < ActiveRecord::Migration
def up
- create_enumeration :format_enum, ["html", "markdown", "text"]
+ create_enumeration :format_enum, %w(html markdown text)
add_column :users, :description_format, :format_enum, :null => false, :default => "html"
add_column :user_blocks, :reason_format, :format_enum, :null => false, :default => "html"
add_column :diary_entries, :body_format, :format_enum, :null => false, :default => "html"
class BoundingBox
attr_reader :min_lon, :min_lat, :max_lon, :max_lat
-private
+ private
+
LON_LIMIT = 180.0
LAT_LIMIT = 90.0
SCALED_LON_LIMIT = LON_LIMIT * GeoRecord::SCALE
SCALED_LAT_LIMIT = LAT_LIMIT * GeoRecord::SCALE
-public
+ public
+
def initialize(min_lon, min_lat, max_lon, max_lat)
@min_lon = min_lon.to_f unless min_lon.nil?
@min_lat = min_lat.to_f unless min_lat.nil?
end
def self.from_bbox_params(params)
- if params[:bbox] and params[:bbox].count(',') == 3
+ if params[:bbox] && params[:bbox].count(',') == 3
bbox_array = params[:bbox].split(',')
end
from_bbox_array(bbox_array)
end
def self.from_lon_lat_params(params)
- if params[:minlon] and params[:minlat] and params[:maxlon] and params[:maxlat]
+ if params[:minlon] && params[:minlat] && params[:maxlon] && params[:maxlat]
bbox_array = [params[:minlon], params[:minlat], params[:maxlon], params[:maxlat]]
end
from_bbox_array(bbox_array)
end
def self.from_lrbt_params(params)
- if params[:l] and params[:b] and params[:t] and params[:t]
+ if params[:l] && params[:b] && params[:t] && params[:t]
bbox_array = [params[:l], params[:b], params[:r], params[:t]]
end
from_bbox_array(bbox_array)
def check_boundaries
# check the bbox is sane
if min_lon > max_lon
- raise OSM::APIBadBoundingBox.new(
+ fail OSM::APIBadBoundingBox.new(
"The minimum longitude must be less than the maximum longitude, but it wasn't")
end
if min_lat > max_lat
- raise OSM::APIBadBoundingBox.new(
+ fail OSM::APIBadBoundingBox.new(
"The minimum latitude must be less than the maximum latitude, but it wasn't")
end
if min_lon < -LON_LIMIT || min_lat < -LAT_LIMIT || max_lon > +LON_LIMIT || max_lat > +LAT_LIMIT
- raise OSM::APIBadBoundingBox.new("The latitudes must be between #{-LAT_LIMIT} and #{LAT_LIMIT}," +
+ fail OSM::APIBadBoundingBox.new("The latitudes must be between #{-LAT_LIMIT} and #{LAT_LIMIT}," +
" and longitudes between #{-LON_LIMIT} and #{LON_LIMIT}")
end
self
def check_size(max_area = MAX_REQUEST_AREA)
# check the bbox isn't too large
if area > max_area
- raise OSM::APIBadBoundingBox.new("The maximum bbox size is " + max_area.to_s +
+ fail OSM::APIBadBoundingBox.new("The maximum bbox size is " + max_area.to_s +
", and your request was too large. Either request a smaller area, or use planet.osm")
end
self
end
def complete?
- not to_a.include?(nil)
+ !to_a.include?(nil)
end
def centre_lon
end
def slippy_width(zoom)
- width * 256.0 * 2.0 ** zoom / 360.0
+ width * 256.0 * 2.0**zoom / 360.0
end
def slippy_height(zoom)
Math.log((Math.tan(max) + 1.0 / Math.cos(max)) /
(Math.tan(min) + 1.0 / Math.cos(min))) *
- (128.0 * 2.0 ** zoom / Math::PI)
+ (128.0 * 2.0**zoom / Math::PI)
end
# there are two forms used for bounds with and without an underscore,
end
private
+
def self.from_bbox_array(bbox_array)
unless bbox_array
- raise OSM::APIBadUserInput.new(
+ fail OSM::APIBadUserInput.new(
"The parameter bbox is required, and must be of the form min_lon,min_lat,max_lon,max_lat")
end
# Take an array of length 4, create a bounding box with min_lon, min_lat, max_lon and
module Pagination
unless const_defined?(:OPTIONS)
# A hash holding options for controllers using macro-style pagination
- OPTIONS = Hash.new
+ OPTIONS = {}
# The default options for pagination
DEFAULT_OPTIONS = {
end
def self.validate_options!(collection_id, options, in_action) #:nodoc:
- options.merge!(DEFAULT_OPTIONS) {|key, old, new| old}
+ options.merge!(DEFAULT_OPTIONS) { |_key, old, _new| old }
valid_options = DEFAULT_OPTIONS.keys
valid_options << :actions unless in_action
unknown_option_keys = options.keys - valid_options
- raise ActionController::ActionControllerError,
- "Unknown options: #{unknown_option_keys.join(', ')}" unless
+ fail ActionController::ActionControllerError,
+ "Unknown options: #{unknown_option_keys.join(', ')}" unless
unknown_option_keys.empty?
options[:singular_name] ||= ActiveSupport::Inflector.singularize(collection_id.to_s)
#
# <tt>:group</tt>:: :group parameter passed to Model.find(:all, *params). It forces the use of DISTINCT instead of plain COUNT to come up with the total number of records
#
- def paginate(collection_id, options={})
+ def paginate(collection_id, options = {})
Pagination.validate_options!(collection_id, options, true)
paginator_and_collection_for(collection_id, options)
end
# of:
# <tt>:actions</tt>:: an array of actions for which the pagination is
# active. Defaults to +nil+ (i.e., every action)
- def paginate(collection_id, options={})
+ def paginate(collection_id, options = {})
Pagination.validate_options!(collection_id, options, false)
module_eval do
before_filter :create_paginators_and_retrieve_collections
- OPTIONS[self] ||= Hash.new
+ OPTIONS[self] ||= {}
OPTIONS[self][collection_id] = options
end
end
paginator_and_collection_for(collection_id, options)
paginator_name = "@#{options[:singular_name]}_pages"
- self.instance_variable_set(paginator_name, paginator)
+ instance_variable_set(paginator_name, paginator)
- collection_name = "@#{collection_id.to_s}"
- self.instance_variable_set(collection_name, collection)
+ collection_name = "@#{collection_id}"
+ instance_variable_set(collection_name, collection)
end
end
:count_collection_for_pagination,
:find_collection_for_pagination
- def paginator_and_collection_for(collection_id, options) #:nodoc:
+ def paginator_and_collection_for(_collection_id, options) #:nodoc:
klass = options[:class_name].constantize
page = params[options[:parameter]]
count = count_collection_for_pagination(klass, options)
paginator = Paginator.new(self, count, options[:per_page], page)
collection = find_collection_for_pagination(klass, options, paginator)
- return paginator, collection
+ [paginator, collection]
end
private :paginator_and_collection_for
# Raises ArgumentError if items_per_page is out of bounds (i.e., less
# than or equal to zero). The page CGI parameter for links defaults to
# "page" and can be overridden with +page_parameter+.
- def initialize(controller, item_count, items_per_page, current_page=1)
- raise ArgumentError, 'must have at least one item per page' if
+ def initialize(controller, item_count, items_per_page, current_page = 1)
+ fail ArgumentError, 'must have at least one item per page' if
items_per_page <= 0
@controller = controller
# not belong to this Paginator, an ArgumentError is raised.
def current_page=(page)
if page.is_a? Page
- raise ArgumentError, 'Page/Paginator mismatch' unless
+ fail ArgumentError, 'Page/Paginator mismatch' unless
page.paginator == self
end
page = page.to_i
def current_page
@current_page ||= self[@current_page_number]
end
- alias current :current_page
+ alias_method :current, :current_page
# Returns a new Page representing the first page in this paginator.
def first_page
@first_page ||= self[1]
end
- alias first :first_page
+ alias_method :first, :first_page
# Returns a new Page representing the last page in this paginator.
def last_page
@last_page ||= self[page_count]
end
- alias last :last_page
+ alias_method :last, :last_page
# Returns the number of pages in this paginator.
def page_count
@page_count ||= @item_count.zero? ? 1 :
- (q,r=@item_count.divmod(@items_per_page); r==0? q : q+1)
+ (q, r = @item_count.divmod(@items_per_page); r == 0 ? q : q + 1)
end
- alias length :page_count
+ alias_method :length, :page_count
# Returns true if this paginator contains the page of index +number+.
def has_page_number?(number)
- number >= 1 and number <= page_count
+ number >= 1 && number <= page_count
end
# Returns a new Page representing the page with the given index
end
# Successively yields all the paginator's pages to the given block.
- def each(&block)
+ def each(&_block)
page_count.times do |n|
- yield self[n+1]
+ yield self[n + 1]
end
end
@number = 1 unless @paginator.has_page_number? @number
end
attr_reader :paginator, :number
- alias to_i :number
+ alias_method :to_i, :number
# Compares two Page objects and returns true when they represent the
# same page (i.e., their paginators are the same and they have the
# same page number).
def ==(page)
return false if page.nil?
- @paginator == page.paginator and
+ @paginator == page.paginator &&
@number == page.number
end
# left-hand page comes after the right-hand page. Raises ArgumentError
# if the pages do not belong to the same Paginator object.
def <=>(page)
- raise ArgumentError unless @paginator == page.paginator
+ fail ArgumentError unless @paginator == page.paginator
@number <=> page.number
end
# Returns a new Window object for this page with the specified
# +padding+.
- def window(padding=2)
+ def window(padding = 2)
Window.new(self, padding)
end
class Window
# Creates a new Window object for the given +page+ with the specified
# +padding+.
- def initialize(page, padding=2)
+ def initialize(page, padding = 2)
@paginator = page.paginator
@page = page
self.padding = padding
# Returns an array of Page objects in the current window.
def pages
- (@first.number..@last.number).to_a.collect! {|n| @paginator[n]}
+ (@first.number..@last.number).to_a.collect! { |n| @paginator[n] }
end
- alias to_a :pages
+ alias_method :to_a, :pages
end
end
-
end
end
# pagination_links(@person_pages, :params => { :viewer => "flash" })
# # => 1 <a href="/?page=2&viewer=flash/">2</a> <a href="/?page=3&viewer=flash/">3</a> ...
# # <a href="/?page=10&viewer=flash/">10</a>
- def pagination_links(paginator, options={}, html_options={})
+ def pagination_links(paginator, options = {}, html_options = {})
name = options[:name] || DEFAULT_OPTIONS[:name]
params = (options[:params] || DEFAULT_OPTIONS[:params]).clone
html << prefix if prefix
- if always_show_anchors and not (wp_first = window_pages[0]).first?
+ if always_show_anchors && !(wp_first = window_pages[0]).first?
html << yield(first.number)
html << ' ... ' if wp_first.number - first.number > 1
html << ' '
html << ' '
end
- if always_show_anchors and not (wp_last = window_pages[-1]).last?
+ if always_show_anchors && !(wp_last = window_pages[-1]).last?
html << ' ... ' if last.number - wp_last.number > 1
html << yield(last.number)
end
html
end
-
end # PaginationHelper
end # Helpers
end # ActionView
# needed for creates, but are currently not run :-(
# This will throw an exception if there is an inconsistency
def check_consistency(old, new, user)
- if new.id != old.id or new.id.nil? or old.id.nil?
- raise OSM::APIPreconditionFailedError.new("New and old IDs don't match on #{new.class.to_s}. #{new.id} != #{old.id}.")
+ if new.id != old.id || new.id.nil? || old.id.nil?
+ fail OSM::APIPreconditionFailedError.new("New and old IDs don't match on #{new.class}. #{new.id} != #{old.id}.")
elsif new.version != old.version
- raise OSM::APIVersionMismatchError.new(new.id, new.class.to_s, new.version, old.version)
+ fail OSM::APIVersionMismatchError.new(new.id, new.class.to_s, new.version, old.version)
elsif new.changeset.nil?
- raise OSM::APIChangesetMissingError.new
+ fail OSM::APIChangesetMissingError.new
elsif new.changeset.user_id != user.id
- raise OSM::APIUserChangesetMismatchError.new
- elsif not new.changeset.is_open?
- raise OSM::APIChangesetAlreadyClosedError.new(new.changeset)
+ fail OSM::APIUserChangesetMismatchError.new
+ elsif !new.changeset.is_open?
+ fail OSM::APIChangesetAlreadyClosedError.new(new.changeset)
end
end
# This is similar to above, just some validations don't apply
def check_create_consistency(new, user)
if new.changeset.nil?
- raise OSM::APIChangesetMissingError.new
+ fail OSM::APIChangesetMissingError.new
elsif new.changeset.user_id != user.id
- raise OSM::APIUserChangesetMismatchError.new
- elsif not new.changeset.is_open?
- raise OSM::APIChangesetAlreadyClosedError.new(new.changeset)
+ fail OSM::APIUserChangesetMismatchError.new
+ elsif !new.changeset.is_open?
+ fail OSM::APIChangesetAlreadyClosedError.new(new.changeset)
end
end
# check user credentials - only the user who opened a changeset
# may alter it.
if changeset.nil?
- raise OSM::APIChangesetMissingError.new
+ fail OSM::APIChangesetMissingError.new
elsif user.id != changeset.user_id
- raise OSM::APIUserChangesetMismatchError.new
- elsif not changeset.is_open?
- raise OSM::APIChangesetAlreadyClosedError.new(changeset)
+ fail OSM::APIUserChangesetMismatchError.new
+ elsif !changeset.is_open?
+ fail OSM::APIChangesetAlreadyClosedError.new(changeset)
end
end
end
countries[code]
end
-private
+ private
def self.countries
@@countries ||= load_countries
end
def self.load_countries
- countries = Hash.new
+ countries = {}
xml = REXML::Document.new(File.read("config/countries.xml"))
xml.elements.each("geonames/country") do |ele|
#!/usr/bin/env ruby
-#You might want to change this
-#ENV["RAILS_ENV"] ||= "development"
+# You might want to change this
+# ENV["RAILS_ENV"] ||= "development"
require File.dirname(__FILE__) + "/../../config/environment"
logger = ActiveRecord::Base.logger
-while(true) do
+loop do
ActiveRecord::Base.logger.info("GPX Import daemon wake @ #{Time.now}.")
Trace.find(:all, :conditions => { :inserted => false, :visible => true }, :order => "id").each do |trace|
end
rescue Exception => ex
logger.info ex.to_s
- ex.backtrace.each {|l| logger.info l }
+ ex.backtrace.each { |l| logger.info l }
Notifier.gpx_failure(trace, ex.to_s + "\n" + ex.backtrace.join("\n")).deliver
trace.destroy
end
trace.destroy
rescue Exception => ex
logger.info ex.to_s
- ex.backtrace.each {|l| logger.info l }
+ ex.backtrace.each { |l| logger.info l }
end
Signal.trap("TERM", "DEFAULT")
class Hash
def with_symbols!
- self.keys.each{|key| self[key.to_s.to_sym] = self[key] }; self
+ keys.each { |key| self[key.to_s.to_sym] = self[key] }; self
end
end
options = YAML.load(
ERB.new(
- IO.read(
- File.dirname(__FILE__) + "/../../config/daemons.yml"
- )).result).with_symbols!
+ IO.read(
+ File.dirname(__FILE__) + "/../../config/daemons.yml"
+ )).result).with_symbols!
options[:dir_mode] = options[:dir_mode].to_sym
Daemons.run File.dirname(__FILE__) + '/gpx_import.rb', options
def read_or_die
# NOTE: XML::Reader#read returns false for EOF and raises an
# exception if an error occurs.
- begin
- @reader.read
- rescue LibXML::XML::Error => ex
- raise OSM::APIBadXMLError.new("changeset", xml, ex.message)
- end
+ @reader.read
+ rescue LibXML::XML::Error => ex
+ raise OSM::APIBadXMLError.new("changeset", xml, ex.message)
end
##
# read the first element
read_or_die
- while @reader.node_type != 15 do # end element
+ while @reader.node_type != 15 # end element
# because we read elements in DOM-style to reuse their DOM
# parsing code, we don't always read an element on each pass
# as the call to @reader.next in the innermost loop will take
# elements, it would be better to DRY and do this in a block. This
# could also help with error handling...?
def with_model
- with_element do |model_name,model_attributes|
+ with_element do |model_name, _model_attributes|
model = MODELS[model_name]
- raise OSM::APIBadUserInput.new("Unexpected element type #{model_name}, " +
+ fail OSM::APIBadUserInput.new("Unexpected element type #{model_name}, " +
"expected node, way or relation.") if model.nil?
# new in libxml-ruby >= 2, expand returns an element not associated
# with a document. this means that there's no encoding parameter,
# Checks a few invariants. Others are checked in the model methods
# such as save_ and delete_with_history.
def check(model, xml, new)
- raise OSM::APIBadXMLError.new(model, xml) if new.nil?
+ fail OSM::APIBadXMLError.new(model, xml) if new.nil?
unless new.changeset_id == @changeset.id
- raise OSM::APIChangesetMismatchError.new(new.changeset_id, @changeset.id)
+ fail OSM::APIChangesetMismatchError.new(new.changeset_id, @changeset.id)
end
end
# On a failure to meet preconditions (e.g: optimistic locking fails)
# an exception subclassing OSM::APIError will be thrown.
def commit
-
# data structure used for mapping placeholder IDs to real IDs
node_ids, way_ids, rel_ids = {}, {}, {}
- ids = { :node => node_ids, :way => way_ids, :relation => rel_ids}
+ ids = { :node => node_ids, :way => way_ids, :relation => rel_ids }
# take the first element and check that it is an osmChange element
@reader.read
- raise OSM::APIBadUserInput.new("Document element should be 'osmChange'.") if @reader.name != 'osmChange'
+ fail OSM::APIBadUserInput.new("Document element should be 'osmChange'.") if @reader.name != 'osmChange'
result = OSM::API.new.get_xml_doc
result.root.name = "diffResult"
# loop at the top level, within the <osmChange> element
- with_element do |action_name,action_attributes|
+ with_element do |action_name, action_attributes|
if action_name == 'create'
# create a new element. this code is agnostic of the element type
# because all the elements support the methods that we're using.
# when this element is saved it will get a new ID, so we save it
# to produce the mapping which is sent to other elements.
placeholder_id = xml['id'].to_i
- raise OSM::APIBadXMLError.new(model, xml) if placeholder_id.nil?
+ fail OSM::APIBadXMLError.new(model, xml) if placeholder_id.nil?
# check if the placeholder ID has been given before and throw
# an exception if it has - we can't create the same element twice.
model_sym = model.to_s.downcase.to_sym
- raise OSM::APIBadUserInput.new("Placeholder IDs must be unique for created elements.") if ids[model_sym].include? placeholder_id
+ fail OSM::APIBadUserInput.new("Placeholder IDs must be unique for created elements.") if ids[model_sym].include? placeholder_id
# some elements may have placeholders for other elements in the
# diff, so we must fix these before saving the element.
# delete doesn't have to contain a full payload, according to
# the wiki docs, so we just extract the things we need.
new_id = xml['id'].to_i
- raise OSM::APIBadXMLError.new(model, xml, "ID attribute is required") if new_id.nil?
+ fail OSM::APIBadXMLError.new(model, xml, "ID attribute is required") if new_id.nil?
# if the ID is a placeholder then map it to the real ID
model_sym = model.to_s.downcase.to_sym
else
# no other actions to choose from, so it must be the users fault!
- raise OSM::APIChangesetActionInvalid.new(action_name)
+ fail OSM::APIChangesetActionInvalid.new(action_name)
end
end
# return the XML document to be rendered back to the client
- return result
+ result
end
-
end
module Editors
- ALL_EDITORS = [ "potlatch", "potlatch2", "id", "remote" ]
- RECOMMENDED_EDITORS = [ "id", "potlatch2", "remote" ]
+ ALL_EDITORS = %w(potlatch potlatch2 id remote)
+ RECOMMENDED_EDITORS = %w(id potlatch2 remote)
end
# Is this node within -90 >= latitude >= 90 and -180 >= longitude >= 180
# * returns true/false
def in_world?
- return false if self.lat < -90 or self.lat > 90
- return false if self.lon < -180 or self.lon > 180
- return true
+ return false if lat < -90 || lat > 90
+ return false if lon < -180 || lon > 180
+ true
end
def update_tile
# Return WGS84 latitude
def lat
- return self.latitude.to_f / SCALE
+ latitude.to_f / SCALE
end
# Return WGS84 longitude
def lon
- return self.longitude.to_f / SCALE
+ longitude.to_f / SCALE
end
-private
+ private
def lat2y(a)
- 180/Math::PI * Math.log(Math.tan(Math::PI/4+a*(Math::PI/180)/2))
+ 180 / Math::PI * Math.log(Math.tan(Math::PI / 4 + a * (Math::PI / 180) / 2))
end
end
if reader.name == "trkpt"
point = TrkPt.new(@tracksegs, reader["lat"].to_f, reader["lon"].to_f)
@possible_points += 1
- elsif reader.name == "ele" and point
+ elsif reader.name == "ele" && point
point.altitude = reader.read_string.to_f
- elsif reader.name == "time" and point
+ elsif reader.name == "time" && point
point.timestamp = DateTime.parse(reader.read_string)
end
elsif reader.node_type == XML::Reader::TYPE_END_ELEMENT
- if reader.name == "trkpt" and point and point.valid?
+ if reader.name == "trkpt" && point && point.valid?
point.altitude ||= 0
yield point
@actual_points += 1
end
m += 1
- if m > num_points.to_f / frames.to_f * (mm+1)
+ if m > num_points.to_f / frames.to_f * (mm + 1)
mm += 1
end
il.delay = 50
il.format = 'GIF'
- return il.to_blob
+ il.to_blob
end
def icon(min_lat, min_lon, max_lat, max_lon)
oldpx = px
end
- return image.to_blob
+ image.to_blob
end
end
-private
+ private
class TrkPt < Struct.new(:segment, :latitude, :longitude, :altitude, :timestamp)
def valid?
- self.latitude and self.longitude and self.timestamp and
- self.latitude >= -90 and self.latitude <= 90 and
- self.longitude >= -180 and self.longitude <= 180
+ latitude && longitude && timestamp &&
+ latitude >= -90 && latitude <= 90 &&
+ longitude >= -180 && longitude <= 180
end
end
end
module ID
- LOCALES = Rails.root.join('vendor/assets/iD/iD/locales').entries.map {|p| p.basename.to_s[/(.*).json/] && $1 }.compact
+ LOCALES = Rails.root.join('vendor/assets/iD/iD/locales').entries.map { |p| p.basename.to_s[/(.*).json/] && $1 }.compact
end
end
module SchemaStatements
- def add_primary_key(table_name, column_name, options = {})
+ def add_primary_key(table_name, column_name, _options = {})
execute "ALTER TABLE #{quote_table_name(table_name)} ADD PRIMARY KEY (#{quote_column_name(column_name)})"
end
extend ActionView::Helpers::NumberHelper
def self.describe_location(lat, lon, zoom = nil, language = nil)
- zoom = zoom || 14
- language = language || http_accept_language.user_preferred_languages.join(',')
+ zoom ||= 14
+ language ||= http_accept_language.user_preferred_languages.join(',')
Rails.cache.fetch "/nominatim/location/#{lat}/#{lon}/#{zoom}/#{language}" do
url = "http://nominatim.openstreetmap.org/reverse?lat=#{lat}&lon=#{lon}&zoom=#{zoom}&accept-language=#{language}"
response = nil
end
- if response and result = response.get_text("reversegeocode/result")
+ if response && result = response.get_text("reversegeocode/result")
result.to_s
else
"#{number_with_precision(lat, :precision => 3)}, #{number_with_precision(lon, :precision => 3)}"
false
end
- def redact!(r)
- raise OSM::APICannotRedactError.new
+ def redact!(_r)
+ fail OSM::APICannotRedactError.new
end
end
# The OSM module provides support functions for OSM.
module OSM
-
require 'time'
require 'rexml/parsers/sax2parser'
require 'rexml/text'
# Raised when bad XML is encountered which stops things parsing as
# they should.
class APIBadXMLError < APIError
- def initialize(model, xml, message="")
+ def initialize(model, xml, message = "")
@model, @xml, @message = model, xml, message
end
class Mercator
include Math
- #init me with your bounding box and the size of your image
+ # init me with your bounding box and the size of your image
def initialize(min_lat, min_lon, max_lat, max_lon, width, height)
xsize = xsheet(max_lon) - xsheet(min_lon)
ysize = ysheet(max_lat) - ysheet(min_lat)
@by = ysheet(max_lat) + ypad / 2
end
- #the following two functions will give you the x/y on the entire sheet
+ # the following two functions will give you the x/y on the entire sheet
def ysheet(lat)
log(tan(PI / 4 + (lat * PI / 180 / 2))) / (PI / 180)
lon
end
- #and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
+ # and these two will give you the right points on your image. all the constants can be reduced to speed things up. FIXME
def y(lat)
- return @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
+ @height - ((ysheet(lat) - @ty) / (@by - @ty) * @height)
end
def x(lon)
- return ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
+ ((xsheet(lon) - @tx) / (@bx - @tx) * @width)
end
end
def distance(lat, lon)
lat = lat * PI / 180
lon = lon * PI / 180
- return 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2) ** 2 + cos(@lat) * cos(lat) * sin((lon - @lon)/2) ** 2))
+ 6372.795 * 2 * asin(sqrt(sin((lat - @lat) / 2)**2 + cos(@lat) * cos(lat) * sin((lon - @lon) / 2)**2))
end
# get the worst case bounds for a given radius from the base position
def bounds(radius)
- latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2))
+ latradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2)**2))
begin
- lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2) ** 2 / cos(@lat) ** 2))
+ lonradius = 2 * asin(sqrt(sin(radius / 6372.795 / 2)**2 / cos(@lat)**2))
rescue Errno::EDOM, Math::DomainError
lonradius = PI
end
minlon = (@lon - lonradius) * 180 / PI
maxlon = (@lon + lonradius) * 180 / PI
- return { :minlat => minlat, :maxlat => maxlat, :minlon => minlon, :maxlon => maxlon }
+ { :minlat => minlat, :maxlat => maxlat, :minlon => minlon, :maxlon => maxlon }
end
# get the SQL to use to calculate distance
root['attribution'] = ATTRIBUTION_URL
root['license'] = LICENSE_URL
doc.root = root
- return doc
+ doc
end
end
Timer.timeout(4) do
ipinfo = Quova::IpInfo.new(ip_address)
- if ipinfo.status == Quova::Success then
+ if ipinfo.status == Quova::Success
country = ipinfo.country_code
else
Net::HTTP.start('api.hostip.info') do |http|
def self.IPLocation(ip_address)
code = OSM.IPToCountry(ip_address)
- if code and country = Country.find_by_code(code)
+ if code && country = Country.find_by_code(code)
return { :minlon => country.min_lon, :minlat => country.min_lat, :maxlon => country.max_lon, :maxlat => country.max_lat }
end
- return nil
+ nil
end
# Parse a float, raising a specified exception on failure
token += chars[(rand * chars.length).to_i].chr
end
- return token
+ token
end
# Return an SQL fragment to select a given area of the globe
tilesql = QuadTile.sql_for_area(bbox, prefix)
bbox = bbox.to_scaled
- return "#{tilesql} AND #{prefix}latitude BETWEEN #{bbox.min_lat} AND #{bbox.max_lat} " +
- "AND #{prefix}longitude BETWEEN #{bbox.min_lon} AND #{bbox.max_lon}"
+ "#{tilesql} AND #{prefix}latitude BETWEEN #{bbox.min_lat} AND #{bbox.max_lat} " +
+ "AND #{prefix}longitude BETWEEN #{bbox.min_lon} AND #{bbox.max_lon}"
end
def self.legal_text_for_country(country_code)
file_name = File.join(Rails.root, "config", "legales", country_code.to_s + ".yml")
file_name = File.join(Rails.root, "config", "legales", DEFAULT_LEGALE + ".yml") unless File.exist? file_name
- YAML::load_file(file_name)
+ YAML.load_file(file_name)
end
end
def strip_whitespace
response.body.gsub!(/()|(.*?<\/script>)|()|()|\s+/m) do |m|
if m =~ /^()(.*?)<\/script>$/m
- $1 + $2.strip.gsub(/\s+/, ' ').gsub('',"\n-->") + ''
+ $1 + $2.strip.gsub(/\s+/, ' ').gsub('', "\n-->") + ''
elsif m =~ /^$/m
''
elsif m =~ /^<(textarea|pre)/
def self.create(password)
salt = SecureRandom.base64(SALT_BYTE_SIZE)
hash = self.hash(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE, DIGEST_ALGORITHM)
- return hash, [DIGEST_ALGORITHM, PBKDF2_ITERATIONS, salt].join("!")
+ [hash, [DIGEST_ALGORITHM, PBKDF2_ITERATIONS, salt].join("!")]
end
def self.check(hash, salt, candidate)
candidate = Digest::MD5.hexdigest(salt + candidate)
end
- return hash == candidate
+ hash == candidate
end
def self.upgrade?(hash, salt)
return true
end
- return false
+ false
end
-private
+ private
def self.hash(password, salt, iterations, size, algorithm)
digest = OpenSSL::Digest.new(algorithm)
- pbkdf2 = OpenSSL::PKCS5::pbkdf2_hmac(password, salt, iterations, size, digest)
+ pbkdf2 = OpenSSL::PKCS5.pbkdf2_hmac(password, salt, iterations, size, digest)
Base64.strict_encode64(pbkdf2)
end
end
# The Potlatch module provides helper functions for potlatch and its communication with the server
module Potlatch
-
# The AMF class is a set of helper functions for encoding and decoding AMF.
class AMF
-
# Return two-byte integer
def self.getint(s)
- s.getbyte*256+s.getbyte
+ s.getbyte * 256 + s.getbyte
end
# Return four-byte long
def self.getlong(s)
- ((s.getbyte*256+s.getbyte)*256+s.getbyte)*256+s.getbyte
+ ((s.getbyte * 256 + s.getbyte) * 256 + s.getbyte) * 256 + s.getbyte
end
# Return string with two-byte length
def self.getstring(s)
- len=s.getbyte*256+s.getbyte
- str=s.read(len)
+ len = s.getbyte * 256 + s.getbyte
+ str = s.read(len)
str.force_encoding("UTF-8") if str.respond_to?("force_encoding")
str
end
# Return eight-byte double-precision float
def self.getdouble(s)
- a=s.read(8).unpack('G') # G big-endian, E little-endian
+ a = s.read(8).unpack('G') # G big-endian, E little-endian
a[0]
end
# Return numeric array
def self.getarray(s)
- len=getlong(s)
- arr=[]
- for i in (0..len-1)
- arr[i]=getvalue(s)
+ len = getlong(s)
+ arr = []
+ for i in (0..len - 1)
+ arr[i] = getvalue(s)
end
arr
end
# Return object/hash
def self.getobject(s)
- arr={}
- while (key=getstring(s))
- if (key=='') then break end
- arr[key]=getvalue(s)
+ arr = {}
+ while (key = getstring(s))
+ if (key == '') then break end
+ arr[key] = getvalue(s)
end
s.getbyte # skip the 9 'end of object' value
arr
# Parse and get value
def self.getvalue(s)
case s.getbyte
- when 0; return getdouble(s) # number
- when 1; return s.getbyte # boolean
- when 2; return getstring(s) # string
- when 3; return getobject(s) # object/hash
- when 5; return nil # null
- when 6; return nil # undefined
- when 8; s.read(4) # mixedArray
- return getobject(s) # |
- when 10; return getarray(s) # array
+ when 0 then return getdouble(s) # number
+ when 1 then return s.getbyte # boolean
+ when 2 then return getstring(s) # string
+ when 3 then return getobject(s) # object/hash
+ when 5 then return nil # null
+ when 6 then return nil # undefined
+ when 8 then s.read(4) # mixedArray
+ return getobject(s) # |
+ when 10 then return getarray(s) # array
else; return nil # error
end
end
# Envelope data into AMF writeable form
- def self.putdata(index,n)
- d =encodestring(index+"/onResult")
- d+=encodestring("null")
- d+=[-1].pack("N")
- d+=encodevalue(n)
+ def self.putdata(index, n)
+ d = encodestring(index + "/onResult")
+ d += encodestring("null")
+ d += [-1].pack("N")
+ d += encodevalue(n)
end
# Pack variables as AMF
def self.encodevalue(n)
case n.class.to_s
when 'Array'
- a=10.chr+encodelong(n.length)
+ a = 10.chr + encodelong(n.length)
n.each do |b|
- a+=encodevalue(b)
+ a += encodevalue(b)
end
a
when 'Hash'
- a=3.chr
- n.each do |k,v|
- a+=encodestring(k.to_s)+encodevalue(v)
+ a = 3.chr
+ n.each do |k, v|
+ a += encodestring(k.to_s) + encodevalue(v)
end
- a+0.chr+0.chr+9.chr
+ a + 0.chr + 0.chr + 9.chr
when 'String'
- 2.chr+encodestring(n)
- when 'Bignum','Fixnum','Float'
- 0.chr+encodedouble(n)
+ 2.chr + encodestring(n)
+ when 'Bignum', 'Fixnum', 'Float'
+ 0.chr + encodedouble(n)
when 'NilClass'
5.chr
- when 'TrueClass'
- 0.chr+encodedouble(1)
- when 'FalseClass'
- 0.chr+encodedouble(0)
- else
- Rails.logger.error("Unexpected Ruby type for AMF conversion: "+n.class.to_s)
+ when 'TrueClass'
+ 0.chr + encodedouble(1)
+ when 'FalseClass'
+ 0.chr + encodedouble(0)
+ else
+ Rails.logger.error("Unexpected Ruby type for AMF conversion: " + n.class.to_s)
end
end
# Encode string with two-byte length
def self.encodestring(n)
- n=n.dup.force_encoding("ASCII-8BIT") if n.respond_to?("force_encoding")
- a,b=n.size.divmod(256)
- a.chr+b.chr+n
+ n = n.dup.force_encoding("ASCII-8BIT") if n.respond_to?("force_encoding")
+ a, b = n.size.divmod(256)
+ a.chr + b.chr + n
end
# Encode number as eight-byte double precision float
def self.encodelong(n)
[n].pack('N')
end
-
end
# The Dispatcher class handles decoding a series of RPC calls
# from the request, dispatching them, and encoding the response
class Dispatcher
- def initialize(request, &block)
+ def initialize(request, &_block)
# Get stream for request data
@request = StringIO.new(request + 0.chr)
@dispatch = Proc.new
end
- def each(&block)
+ def each(&_block)
# Read number of message bodies
bodies = AMF.getint(@request)
# Output response header
- a,b = bodies.divmod(256)
+ a, b = bodies.divmod(256)
yield 0.chr + 0.chr + 0.chr + 0.chr + a.chr + b.chr
# Process the bodies
# The Potlatch class is a helper for Potlatch
class Potlatch
-
# ----- getpresets
# in: none
# does: reads tag preset menus, colours, and autocomplete config files
Rails.logger.info(" Message: getpresets")
# Read preset menus
- presets={}
- presetmenus={}; presetmenus['point']=[]; presetmenus['way']=[]; presetmenus['POI']=[]
- presetnames={}; presetnames['point']={}; presetnames['way']={}; presetnames['POI']={}
- presettype=''
- presetcategory=''
+ presets = {}
+ presetmenus = {}; presetmenus['point'] = []; presetmenus['way'] = []; presetmenus['POI'] = []
+ presetnames = {}; presetnames['point'] = {}; presetnames['way'] = {}; presetnames['POI'] = {}
+ presettype = ''
+ presetcategory = ''
# StringIO.open(txt) do |file|
File.open("#{Rails.root}/config/potlatch/presets.txt") do |file|
- file.each_line {|line|
- t=line.chomp
- if (t=~/(\w+)\/(\w+)/) then
- presettype=$1
- presetcategory=$2
+ file.each_line do|line|
+ t = line.chomp
+ if t =~ /(\w+)\/(\w+)/
+ presettype = $1
+ presetcategory = $2
presetmenus[presettype].push(presetcategory)
- presetnames[presettype][presetcategory]=["(no preset)"]
- elsif (t=~/^([\w\s]+):\s?(.+)$/) then
- pre=$1; kv=$2
+ presetnames[presettype][presetcategory] = ["(no preset)"]
+ elsif t =~ /^([\w\s]+):\s?(.+)$/
+ pre = $1; kv = $2
presetnames[presettype][presetcategory].push(pre)
- presets[pre]={}
- kv.split(',').each {|a|
- if (a=~/^(.+)=(.*)$/) then presets[pre][$1]=$2 end
- }
+ presets[pre] = {}
+ kv.split(',').each do|a|
+ if a =~ /^(.+)=(.*)$/ then presets[pre][$1] = $2 end
+ end
end
- }
+ end
end
# Read colours/styling
- colours={}; casing={}; areas={}
+ colours = {}; casing = {}; areas = {}
File.open("#{Rails.root}/config/potlatch/colours.txt") do |file|
- file.each_line {|line|
- t=line.chomp
- if (t=~/(\w+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)/) then
- tag=$1
- if ($2!='-') then colours[tag]=$2.hex end
- if ($3!='-') then casing[tag]=$3.hex end
- if ($4!='-') then areas[tag]=$4.hex end
+ file.each_line do|line|
+ t = line.chomp
+ if t =~ /(\w+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)/
+ tag = $1
+ if ($2 != '-') then colours[tag] = $2.hex end
+ if ($3 != '-') then casing[tag] = $3.hex end
+ if ($4 != '-') then areas[tag] = $4.hex end
end
- }
+ end
end
# Read relations colours/styling
- relcolours={}; relalphas={}; relwidths={}
+ relcolours = {}; relalphas = {}; relwidths = {}
File.open("#{Rails.root}/config/potlatch/relation_colours.txt") do |file|
- file.each_line {|line|
- t=line.chomp
- if (t=~/(\w+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)/) then
- tag=$1
- if ($2!='-') then relcolours[tag]=$2.hex end
- if ($3!='-') then relalphas[tag]=$3.to_i end
- if ($4!='-') then relwidths[tag]=$4.to_i end
+ file.each_line do|line|
+ t = line.chomp
+ if t =~ /(\w+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)/
+ tag = $1
+ if ($2 != '-') then relcolours[tag] = $2.hex end
+ if ($3 != '-') then relalphas[tag] = $3.to_i end
+ if ($4 != '-') then relwidths[tag] = $4.to_i end
end
- }
+ end
end
# Read POI presets
- icon_list=[]; icon_tags={};
+ icon_list = []; icon_tags = {}
File.open("#{Rails.root}/config/potlatch/icon_presets.txt") do |file|
- file.each_line {|line|
- (icon,tags)=line.chomp.split("\t")
+ file.each_line do|line|
+ (icon, tags) = line.chomp.split("\t")
icon_list.push(icon)
- icon_tags[icon]=Hash[*tags.scan(/([^;=]+)=([^;=]+)/).flatten]
- }
+ icon_tags[icon] = Hash[*tags.scan(/([^;=]+)=([^;=]+)/).flatten]
+ end
end
icon_list.reverse!
# Read auto-complete
- autotags={}; autotags['point']={}; autotags['way']={}; autotags['POI']={};
+ autotags = {}; autotags['point'] = {}; autotags['way'] = {}; autotags['POI'] = {}
File.open("#{Rails.root}/config/potlatch/autocomplete.txt") do |file|
- file.each_line {|line|
- t=line.chomp
- if (t=~/^([\w:]+)\/(\w+)\s+(.+)$/) then
- tag=$1; type=$2; values=$3
- if values=='-' then autotags[type][tag]=[]
- else autotags[type][tag]=values.split(',').sort.reverse end
+ file.each_line do|line|
+ t = line.chomp
+ if t =~ /^([\w:]+)\/(\w+)\s+(.+)$/
+ tag = $1; type = $2; values = $3
+ if values == '-' then autotags[type][tag] = []
+ else autotags[type][tag] = values.split(',').sort.reverse end
end
- }
+ end
end
- [presets,presetmenus,presetnames,colours,casing,areas,autotags,relcolours,relalphas,relwidths,icon_list,{},icon_tags]
+ [presets, presetmenus, presetnames, colours, casing, areas, autotags, relcolours, relalphas, relwidths, icon_list, {}, icon_tags]
end
end
-
end
x = ((lon.to_f + 180) * 65535 / 360).round
y = ((lat.to_f + 90) * 65535 / 180).round
- return tile_for_xy(x, y)
+ tile_for_xy(x, y)
end
def self.tiles_for_area(bbox)
end
end
- return tiles
+ tiles
end
def self.tile_for_xy(x, y)
16.times do
t = t << 1
- t = t | 1 unless (x & 0x8000).zero?
+ t |= 1 unless (x & 0x8000).zero?
x <<= 1
t = t << 1
- t = t | 1 unless (y & 0x8000).zero?
+ t |= 1 unless (y & 0x8000).zero?
y <<= 1
end
- return t
+ t
end
def self.iterate_tiles_for_area(bbox)
end
def self.sql_for_area(bbox, prefix)
- sql = Array.new
- single = Array.new
+ sql = []
+ single = []
- iterate_tiles_for_area(bbox) do |first,last|
+ iterate_tiles_for_area(bbox) do |first, last|
if first == last
single.push(first)
else
sql.push("#{prefix}tile IN (#{single.join(',')})") if single.size > 0
- return "( " + sql.join(" OR ") + " )"
+ "( " + sql.join(" OR ") + " )"
end
private_class_method :tile_for_xy, :iterate_tiles_for_area
# Monkey patch WSDL parser to stop it moaning
module WSDL
class Parser
- def warn(msg)
+ def warn(_msg)
end
end
end
module Quova
##
# Access details for WSDL description
- WSDL_URL="https://webservices.quova.com/OnDemand/GeoPoint/v1/default.asmx?WSDL"
+ WSDL_URL = "https://webservices.quova.com/OnDemand/GeoPoint/v1/default.asmx?WSDL"
WSDL_USER = QUOVA_USERNAME
WSDL_PASS = QUOVA_PASSWORD
# Class representing geolocation details for an IP address
class IpInfo
def initialize(ip_address)
- @ipinfo = Quova::soap.GetIpInfo(:ipAddress => ip_address)
+ @ipinfo = Quova.soap.GetIpInfo(:ipAddress => ip_address)
end
def status
end
def redacted?
- not self.redaction.nil?
+ !redaction.nil?
end
def redact!(redaction)
# check that this version isn't the current version
- raise OSM::APICannotRedactError.new if self.is_latest_version?
+ fail OSM::APICannotRedactError.new if self.is_latest_version?
# make the change
self.redaction = redaction
module RichText
def self.new(format, text)
case format
- when "html"; HTML.new(text || "")
- when "markdown"; Markdown.new(text || "")
- when "text"; Text.new(text || "")
+ when "html" then HTML.new(text || "")
+ when "markdown" then Markdown.new(text || "")
+ when "text" then Text.new(text || "")
else; nil
end
end
link_proportion = 0
end
- return [link_proportion - 0.2, 0.0].max * 200 + link_count * 40
+ [link_proportion - 0.2, 0.0].max * 200 + link_count * 40
end
- protected
+ protected
def simple_format(text)
SimpleFormat.new.simple_format(text)
end
def to_text
- self.to_s
+ to_s
end
- private
+ private
def sanitize(text)
Sanitize.clean(text, Sanitize::Config::OSM).html_safe
end
def to_text
- self.to_s
+ to_s
end
- private
+ private
def html_parser
- @@html_renderer ||= Renderer.new({
- :filter_html => true, :safe_links_only => true
- })
- @@html_parser ||= Redcarpet::Markdown.new(@@html_renderer, {
- :no_intra_emphasis => true, :autolink => true, :space_after_headers => true
- })
+ @@html_renderer ||= Renderer.new(:filter_html => true, :safe_links_only => true)
+ @@html_parser ||= Redcarpet::Markdown.new(@@html_renderer, :no_intra_emphasis => true, :autolink => true, :space_after_headers => true)
end
class Renderer < Redcarpet::Render::XHTML
- def link(link, title, alt_text)
+ def link(link, _title, alt_text)
"<a rel=\"nofollow\" href=\"#{link}\">#{alt_text}</a>"
end
end
def to_text
- self.to_s
+ to_s
end
end
end
# Each character encodes 3 bits of x and 3 of y, so there are extra characters
# tacked on the end to make the zoom levels "work".
module ShortLink
-
# array of 64 chars to encode 6 bits. this is almost like base64 encoding, but
# the symbolic chars are different, as base64's + and / aren't very
# URL-friendly.
- ARRAY = ('A'..'Z').to_a + ('a'..'z').to_a + ('0'..'9').to_a + ['_','~']
+ ARRAY = ('A'..'Z').to_a + ('a'..'z').to_a + ('0'..'9').to_a + ['_', '~']
##
# Given a string encoding a location, returns the [lon, lat, z] tuple of that
# keep support for old shortlinks which use the @ character, now
# replaced by the ~ character because twitter is horribly broken
# and we can't have that.
- str.gsub!("@","~")
+ str.gsub!("@", "~")
str.each_char do |c|
t = ARRAY.index c
z_offset -= 1
else
3.times do
- x <<= 1; x = x | 1 unless (t & 32).zero?; t <<= 1
- y <<= 1; y = y | 1 unless (t & 32).zero?; t <<= 1
+ x <<= 1; x |= 1 unless (t & 32).zero?; t <<= 1
+ y <<= 1; y |= 1 unless (t & 32).zero?; t <<= 1
end
z += 3
end
str = ""
# add eight to the zoom level, which approximates an accuracy of
# one pixel in a tile.
- ((z + 8)/3.0).ceil.times do |i|
+ ((z + 8) / 3.0).ceil.times do |i|
digit = (code >> (58 - 6 * i)) & 0x3f
str << ARRAY[digit]
end
# of 3 zoom levels).
((z + 8) % 3).times { str << "-" }
- return str
+ str
end
private
end
c
end
-
end
while offset < (id_max + increment)
hash = {}
- #should be offsetting not selecting
+ # should be offsetting not selecting
OldNode.find(:all, :limit => increment, :offset => offset, :order => 'timestamp').each do |node|
- if hash[node.id].nil?
- hash[node.id] = []
- end
- hash[node.id] << node
+ if hash[node.id].nil?
+ hash[node.id] = []
+ end
+ hash[node.id] << node
end
hash.each_value do |node_array|
temp_old_node.timestamp = node.timestamp
temp_old_node.tile = node.tile
temp_old_node.version = n
- temp_old_node.save! || raise
- n +=1
+ temp_old_node.save! || fail
+ n += 1
end
end
offset += increment
##
# Checks that a string is valid UTF-8 by trying to convert it to UTF-8
# using the iconv library, which is in the standard library.
- if String.new.respond_to?("valid_encoding?")
+ if ''.respond_to?("valid_encoding?")
def self.valid?(str)
return true if str.nil?
- return str.valid_encoding?
+ str.valid_encoding?
end
else
require 'iconv'
module ActiveRecord
module Validations
module ClassMethods
-
# error message when invalid UTF-8 is detected
@@invalid_utf8_message = " is invalid UTF-8"
record.errors.add(attr, @@invalid_utf8_message) unless UTF8.valid? value
end
end
-
end
end
end
#!/usr/bin/env ruby
-Dir[File.dirname(__FILE__) + "/../lib/daemons/*_ctl"].each {|f| `#{f} #{ARGV.first}`}
+Dir[File.dirname(__FILE__) + "/../lib/daemons/*_ctl"].each { |f| `#{f} #{ARGV.first}` }
to = message.sender
end
-exit 0 unless recipient[3] == digest[0,6]
+exit 0 unless recipient[3] == digest[0, 6]
exit 0 if date < 1.month.ago
message.update_attribute(:message_read, true) if message
if keys.empty?
hash[key] = value
else
- unless hash.has_key? key
+ unless hash.key? key
hash[key] = {}
end
add_translation(hash[key], keys, value)
trs = {}
path = []
msgstr = ''
- f.each_line { |line|
+ f.each_line do |line|
line.strip!
if line[0..8] == 'msgctxt "'
path = line[9..-2].split(':')
msgstr = line[8..-2]
end
- if !path.empty? and !msgstr.empty?
+ if !path.empty? && !msgstr.empty?
add_translation(trs, path, msgstr)
path = []
msgstr = ''
end
- }
+ end
trs
end
langcode = File.basename(filename, '.po')
-tr = {langcode => po2hash(pofile)}
+tr = { langcode => po2hash(pofile) }
print tr.to_yaml
require "optparse"
LOCALE_DIR = File.dirname(__FILE__) + '/../../config/locales/'
-EN = YAML::load_file(LOCALE_DIR+'en.yml')
+EN = YAML.load_file(LOCALE_DIR + 'en.yml')
-def iterate(hash, fhash={}, path='', outfile=$stdout)
+def iterate(hash, fhash = {}, path = '', outfile = $stdout)
postr = ''
- hash.each {|key, val|
- fhash[key] = {} unless fhash.has_key? key
+ hash.each do |key, val|
+ fhash[key] = {} unless fhash.key? key
if val.is_a? Hash
fhash[key] = {} unless fhash[key].is_a? Hash
- iterate(val, fhash[key], path+key+':', outfile)
+ iterate(val, fhash[key], path + key + ':', outfile)
else
outfile.puts "msgctxt \"#{path}#{key}\""
outfile.puts "msgid \"#{val}\""
outfile.puts "msgstr \"#{fhash[key]}\""
end
- }
+ end
end
-def lang2po(lang, outfile=$stdout)
+def lang2po(lang, outfile = $stdout)
puts lang
oth = {}
- infile = LOCALE_DIR+lang+'.yml'
- if File.exists? infile
- oth = YAML::load_file(infile)
+ infile = LOCALE_DIR + lang + '.yml'
+ if File.exist? infile
+ oth = YAML.load_file(infile)
oth = oth[lang]
iterate(EN['en'], oth, '', outfile)
else
opt = ARGV[0]
if opt == '--all'
# Produce .po files for all langs, and a .pot template
- PO_DIR = LOCALE_DIR+'po/'
+ PO_DIR = LOCALE_DIR + 'po/'
Dir.mkdir(PO_DIR) unless File.directory?(PO_DIR)
- Dir.glob(LOCALE_DIR+"*.yml") {|filename|
+ Dir.glob(LOCALE_DIR + "*.yml") do |filename|
lang = File.basename(filename, '.yml')
unless lang == 'en'
- outfile = File.new(PO_DIR+"#{lang}.po", 'w')
+ outfile = File.new(PO_DIR + "#{lang}.po", 'w')
lang2po(lang, outfile)
outfile.close
end
- }
- outfile = File.new(PO_DIR+"rails_port.pot", 'w')
+ end
+ outfile = File.new(PO_DIR + "rails_port.pot", 'w')
iterate(EN['en'], {}, '', outfile)
outfile.close
elsif opt
puts "<style>th { text-align: left }</style>"
puts "</head>"
puts "<body>"
-puts "<h2>OpenStreetMap stats report run at #{start_time.to_s}</h2>"
+puts "<h2>OpenStreetMap stats report run at #{start_time}</h2>"
begin
ActiveRecord::Base.transaction do
- user_count = User.where(:status => ["active", "confirmed", "suspended"]).count
+ user_count = User.where(:status => %w(active confirmed suspended)).count
tracepoint_count = Tracepoint.count
node_count = Node.where(:visible => true).count
way_count = Way.where(:visible => true).count
puts "</table>"
end
rescue Exception => e
- puts "<p><em>Exception: #{e.to_s}</em><br />#{e.backtrace.join('<br />')}</p>"
+ puts "<p><em>Exception: #{e}</em><br />#{e.backtrace.join('<br />')}</p>"
end
-puts "<p>Report took #{(Time.new - start_time).to_s} seconds to run</p>"
+puts "<p>Report took #{(Time.new - start_time)} seconds to run</p>"
puts "</body>"
puts "</html>"
addresses = User.count(
:conditions => {
- :status => ["suspended", "deleted"],
- :creation_time => Time.now - 28.days .. Time.now
+ :status => %w(suspended deleted),
+ :creation_time => Time.now - 28.days..Time.now
},
:group => :creation_ip
)
-addresses.each do |address,count|
+addresses.each do |address, count|
if count > 1
acl = Acl.find(:first, :conditions => {
- :address => address,
- })
+ :address => address
+ })
unless acl
Acl.create({
- :address => address,
- :k => "no_account_creation",
- :v => "auto_spam_block"
- }, :without_protection => true)
+ :address => address,
+ :k => "no_account_creation",
+ :v => "auto_spam_block"
+ }, { :without_protection => true })
puts "Blocked #{address}"
end
end
acls = Acl.find(:all, :conditions => {
- :k => "no_account_creation",
- :v => "auto_spam_block"
-})
+ :k => "no_account_creation",
+ :v => "auto_spam_block"
+ })
acls.each do |acl|
unless addresses[acl.address]
assert_equal -4, way[0], -4
assert_equal "way", way[1]
assert_equal id, way[2]
- assert way[3].nil? and way[4].nil? and way[5].nil? and way[6].nil?
+ assert(way[3].nil?) && way[4].nil? && way[5].nil? && way[6].nil?
end
def test_getway_with_versions
assert_equal -4, way[0]
assert_equal "way", way[1]
assert_equal 0, way[2]
- assert way[3].nil? and way[4].nil? and way[5].nil? and way[6].nil?
+ assert(way[3].nil?) && way[4].nil? && way[5].nil? && way[6].nil?
end
def test_whichways
node = current_nodes(:used_node_1)
- minlon = node.lon-0.1
- minlat = node.lat-0.1
- maxlon = node.lon+0.1
- maxlat = node.lat+0.1
+ minlon = node.lon - 0.1
+ minlat = node.lat - 0.1
+ maxlon = node.lon + 0.1
+ maxlat = node.lat + 0.1
amf_content "whichways", "/1", [minlon, minlat, maxlon, maxlat]
post :amf_read
assert_response :success
# so someone who knows what they're doing should check this!
ways = map[2].collect { |x| x[0] }
assert ways.include?(current_ways(:used_way).id),
- "map should include used way"
+ "map should include used way"
assert !ways.include?(current_ways(:invisible_way).id),
- 'map should not include deleted way'
+ 'map should not include deleted way'
end
##
# checks that too-large a bounding box will not be served.
def test_whichways_toobig
- bbox = [-0.1,-0.1,1.1,1.1]
- check_bboxes_are_bad [bbox] do |map,bbox|
+ bbox = [-0.1, -0.1, 1.1, 1.1]
+ check_bboxes_are_bad [bbox] do |map, _bbox|
assert_boundary_error map, " The server said: The maximum bbox size is 0.25, and your request was too large. Either request a smaller area, or use planet.osm"
end
end
#
# NOTE: the controller expands the bbox by 0.01 in each direction!
def test_whichways_badlat
- bboxes = [[0,0.1,0.1,0], [-0.1,80,0.1,70], [0.24,54.35,0.25,54.33]]
+ bboxes = [[0, 0.1, 0.1, 0], [-0.1, 80, 0.1, 70], [0.24, 54.35, 0.25, 54.33]]
check_bboxes_are_bad bboxes do |map, bbox|
assert_boundary_error map, " The server said: The minimum latitude must be less than the maximum latitude, but it wasn't", bbox.inspect
end
#
# NOTE: the controller expands the bbox by 0.01 in each direction!
def test_whichways_badlon
- bboxes = [[80,-0.1,70,0.1], [54.35,0.24,54.33,0.25]]
+ bboxes = [[80, -0.1, 70, 0.1], [54.35, 0.24, 54.33, 0.25]]
check_bboxes_are_bad bboxes do |map, bbox|
assert_boundary_error map, " The server said: The minimum longitude must be less than the maximum longitude, but it wasn't", bbox.inspect
end
def test_whichways_deleted
node = current_nodes(:used_node_1)
- minlon = node.lon-0.1
- minlat = node.lat-0.1
- maxlon = node.lon+0.1
- maxlat = node.lat+0.1
+ minlon = node.lon - 0.1
+ minlat = node.lat - 0.1
+ maxlon = node.lon + 0.1
+ maxlat = node.lat + 0.1
amf_content "whichways_deleted", "/1", [minlon, minlat, maxlon, maxlat]
post :amf_read
assert_response :success
# TODO: looks like amf_controller changed since this test was written
# so someone who knows what they're doing should check this!
assert !map[2].include?(current_ways(:used_way).id),
- "map should not include used way"
+ "map should not include used way"
assert map[2].include?(current_ways(:invisible_way).id),
- 'map should include deleted way'
+ 'map should include deleted way'
end
def test_whichways_deleted_toobig
- bbox = [-0.1,-0.1,1.1,1.1]
+ bbox = [-0.1, -0.1, 1.1, 1.1]
amf_content "whichways_deleted", "/1", bbox
post :amf_read
assert_response :success
assert_equal rel[0], -4
assert_equal rel[1], "relation"
assert_equal rel[2], id
- assert rel[3].nil? and rel[4].nil?
+ assert(rel[3].nil?) && rel[4].nil?
end
def test_getrelation_nonexistent
assert_equal rel[0], -4
assert_equal rel[1], "relation"
assert_equal rel[2], id
- assert rel[3].nil? and rel[4].nil?
+ assert(rel[3].nil?) && rel[4].nil?
end
def test_getway_old
# note that (as per getway_history) we actually round up
# to the next second
assert_equal history[0], 'node',
- 'first element should be "node"'
+ 'first element should be "node"'
assert_equal history[1], latest.id,
- 'second element should be the input node ID'
+ 'second element should be the input node ID'
assert_equal history[2].first[0],
- (latest.timestamp + 1).strftime("%d %b %Y, %H:%M:%S"),
- 'first element in third element (array) should be the latest version'
+ (latest.timestamp + 1).strftime("%d %b %Y, %H:%M:%S"),
+ 'first element in third element (array) should be the latest version'
assert_equal history[2].last[0],
- (nodes(:node_with_versions_v1).timestamp + 1).strftime("%d %b %Y, %H:%M:%S"),
- 'last element in third element (array) should be the initial version'
+ (nodes(:node_with_versions_v1).timestamp + 1).strftime("%d %b %Y, %H:%M:%S"),
+ 'last element in third element (array) should be the initial version'
end
def test_getnode_history_nonexistent
assert_equal "", result[1]
assert_equal nd.id, result[2]
assert_equal nd.id, result[3]
- assert_equal nd.version+1, result[4]
+ assert_equal nd.version + 1, result[4]
# Now try to update again, with a different lat/lon, using the updated version number
- lat = nd.lat+0.1
- lon = nd.lon-0.1
- amf_content "putpoi", "/2", ["test@example.com:test", cs_id, nd.version+1, nd.id, lon, lat, nd.tags, nd.visible]
+ lat = nd.lat + 0.1
+ lon = nd.lon - 0.1
+ amf_content "putpoi", "/2", ["test@example.com:test", cs_id, nd.version + 1, nd.id, lon, lat, nd.tags, nd.visible]
post :amf_write
assert_response :success
amf_parse_response
assert_equal "", result[1]
assert_equal nd.id, result[2]
assert_equal nd.id, result[3]
- assert_equal nd.version+2, result[4]
+ assert_equal nd.version + 2, result[4]
end
# Check that we can create a no valid poi
# This node has no tags
nd = Node.new
# create a node with random lat/lon
- lat = rand(100)-50 + rand
- lon = rand(100)-50 + rand
+ lat = rand(100) - 50 + rand
+ lon = rand(100) - 50 + rand
# normal user has a changeset open
changeset = changesets(:public_user_first_change)
# This node has some tags
tnd = Node.new
# create a node with random lat/lon
- lat = rand(100)-50 + rand
- lon = rand(100)-50 + rand
+ lat = rand(100) - 50 + rand
+ lon = rand(100) - 50 + rand
# normal user has a changeset open
changeset = changesets(:public_user_first_change)
# This node has no tags
nd = Node.new
# create a node with random lat/lon
- lat = rand(100)-50 + rand
- lon = rand(100)-50 + rand
+ lat = rand(100) - 50 + rand
+ lon = rand(100) - 50 + rand
# normal user has a changeset open
changeset = changesets(:public_user_first_change)
- mostly_invalid = (0..31).to_a.map {|i| i.chr}.join
+ mostly_invalid = (0..31).to_a.map(&:chr).join
tags = { "something" => "foo#{mostly_invalid}bar" }
amf_content "putpoi", "/1", ["test@example.com:test", changeset.id, nil, nil, lon, lat, tags, nil]
# This node has no tags
nd = Node.new
# create a node with random lat/lon
- lat = rand(100)-50 + rand
- lon = rand(100)-50 + rand
+ lat = rand(100) - 50 + rand
+ lon = rand(100) - 50 + rand
# normal user has a changeset open
changeset = changesets(:public_user_first_change)
end
def test_putpoi_delete_valid
-
end
def test_putpoi_delete_already_deleted
-
end
def test_putpoi_delete_not_found
-
end
def test_putpoi_invalid_latlon
-
end
def test_startchangeset_invalid_xmlchar_comment
invalid = "\035\022"
comment = "foo#{invalid}bar"
- amf_content "startchangeset", "/1", ["test@example.com:test", Hash.new, nil, comment, 1]
+ amf_content "startchangeset", "/1", ["test@example.com:test", {}, nil, comment, 1]
post :amf_write
assert_response :success
amf_parse_response
# Get the result record for the specified ID
# It's an assertion FAIL if the record does not exist
- def amf_result ref
- assert @amf_result.has_key?("#{ref}/onResult")
+ def amf_result(ref)
+ assert @amf_result.key?("#{ref}/onResult")
@amf_result["#{ref}/onResult"]
end
# Encode the AMF message to invoke "target" with parameters as
# the passed data. The ref is used to retrieve the results.
def amf_content(target, ref, data)
- a,b=1.divmod(256)
- c = StringIO.new()
- c.write 0.chr+0.chr # version 0
- c.write 0.chr+0.chr # n headers
- c.write a.chr+b.chr # n bodies
+ a, b = 1.divmod(256)
+ c = StringIO.new
+ c.write 0.chr + 0.chr # version 0
+ c.write 0.chr + 0.chr # n headers
+ c.write a.chr + b.chr # n bodies
c.write AMF.encodestring(target)
c.write AMF.encodestring(ref)
c.write [-1].pack("N")
req.read(2) # version
# parse through any headers
- headers=AMF.getint(req) # Read number of headers
- headers.times do # Read each header
- name=AMF.getstring(req) # |
- req.getc # | skip boolean
- value=AMF.getvalue(req) # |
- end
+ headers = AMF.getint(req) # Read number of headers
+ headers.times do # Read each header
+ name = AMF.getstring(req) # |
+ req.getc # | skip boolean
+ value = AMF.getvalue(req) # |
+ end
# parse through responses
results = {}
- bodies=AMF.getint(req) # Read number of bodies
- bodies.times do # Read each body
- message=AMF.getstring(req) # | get message name
- index=AMF.getstring(req) # | get index in response sequence
- bytes=AMF.getlong(req) # | get total size in bytes
- args=AMF.getvalue(req) # | get response (probably an array)
+ bodies = AMF.getint(req) # Read number of bodies
+ bodies.times do # Read each body
+ message = AMF.getstring(req) # | get message name
+ index = AMF.getstring(req) # | get index in response sequence
+ bytes = AMF.getlong(req) # | get total size in bytes
+ args = AMF.getvalue(req) # | get response (probably an array)
results[message] = args
end
@amf_result = results
# this should be what AMF controller returns when the bbox of a
# whichways request is invalid or too large.
- def assert_boundary_error(map, msg=nil, error_hint=nil)
+ def assert_boundary_error(map, msg = nil, error_hint = nil)
expected_map = [-2, "Sorry - I can't get the map for that area.#{msg}"]
assert_equal expected_map, map, "AMF controller should have returned an error. (#{error_hint})"
end
# this should be what AMF controller returns when the bbox of a
# whichways_deleted request is invalid or too large.
- def assert_deleted_boundary_error(map, msg=nil, error_hint=nil)
+ def assert_deleted_boundary_error(map, msg = nil, error_hint = nil)
expected_map = [-2, "Sorry - I can't get the map for that area.#{msg}"]
assert_equal expected_map, map, "AMF controller should have returned an error. (#{error_hint})"
end
def setup
super
- @badbigbbox = %w{ -0.1,-0.1,1.1,1.1 10,10,11,11 }
- @badmalformedbbox = %w{ -0.1 hello
- 10N2W10.1N2.1W }
- @badlatmixedbbox = %w{ 0,0.1,0.1,0 -0.1,80,0.1,70 0.24,54.34,0.25,54.33 }
- @badlonmixedbbox = %w{ 80,-0.1,70,0.1 54.34,0.24,54.33,0.25 }
- #@badlatlonoutboundsbbox = %w{ 191,-0.1,193,0.1 -190.1,89.9,-190,90 }
- @goodbbox = %w{ -0.1,-0.1,0.1,0.1 51.1,-0.1,51.2,0
- -0.1,%20-0.1,%200.1,%200.1 -0.1edcd,-0.1d,0.1,0.1 -0.1E,-0.1E,0.1S,0.1N S0.1,W0.1,N0.1,E0.1}
+ @badbigbbox = %w(-0.1,-0.1,1.1,1.1 10,10,11,11)
+ @badmalformedbbox = %w(-0.1 hello
+ 10N2W10.1N2.1W)
+ @badlatmixedbbox = %w(0,0.1,0.1,0 -0.1,80,0.1,70 0.24,54.34,0.25,54.33)
+ @badlonmixedbbox = %w(80,-0.1,70,0.1 54.34,0.24,54.33,0.25)
+ # @badlatlonoutboundsbbox = %w{ 191,-0.1,193,0.1 -190.1,89.9,-190,90 }
+ @goodbbox = %w(-0.1,-0.1,0.1,0.1 51.1,-0.1,51.2,0
+ -0.1,%20-0.1,%200.1,%200.1 -0.1edcd,-0.1d,0.1,0.1 -0.1E,-0.1E,0.1S,0.1N S0.1,W0.1,N0.1,E0.1)
# That last item in the goodbbox really shouldn't be there, as the API should
# reall reject it, however this is to test to see if the api changes.
end
node = current_nodes(:used_node_1)
# Need to split the min/max lat/lon out into their own variables here
# so that we can test they are returned later.
- minlon = node.lon-0.1
- minlat = node.lat-0.1
- maxlon = node.lon+0.1
- maxlat = node.lat+0.1
+ minlon = node.lon - 0.1
+ minlat = node.lat - 0.1
+ maxlon = node.lon + 0.1
+ maxlat = node.lat + 0.1
bbox = "#{minlon},#{minlat},#{maxlon},#{maxlat}"
get :map, :bbox => bbox
if $VERBOSE
def test_tracepoints
point = gpx_files(:public_trace_file)
- minlon = point.longitude-0.001
- minlat = point.latitude-0.001
- maxlon = point.longitude+0.001
- maxlat = point.latitude+0.001
+ minlon = point.longitude - 0.001
+ minlat = point.latitude - 0.001
+ maxlon = point.longitude + 0.001
+ maxlat = point.latitude + 0.001
bbox = "#{minlon},#{minlat},#{maxlon},#{maxlat}"
get :trackpoints, :bbox => bbox
assert_response :success
def test_tracepoints_trackable
point = gpx_files(:trackable_trace_file)
- minlon = point.longitude-0.002
- minlat = point.latitude-0.002
- maxlon = point.longitude+0.002
- maxlat = point.latitude+0.002
+ minlon = point.longitude - 0.002
+ minlat = point.latitude - 0.002
+ maxlon = point.longitude + 0.002
+ maxlat = point.latitude + 0.002
bbox = "#{minlon},#{minlat},#{maxlon},#{maxlat}"
get :trackpoints, :bbox => bbox
assert_response :success
def test_tracepoints_identifiable
point = gpx_files(:identifiable_trace_file)
- minlon = point.longitude-0.002
- minlat = point.latitude-0.002
- maxlon = point.longitude+0.002
- maxlat = point.latitude+0.002
+ minlon = point.longitude - 0.002
+ minlat = point.latitude - 0.002
+ maxlon = point.longitude + 0.002
+ maxlat = point.latitude + 0.002
bbox = "#{minlon},#{minlat},#{maxlon},#{maxlat}"
get :trackpoints, :bbox => bbox
assert_response :success
end
def test_map_without_bbox
- ["trackpoints", "map"].each do |tq|
+ %w(trackpoints map).each do |tq|
get tq
assert_response :bad_request
assert_equal "The parameter bbox is required, and must be of the form min_lon,min_lat,max_lon,max_lat", @response.body, "A bbox param was expected"
def test_bbox_too_big
@badbigbbox.each do |bbox|
- [ "trackpoints", "map" ].each do |tq|
+ %w(trackpoints map).each do |tq|
get tq, :bbox => bbox
assert_response :bad_request, "The bbox:#{bbox} was expected to be too big"
assert_equal "The maximum bbox size is #{MAX_REQUEST_AREA}, and your request was too large. Either request a smaller area, or use planet.osm", @response.body, "bbox: #{bbox}"
def test_bbox_malformed
@badmalformedbbox.each do |bbox|
- [ "trackpoints", "map" ].each do |tq|
+ %w(trackpoints map).each do |tq|
get tq, :bbox => bbox
assert_response :bad_request, "The bbox:#{bbox} was expected to be malformed"
assert_equal "The parameter bbox is required, and must be of the form min_lon,min_lat,max_lon,max_lat", @response.body, "bbox: #{bbox}"
def test_bbox_lon_mixedup
@badlonmixedbbox.each do |bbox|
- [ "trackpoints", "map" ].each do |tq|
+ %w(trackpoints map).each do |tq|
get tq, :bbox => bbox
assert_response :bad_request, "The bbox:#{bbox} was expected to have the longitude mixed up"
assert_equal "The minimum longitude must be less than the maximum longitude, but it wasn't", @response.body, "bbox: #{bbox}"
def test_bbox_lat_mixedup
@badlatmixedbbox.each do |bbox|
- ["trackpoints", "map"].each do |tq|
+ %w(trackpoints map).each do |tq|
get tq, :bbox => bbox
assert_response :bad_request, "The bbox:#{bbox} was expected to have the latitude mixed up"
assert_equal "The minimum latitude must be less than the maximum latitude, but it wasn't", @response.body, "bbox: #{bbox}"
end
# We can't actually get an out of bounds error, as the bbox is sanitised.
- #def test_latlon_outofbounds
+ # def test_latlon_outofbounds
# @badlatlonoutboundsbbox.each do |bbox|
# [ "trackpoints", "map" ].each do |tq|
# get tq, :bbox => bbox
# assert_equal "The latitudes must be between -90 an 90, and longitudes between -180 and 180", @response.body, "bbox: #{bbox}"
# end
# end
- #end
+ # end
# MySQL and Postgres require that the C based functions are installed for
# this test to work. More information is available from:
Timecop.freeze(Time.parse('2010-04-03 10:55:00'))
get :changes
assert_response :success
- #print @response.body
+ # print @response.body
# As we have loaded the fixtures, we can assume that there are no
# changes at the time we have frozen at
now = Time.now.getutc
end
def test_changes_zoom_invalid
- zoom_to_test = %w{ p -1 0 17 one two }
+ zoom_to_test = %w(p -1 0 17 one two)
zoom_to_test.each do |zoom|
get :changes, :zoom => zoom
assert_response :bad_request
end
def test_hours_invalid
- invalid = %w{ -21 335 -1 0 25 26 100 one two three ping pong : }
+ invalid = %w(-21 335 -1 0 25 26 100 one two three ping pong :)
invalid.each do |hour|
get :changes, :hours => hour
assert_response :bad_request, "Problem with the hour: #{hour}"
assert_select ".browse-section.browse-relation", 2
end
-private
+ private
# This is a convenience method for most of the above checks
# First we check that when we don't have an id, it will correctly return a 404
end
assert_raise ActionController::UrlGenerationError do
- get type, {:id => -10} # we won't have an id that's negative
+ get type, :id => -10 # we won't have an id that's negative
end
- get type, {:id => id}
+ get type, :id => id
assert_response :success
assert_template template
assert_template :layout => "map"
- xhr :get, type, {:id => id}
+ xhr :get, type, :id => id
assert_response :success
assert_template template
assert_template :layout => "xhr"
)
assert_routing(
{ :path => "/changeset/1/comments/feed", :method => :get },
- { :controller => "changeset", :action => "comments_feed", :id => "1", :format =>"rss" }
+ { :controller => "changeset", :action => "comments_feed", :id => "1", :format => "rss" }
)
assert_routing(
{ :path => "/user/name/history", :method => :get },
)
assert_routing(
{ :path => "/history/comments/feed", :method => :get },
- { :controller => "changeset", :action => "comments_feed", :format =>"rss" }
+ { :controller => "changeset", :action => "comments_feed", :format => "rss" }
)
end
put :create
assert_require_public_data
-
basic_authorization users(:public_user).email, "test"
# Create the first user's changeset
content "<osm><changeset>" +
# the difference can either be a rational, or a floating point number
# of seconds, depending on the code path taken :-(
if duration.class == Rational
- assert_equal Rational(1,24), duration , "initial idle timeout should be an hour (#{cs.created_at} -> #{cs.closed_at})"
+ assert_equal Rational(1, 24), duration, "initial idle timeout should be an hour (#{cs.created_at} -> #{cs.closed_at})"
else
# must be number of seconds...
assert_equal 3600, duration.round, "initial idle timeout should be an hour (#{cs.created_at} -> #{cs.closed_at})"
put :close, :id => changesets(:public_user_first_change).id
assert_response :unauthorized
-
## Try using the non-public user
basic_authorization users(:normal_user).email, "test"
put :close, :id => changesets(:normal_user_first_change).id
assert_require_public_data
-
## The try with the public user
basic_authorization users(:public_user).email, "test"
content diff
post :upload, :id => changeset_id
assert_response :unauthorized,
- "shouldnn't be able to upload a simple valid diff to changeset: #{@response.body}"
-
-
+ "shouldnn't be able to upload a simple valid diff to changeset: #{@response.body}"
## Now try with a private user
basic_authorization users(:normal_user).email, "test"
content diff
post :upload, :id => changeset_id
assert_response :forbidden,
- "can't upload a simple valid diff to changeset: #{@response.body}"
-
-
+ "can't upload a simple valid diff to changeset: #{@response.body}"
## Now try with the public user
basic_authorization users(:public_user).email, "test"
content diff
post :upload, :id => changeset_id
assert_response :success,
- "can't upload a simple valid diff to changeset: #{@response.body}"
+ "can't upload a simple valid diff to changeset: #{@response.body}"
# check that the changes made it into the database
assert_equal 0, Node.find(1).tags.size, "node 1 should now have no tags"
content diff
post :upload, :id => cs_id
assert_response :success,
- "can't upload a simple valid creation to changeset: #{@response.body}"
+ "can't upload a simple valid creation to changeset: #{@response.body}"
# check the returned payload
assert_select "diffResult[version='#{API_VERSION}'][generator='OpenStreetMap server']", 1
# update the changeset to one that this user owns
changeset_id = changesets(:public_user_first_change).id
- ["node", "way", "relation"].each do |type|
+ %w(node way relation).each do |type|
delete.find("//osmChange/delete/#{type}").each do |n|
n['changeset'] = changeset_id.to_s
end
content diff
post :upload, :id => changeset_id
assert_response :success,
- "can't upload a deletion diff to changeset: #{@response.body}"
+ "can't upload a deletion diff to changeset: #{@response.body}"
# check the response is well-formed
assert_select "diffResult>node", 1
content diff
post :upload, :id => cs.id
assert_response :success,
- "can't upload a deletion diff to changeset: #{@response.body}"
+ "can't upload a deletion diff to changeset: #{@response.body}"
# check the response is well-formed
assert_select "diffResult>node", 1
content diff
post :upload, :id => changeset_id
assert_response :success,
- "can't upload a spatially-large diff to changeset: #{@response.body}"
+ "can't upload a spatially-large diff to changeset: #{@response.body}"
# check that the changeset bbox is within bounds
cs = Changeset.find(changeset_id)
content diff
post :upload, :id => 2
assert_response :precondition_failed,
- "shouldn't be able to upload a invalid deletion diff: #{@response.body}"
+ "shouldn't be able to upload a invalid deletion diff: #{@response.body}"
assert_equal "Precondition failed: Way 3 is still used by relations 1.", @response.body
# check that nothing was, in fact, deleted
content diff
post :upload, :id => 2
assert_response :success,
- "can't do a conditional delete of in use objects: #{@response.body}"
+ "can't do a conditional delete of in use objects: #{@response.body}"
# check the returned payload
assert_select "diffResult[version='#{API_VERSION}'][generator='OpenStreetMap server']", 1
<osmChange>
<create>
<node id='-1' lon='0' lat='0' changeset='#{cs_id}'>
- <tag k='foo' v='#{"x"*256}'/>
+ <tag k='foo' v='#{"x" * 256}'/>
</node>
</create>
</osmChange>
content diff
post :upload, :id => cs_id
assert_response :bad_request,
- "shoudln't be able to upload too long a tag to changeset: #{@response.body}"
-
+ "shoudln't be able to upload too long a tag to changeset: #{@response.body}"
end
##
content diff
post :upload, :id => cs_id
assert_response :success,
- "can't upload a complex diff to changeset: #{@response.body}"
+ "can't upload a complex diff to changeset: #{@response.body}"
# check the returned payload
assert_select "diffResult[version='#{API_VERSION}'][generator='#{GENERATOR}']", 1
# check that the changes made it into the database
assert_equal 2, Node.find(new_node_id).tags.size, "new node should have two tags"
assert_equal [new_node_id, 3], Way.find(1).nds, "way nodes should match"
- Relation.find(1).members.each do |type,id,role|
+ Relation.find(1).members.each do |type, id, _role|
if type == 'node'
assert_equal new_node_id, id, "relation should contain new node"
end
content diff
post :upload, :id => cs_id
assert_response :conflict,
- "uploading a diff with multiple changsets should have failed"
+ "uploading a diff with multiple changsets should have failed"
# check that objects are unmodified
assert_nodes_are_equal(node, Node.find(1))
content diff
post :upload, :id => cs_id
assert_response :success,
- "can't upload multiple versions of an element in a diff: #{@response.body}"
+ "can't upload multiple versions of an element in a diff: #{@response.body}"
# check the response is well-formed. its counter-intuitive, but the
# API will return multiple elements with the same ID and different
content diff
post :upload, :id => cs_id
assert_response :conflict,
- "shouldn't be able to upload the same element twice in a diff: #{@response.body}"
+ "shouldn't be able to upload the same element twice in a diff: #{@response.body}"
end
##
content diff
post :upload, :id => cs_id
assert_response :bad_request,
- "shouldn't be able to upload an element without version: #{@response.body}"
+ "shouldn't be able to upload an element without version: #{@response.body}"
end
##
</ping>
</osmChange>
EOF
- content diff
- post :upload, :id => cs_id
- assert_response :bad_request, "Shouldn't be able to upload a diff with the action ping"
- assert_equal @response.body, "Unknown action ping, choices are create, modify, delete"
+ content diff
+ post :upload, :id => cs_id
+ assert_response :bad_request, "Shouldn't be able to upload a diff with the action ping"
+ assert_equal @response.body, "Unknown action ping, choices are create, modify, delete"
end
##
content diff
post :upload, :id => changeset_id
assert_response :success,
- "can't upload a valid diff with whitespace variations to changeset: #{@response.body}"
+ "can't upload a valid diff with whitespace variations to changeset: #{@response.body}"
# check the response is well-formed
assert_select "diffResult>node", 2
content diff
post :upload, :id => changeset_id
assert_response :success,
- "can't upload a valid diff with re-used placeholders to changeset: #{@response.body}"
+ "can't upload a valid diff with re-used placeholders to changeset: #{@response.body}"
# check the response is well-formed
assert_select "diffResult>node", 3
content diff
post :upload, :id => changeset_id
assert_response :bad_request,
- "shouldn't be able to re-use placeholder IDs"
+ "shouldn't be able to re-use placeholder IDs"
end
##
content diff
post :upload, :id => changeset_id
assert_response :bad_request,
- "shouldn't be able to use invalid placeholder IDs"
+ "shouldn't be able to use invalid placeholder IDs"
assert_equal "Placeholder node not found for reference -4 in way -1", @response.body
# the same again, but this time use an existing way
content diff
post :upload, :id => changeset_id
assert_response :bad_request,
- "shouldn't be able to use invalid placeholder IDs"
+ "shouldn't be able to use invalid placeholder IDs"
assert_equal "Placeholder node not found for reference -4 in way 1", @response.body
end
content diff
post :upload, :id => changeset_id
assert_response :bad_request,
- "shouldn't be able to use invalid placeholder IDs"
+ "shouldn't be able to use invalid placeholder IDs"
assert_equal "Placeholder Node not found for reference -4 in relation -1.", @response.body
# the same again, but this time use an existing way
content diff
post :upload, :id => changeset_id
assert_response :bad_request,
- "shouldn't be able to use invalid placeholder IDs"
+ "shouldn't be able to use invalid placeholder IDs"
assert_equal "Placeholder Way not found for reference -1 in relation 1.", @response.body
end
content diff
post :upload, :id => changeset_id
assert_response :success,
- "diff should have uploaded OK"
+ "diff should have uploaded OK"
# check the bbox
changeset = Changeset.find(changeset_id)
- assert_equal 1*GeoRecord::SCALE, changeset.min_lon, "min_lon should be 1 degree"
- assert_equal 2*GeoRecord::SCALE, changeset.max_lon, "max_lon should be 2 degrees"
- assert_equal 1*GeoRecord::SCALE, changeset.min_lat, "min_lat should be 1 degree"
- assert_equal 2*GeoRecord::SCALE, changeset.max_lat, "max_lat should be 2 degrees"
+ assert_equal 1 * GeoRecord::SCALE, changeset.min_lon, "min_lon should be 1 degree"
+ assert_equal 2 * GeoRecord::SCALE, changeset.max_lon, "max_lon should be 2 degrees"
+ assert_equal 1 * GeoRecord::SCALE, changeset.min_lat, "min_lat should be 1 degree"
+ assert_equal 2 * GeoRecord::SCALE, changeset.max_lat, "max_lat should be 2 degrees"
end
##
content diff
post :upload, :id => changeset_id
assert_response :success,
- "diff should have uploaded OK"
+ "diff should have uploaded OK"
# check the bbox
changeset = Changeset.find(changeset_id)
- assert_equal 1*GeoRecord::SCALE, changeset.min_lon, "min_lon should be 1 degree"
- assert_equal 3*GeoRecord::SCALE, changeset.max_lon, "max_lon should be 3 degrees"
- assert_equal 1*GeoRecord::SCALE, changeset.min_lat, "min_lat should be 1 degree"
- assert_equal 3*GeoRecord::SCALE, changeset.max_lat, "max_lat should be 3 degrees"
+ assert_equal 1 * GeoRecord::SCALE, changeset.min_lon, "min_lon should be 1 degree"
+ assert_equal 3 * GeoRecord::SCALE, changeset.max_lon, "max_lon should be 3 degrees"
+ assert_equal 1 * GeoRecord::SCALE, changeset.min_lat, "min_lat should be 1 degree"
+ assert_equal 3 * GeoRecord::SCALE, changeset.max_lat, "max_lat should be 3 degrees"
end
##
def test_upload_empty_invalid
basic_authorization users(:public_user).email, "test"
- [ "<osmChange/>",
- "<osmChange></osmChange>",
- "<osmChange><modify/></osmChange>",
- "<osmChange><modify></modify></osmChange>"
+ ["<osmChange/>",
+ "<osmChange></osmChange>",
+ "<osmChange><modify/></osmChange>",
+ "<osmChange><modify></modify></osmChange>"
].each do |diff|
# upload it
content diff
error_format "xml"
post :upload, :id => 2
assert_response :success,
- "failed to return error in XML format"
+ "failed to return error in XML format"
# check the returned payload
assert_select "osmError[version='#{API_VERSION}'][generator='OpenStreetMap server']", 1
assert_select "osmError>status", 1
assert_select "osmError>message", 1
-
end
##
put :create
assert_response :forbidden
-
-
## Now try with the public user
basic_authorization(users(:public_user).email, "test")
content diff
post :upload, :id => changeset_id
assert_response :success,
- "can't upload multiple versions of an element in a diff: #{@response.body}"
+ "can't upload multiple versions of an element in a diff: #{@response.body}"
get :download, :id => changeset_id
assert_response :success
content diff
post :upload, :id => changeset_id
assert_response :success,
- "can't upload a diff from JOSM: #{@response.body}"
+ "can't upload a diff from JOSM: #{@response.body}"
get :download, :id => changeset_id
assert_response :success
content diff
post :upload, :id => changeset_id
assert_response :success,
- "can't upload multiple versions of an element in a diff: #{@response.body}"
+ "can't upload multiple versions of an element in a diff: #{@response.body}"
get :download, :id => changeset_id
assert_response :success
get :download, :id => changesets(:normal_user_first_change).id
assert_response :success
assert_template nil
- #print @response.body
+ # print @response.body
# FIXME needs more assert_select tests
assert_select "osmChange[version='#{API_VERSION}'][generator='#{GENERATOR}']" do
assert_select "create", :count => 5
# NOTE: the include method doesn't over-expand, like inserting
# a real method does. this is because we expect the client to
# know what it is doing!
- check_after_include(changeset_id, 1, 1, [ 1, 1, 1, 1])
- check_after_include(changeset_id, 3, 3, [ 1, 1, 3, 3])
- check_after_include(changeset_id, 4, 2, [ 1, 1, 4, 3])
- check_after_include(changeset_id, 2, 2, [ 1, 1, 4, 3])
+ check_after_include(changeset_id, 1, 1, [1, 1, 1, 1])
+ check_after_include(changeset_id, 3, 3, [1, 1, 3, 3])
+ check_after_include(changeset_id, 4, 2, [1, 1, 4, 3])
+ check_after_include(changeset_id, 2, 2, [1, 1, 4, 3])
check_after_include(changeset_id, -1, -1, [-1, -1, 4, 3])
check_after_include(changeset_id, -2, 5, [-2, -1, 4, 5])
end
assert_response :success, "Creating of changeset failed."
changeset_id = @response.body.to_i
- lon=58.2
- lat=-0.45
+ lon = 58.2
+ lat = -0.45
# Try and put
content "<osm><node lon='#{lon}' lat='#{lat}'/></osm>"
# Try to use a hopefully missing changeset
content "<osm><node lon='#{lon}' lat='#{lat}'/></osm>"
- post :expand_bbox, :id => changeset_id+13245
+ post :expand_bbox, :id => changeset_id + 13245
assert_response :not_found, "shouldn't be able to do a bbox expand on a nonexistant changeset"
-
end
##
def test_query
get :query, :bbox => "-10,-10, 10, 10"
assert_response :success, "can't get changesets in bbox"
- assert_changesets [1,4,6]
+ assert_changesets [1, 4, 6]
get :query, :bbox => "4.5,4.5,4.6,4.6"
assert_response :success, "can't get changesets in bbox"
basic_authorization "test@openstreetmap.org", "test"
get :query, :user => users(:normal_user).id
assert_response :success, "can't get changesets by user ID"
- assert_changesets [1,3,6,8]
+ assert_changesets [1, 3, 6, 8]
get :query, :display_name => users(:normal_user).display_name
assert_response :success, "can't get changesets by user name"
- assert_changesets [1,3,6,8]
+ assert_changesets [1, 3, 6, 8]
# check that the correct error is given when we provide both UID and name
get :query, :user => users(:normal_user).id, :display_name => users(:normal_user).display_name
get :query, :time => '2007-12-31'
assert_response :success, "can't get changesets by time-since"
- assert_changesets [1,2,4,5,6]
+ assert_changesets [1, 2, 4, 5, 6]
get :query, :time => '2008-01-01T12:34Z'
assert_response :success, "can't get changesets by time-since with hour"
- assert_changesets [1,2,4,5,6]
+ assert_changesets [1, 2, 4, 5, 6]
get :query, :time => '2007-12-31T23:59Z,2008-01-01T00:01Z'
assert_response :success, "can't get changesets by time-range"
- assert_changesets [1,5,6]
+ assert_changesets [1, 5, 6]
get :query, :open => 'true'
assert_response :success, "can't get changesets by open-ness"
- assert_changesets [1,2,4]
+ assert_changesets [1, 2, 4]
get :query, :closed => 'true'
assert_response :success, "can't get changesets by closed-ness"
- assert_changesets [3,5,6,7,8]
+ assert_changesets [3, 5, 6, 7, 8]
get :query, :closed => 'true', :user => users(:normal_user).id
assert_response :success, "can't get changesets by closed-ness and user"
- assert_changesets [3,6,8]
+ assert_changesets [3, 6, 8]
get :query, :closed => 'true', :user => users(:public_user).id
assert_response :success, "can't get changesets by closed-ness and user"
get :query, :changesets => '1,2,3'
assert_response :success, "can't get changesets by id (as comma-separated string)"
- assert_changesets [1,2,3]
+ assert_changesets [1, 2, 3]
get :query, :changesets => ''
assert_response :bad_request, "should be a bad request since changesets is empty"
# check that errors are returned if garbage is inserted
# into query strings
def test_query_invalid
- [ "abracadabra!",
- "1,2,3,F",
- ";drop table users;"
- ].each do |bbox|
+ ["abracadabra!",
+ "1,2,3,F",
+ ";drop table users;"
+ ].each do |bbox|
get :query, :bbox => bbox
assert_response :bad_request, "'#{bbox}' isn't a bbox"
end
- [ "now()",
- "00-00-00",
- ";drop table users;",
- ",",
- "-,-"
- ].each do |time|
+ ["now()",
+ "00-00-00",
+ ";drop table users;",
+ ",",
+ "-,-"
+ ].each do |time|
get :query, :time => time
assert_response :bad_request, "'#{time}' isn't a valid time range"
end
- [ "me",
- "foobar",
- "-1",
- "0"
- ].each do |uid|
+ ["me",
+ "foobar",
+ "-1",
+ "0"
+ ].each do |uid|
get :query, :user => uid
assert_response :bad_request, "'#{uid}' isn't a valid user ID"
end
put :update, :id => changeset.id
assert_require_public_data "user with their data non-public, shouldn't be able to edit their changeset"
-
## Now try with the public user
changeset = changesets(:public_user_first_change)
new_changeset = changeset.to_xml
offset.times do |i|
node_xml['lat'] = rand.to_s
node_xml['lon'] = rand.to_s
- node_xml['version'] = (i+1).to_s
+ node_xml['version'] = (i + 1).to_s
content node_doc
put :update, :id => node_id
##
# This should display the last 20 changesets closed.
def test_list
- get :list, {:format => "html"}
+ get :list, :format => "html"
assert_response :success
assert_template "history"
assert_template :layout => "map"
assert_select "h2", :text => "Changesets", :count => 1
- get :list, {:format => "html", :list => '1', :bbox => '-180,-90,90,180'}
+ get :list, :format => "html", :list => '1', :bbox => '-180,-90,90,180'
assert_response :success
assert_template "list"
- changesets = Changeset.
- where("num_changes > 0 and min_lon is not null").
- order(:created_at => :desc).
- limit(20)
+ changesets = Changeset
+ .where("num_changes > 0 and min_lon is not null")
+ .order(:created_at => :desc)
+ .limit(20)
assert changesets.size <= 20
# Now check that all 20 (or however many were returned) changesets are in the html
assert_select "li", :count => changesets.size
- changesets.each do |changeset|
+ changesets.each do |_changeset|
# FIXME this test needs rewriting - test for table contents
end
end
##
# This should display the last 20 changesets closed.
def test_list_xhr
- xhr :get, :list, {:format => "html"}
+ xhr :get, :list, :format => "html"
assert_response :success
assert_template "history"
assert_template :layout => "xhr"
assert_select "h2", :text => "Changesets", :count => 1
- get :list, {:format => "html", :list => '1', :bbox => '-180,-90,90,180'}
+ get :list, :format => "html", :list => '1', :bbox => '-180,-90,90,180'
assert_response :success
assert_template "list"
- changesets = Changeset.
- where("num_changes > 0 and min_lon is not null").
- order(:created_at => :desc).
- limit(20)
+ changesets = Changeset
+ .where("num_changes > 0 and min_lon is not null")
+ .order(:created_at => :desc)
+ .limit(20)
assert changesets.size <= 20
# Now check that all 20 (or however many were returned) changesets are in the html
assert_select "li", :count => changesets.size
- changesets.each do |changeset|
+ changesets.each do |_changeset|
# FIXME this test needs rewriting - test for table contents
end
end
# Checks the display of the user changesets listing
def test_list_user
user = users(:public_user)
- get :list, {:format => "html", :display_name => user.display_name}
+ get :list, :format => "html", :display_name => user.display_name
assert_response :success
assert_template "history"
## FIXME need to add more checks to see which if edits are actually shown if your data is public
##
# Check the not found of the list user changesets
def test_list_user_not_found
- get :list, {:format => "html", :display_name => "Some random user"}
+ get :list, :format => "html", :display_name => "Some random user"
assert_response :not_found
assert_template 'user/no_such_user'
end
def test_feed
changesets = Changeset.where("num_changes > 0").order(:created_at => :desc).limit(20)
assert changesets.size <= 20
- get :feed, {:format => "atom"}
+ get :feed, :format => "atom"
assert_response :success
assert_template "list"
# Now check that all 20 (or however many were returned) changesets are in the html
assert_select "feed", :count => 1
assert_select "entry", :count => changesets.size
- changesets.each do |changeset|
+ changesets.each do |_changeset|
# FIXME this test needs rewriting - test for feed contents
end
end
# Checks the display of the user changesets feed
def test_feed_user
user = users(:public_user)
- get :feed, {:format => "atom", :display_name => user.display_name}
+ get :feed, :format => "atom", :display_name => user.display_name
assert_response :success
assert_template "list"
assert_equal "application/atom+xml", response.content_type
##
# Check the not found of the user changesets feed
def test_feed_user_not_found
- get :feed, {:format => "atom", :display_name => "Some random user"}
+ get :feed, :format => "atom", :display_name => "Some random user"
assert_response :not_found
end
basic_authorization(users(:public_user).email, 'test')
assert_difference('ChangesetComment.count') do
- post :comment, { :id => changesets(:normal_user_closed_change).id, :text => 'This is a comment' }
+ post :comment, :id => changesets(:normal_user_closed_change).id, :text => 'This is a comment'
end
assert_response :success
end
# create comment fail
def test_create_comment_fail
# unauthorized
- post :comment, { :id => changesets(:normal_user_closed_change).id, :text => 'This is a comment' }
+ post :comment, :id => changesets(:normal_user_closed_change).id, :text => 'This is a comment'
assert_response :unauthorized
basic_authorization(users(:public_user).email, 'test')
# bad changeset id
assert_no_difference('ChangesetComment.count') do
- post :comment, { :id => 999111, :text => 'This is a comment' }
+ post :comment, :id => 999111, :text => 'This is a comment'
end
assert_response :not_found
# not closed changeset
assert_no_difference('ChangesetComment.count') do
- post :comment, { :id => changesets(:normal_user_first_change).id, :text => 'This is a comment' }
+ post :comment, :id => changesets(:normal_user_first_change).id, :text => 'This is a comment'
end
assert_response :conflict
# no text
assert_no_difference('ChangesetComment.count') do
- post :comment, { :id => changesets(:normal_user_closed_change).id }
+ post :comment, :id => changesets(:normal_user_closed_change).id
end
assert_response :bad_request
# empty text
assert_no_difference('ChangesetComment.count') do
- post :comment, { :id => changesets(:normal_user_closed_change).id, :text => '' }
+ post :comment, :id => changesets(:normal_user_closed_change).id, :text => ''
end
assert_response :bad_request
end
changeset = changesets(:normal_user_closed_change)
assert_difference('changeset.subscribers.count') do
- post :subscribe, { :id => changeset.id }
+ post :subscribe, :id => changeset.id
end
assert_response :success
end
# unauthorized
changeset = changesets(:normal_user_closed_change)
assert_no_difference('changeset.subscribers.count') do
- post :subscribe, { :id => changeset.id }
+ post :subscribe, :id => changeset.id
end
assert_response :unauthorized
# bad changeset id
assert_no_difference('changeset.subscribers.count') do
- post :subscribe, { :id => 999111 }
+ post :subscribe, :id => 999111
end
assert_response :not_found
# not closed changeset
changeset = changesets(:normal_user_first_change)
assert_no_difference('changeset.subscribers.count') do
- post :subscribe, { :id => changeset.id }
+ post :subscribe, :id => changeset.id
end
assert_response :conflict
# trying to subscribe when already subscribed
changeset = changesets(:normal_user_subscribed_change)
assert_no_difference('changeset.subscribers.count') do
- post :subscribe, { :id => changeset.id }
+ post :subscribe, :id => changeset.id
end
assert_response :conflict
end
changeset = changesets(:normal_user_subscribed_change)
assert_difference('changeset.subscribers.count', -1) do
- post :unsubscribe, { :id => changeset.id }
+ post :unsubscribe, :id => changeset.id
end
assert_response :success
end
# unauthorized
changeset = changesets(:normal_user_closed_change)
assert_no_difference('changeset.subscribers.count') do
- post :unsubscribe, { :id => changeset.id }
+ post :unsubscribe, :id => changeset.id
end
assert_response :unauthorized
# bad changeset id
assert_no_difference('changeset.subscribers.count', -1) do
- post :unsubscribe, { :id => 999111 }
+ post :unsubscribe, :id => 999111
end
assert_response :not_found
# not closed changeset
changeset = changesets(:normal_user_first_change)
assert_no_difference('changeset.subscribers.count', -1) do
- post :unsubscribe, { :id => changeset.id }
+ post :unsubscribe, :id => changeset.id
end
assert_response :conflict
# trying to unsubscribe when not subscribed
changeset = changesets(:normal_user_closed_change)
assert_no_difference('changeset.subscribers.count') do
- post :unsubscribe, { :id => changeset.id }
+ post :unsubscribe, :id => changeset.id
end
assert_response :not_found
end
# unauthorized
comment = changeset_comments(:normal_comment_1)
assert('comment.visible') do
- post :hide_comment, { :id => comment.id }
+ post :hide_comment, :id => comment.id
assert_response :unauthorized
end
# not a moderator
assert('comment.visible') do
- post :hide_comment, { :id => comment.id }
+ post :hide_comment, :id => comment.id
assert_response :forbidden
end
basic_authorization(users(:moderator_user).email, 'test')
# bad comment id
- post :hide_comment, { :id => 999111 }
+ post :hide_comment, :id => 999111
assert_response :not_found
end
basic_authorization(users(:moderator_user).email, 'test')
assert('!comment.visible') do
- post :hide_comment, { :id => comment.id }
+ post :hide_comment, :id => comment.id
end
assert_response :success
end
# unauthorized
comment = changeset_comments(:normal_comment_1)
assert('comment.visible') do
- post :unhide_comment, { :id => comment.id }
+ post :unhide_comment, :id => comment.id
assert_response :unauthorized
end
# not a moderator
assert('comment.visible') do
- post :unhide_comment, { :id => comment.id }
+ post :unhide_comment, :id => comment.id
assert_response :forbidden
end
basic_authorization(users(:moderator_user).email, 'test')
# bad comment id
- post :unhide_comment, { :id => 999111 }
+ post :unhide_comment, :id => 999111
assert_response :not_found
end
basic_authorization(users(:moderator_user).email, 'test')
assert('!comment.visible') do
- post :unhide_comment, { :id => comment.id }
+ post :unhide_comment, :id => comment.id
end
assert_response :success
end
##
# test comments feed
def test_comments_feed
- get :comments_feed, {:format => "rss"}
+ get :comments_feed, :format => "rss"
assert_response :success
assert_equal "application/rss+xml", @response.content_type
assert_select "rss", :count => 1 do
end
end
- get :comments_feed, { :id => changesets(:normal_user_closed_change), :format => "rss"}
+ get :comments_feed, :id => changesets(:normal_user_closed_change), :format => "rss"
assert_response :success
assert_equal "application/rss+xml", @response.content_type
assert_select "rss", :count => 1 do
# update an attribute in a way element
def xml_attr_rewrite(xml, name, value)
xml.find("//osm/way").first[name] = value.to_s
- return xml
+ xml
end
end
assert_redirected_to :controller => :user, :action => "login", :referer => "/diary/new"
# Now pretend to login by using the session hash, with the
# id of the person we want to login as through session(:user)=user.id
- get(:new, nil, {'user' => users(:normal_user).id})
+ get(:new, nil, 'user' => users(:normal_user).id)
assert_response :success
- #print @response.body
+ # print @response.body
- #print @response.to_yaml
+ # print @response.to_yaml
assert_select "title", :text => /New Diary Entry/, :count => 1
assert_select "div.content-heading", :count => 1 do
assert_select "h1", :text => "New Diary Entry", :count => 1
assert_redirected_to :controller => :user, :action => "login", :referer => "/user/#{entry.user.display_name}/diary/#{entry.id}/edit"
# Verify that you get a not found error, when you pass a bogus id
- get(:edit, {:display_name => entry.user.display_name, :id => 9999}, {'user' => entry.user.id})
+ get(:edit, { :display_name => entry.user.display_name, :id => 9999 }, { 'user' => entry.user.id })
assert_response :not_found
assert_select "div.content-heading", :count => 1 do
assert_select "h2", :text => "No entry with the id: 9999", :count => 1
# Now pass the id, and check that you can edit it, when using the same
# user as the person who created the entry
- get(:edit, {:display_name => entry.user.display_name, :id => entry.id}, {'user' => entry.user.id})
+ get(:edit, { :display_name => entry.user.display_name, :id => entry.id }, { 'user' => entry.user.id })
assert_response :success
assert_select "title", :text => /Edit diary entry/, :count => 1
assert_select "div.content-heading", :count => 1 do
new_latitude = "1.1"
new_longitude = "2.2"
new_language_code = "en"
- post(:edit, {:display_name => entry.user.display_name, :id => entry.id, 'commit' => 'save',
- 'diary_entry'=>{'title' => new_title, 'body' => new_body, 'latitude' => new_latitude,
- 'longitude' => new_longitude, 'language_code' => new_language_code} },
- {'user' => entry.user.id})
+ post(:edit, { :display_name => entry.user.display_name, :id => entry.id, 'commit' => 'save',
+ 'diary_entry' => { 'title' => new_title, 'body' => new_body, 'latitude' => new_latitude,
+ 'longitude' => new_longitude, 'language_code' => new_language_code } },
+ { 'user' => entry.user.id })
assert_response :redirect
assert_redirected_to :action => :view, :display_name => entry.user.display_name, :id => entry.id
# Now check that the new data is rendered, when logged in
- get :view, {:display_name => entry.user.display_name, :id => entry.id}, {'user' => entry.user.id}
+ get :view, { :display_name => entry.user.display_name, :id => entry.id }, { 'user' => entry.user.id }
assert_response :success
assert_template 'diary_entry/view'
assert_select "title", :text => /Users' diaries | /, :count => 1
assert_select "p", :text => /#{new_body}/, :count => 1
assert_select "abbr[class='geo'][title='#{number_with_precision(new_latitude, :precision => 4)}; #{number_with_precision(new_longitude, :precision => 4)}']", :count => 1
# As we're not logged in, check that you cannot edit
- #print @response.body
+ # print @response.body
assert_select "a[href='/user/#{entry.user.display_name}/diary/#{entry.id}/edit']", :text => "Edit this entry", :count => 1
end
# and when not logged in as the user who wrote the entry
- get :view, {:display_name => entry.user.display_name, :id => entry.id}, {'user' => entry.user.id}
+ get :view, { :display_name => entry.user.display_name, :id => entry.id }, { 'user' => entry.user.id }
assert_response :success
assert_template 'diary_entry/view'
assert_select "title", :text => /Users' diaries | /, :count => 1
end
def test_edit_diary_entry_i18n
- get :edit, {:display_name => users(:normal_user).display_name, :id => diary_entries(:normal_user_entry_1).id}, {'user' => users(:normal_user).id}
+ get :edit, { :display_name => users(:normal_user).display_name, :id => diary_entries(:normal_user_entry_1).id }, { 'user' => users(:normal_user).id }
assert_response :success
assert_select "span[class=translation_missing]", false, "Missing translation in edit diary entry"
end
assert_redirected_to :controller => :user, :action => :login, :referer => "/diary/new"
# Now try again when logged in
- get :new, {}, {:user => users(:normal_user).id}
+ get :new, {}, { :user => users(:normal_user).id }
assert_response :success
assert_select "title", :text => /New Diary Entry/, :count => 1
assert_select "div.content-heading", :count => 1 do
new_longitude = "2.2"
new_language_code = "en"
assert_difference "DiaryEntry.count", 1 do
- post(:new, {'commit' => 'save',
- 'diary_entry'=>{'title' => new_title, 'body' => new_body, 'latitude' => new_latitude,
- 'longitude' => new_longitude, 'language_code' => new_language_code} },
- {:user => users(:normal_user).id})
+ post(:new, { 'commit' => 'save',
+ 'diary_entry' => { 'title' => new_title, 'body' => new_body, 'latitude' => new_latitude,
+ 'longitude' => new_longitude, 'language_code' => new_language_code } },
+ { :user => users(:normal_user).id })
end
assert_response :redirect
assert_redirected_to :action => :list, :display_name => users(:normal_user).display_name
assert_response :forbidden
# Verify that you get a not found error, when you pass a bogus id
- post :comment, {:display_name => entry.user.display_name, :id => 9999}, {:user => users(:public_user).id}
+ post :comment, { :display_name => entry.user.display_name, :id => 9999 }, { :user => users(:public_user).id }
assert_response :not_found
assert_select "div.content-heading", :count => 1 do
assert_select "h2", :text => "No entry with the id: 9999", :count => 1
# Now try again with the right id
assert_difference "ActionMailer::Base.deliveries.size", 1 do
assert_difference "DiaryComment.count", 1 do
- post :comment, {:display_name => entry.user.display_name, :id => entry.id, :diary_comment => {:body => "New comment"}}, {:user => users(:public_user).id}
+ post :comment, { :display_name => entry.user.display_name, :id => entry.id, :diary_comment => { :body => "New comment" } }, { :user => users(:public_user).id }
end
end
assert_response :redirect
assert_redirected_to :action => :view, :display_name => entry.user.display_name, :id => entry.id
email = ActionMailer::Base.deliveries.first
- assert_equal [ users(:normal_user).email ], email.to
+ assert_equal [users(:normal_user).email], email.to
assert_equal "[OpenStreetMap] #{users(:public_user).display_name} commented on your diary entry", email.subject
assert_match /New comment/, email.text_part.decoded
assert_match /New comment/, email.html_part.decoded
# Check that you can get the expected response and template for all available languages
# Should test that there are no <span class="translation_missing">
def test_listing_diary_entries
- get :list
- assert_response :success, "Should be able to list the diary entries in locale"
- assert_template 'list', "Should use the list template in locale"
- assert_select "span[class=translation_missing]", false, "Missing translation in list of diary entries"
-
- # Now try to find a specific user's diary entry
- get :list, {:display_name => users(:normal_user).display_name}
- assert_response :success, "Should be able to list the diary entries for a user in locale"
- assert_template 'list', "Should use the list template for a user in locale"
- assert_no_missing_translations
+ get :list
+ assert_response :success, "Should be able to list the diary entries in locale"
+ assert_template 'list', "Should use the list template in locale"
+ assert_select "span[class=translation_missing]", false, "Missing translation in list of diary entries"
+
+ # Now try to find a specific user's diary entry
+ get :list, :display_name => users(:normal_user).display_name
+ assert_response :success, "Should be able to list the diary entries for a user in locale"
+ assert_template 'list', "Should use the list template for a user in locale"
+ assert_no_missing_translations
end
def test_rss
- get :rss, {:format => :rss}
+ get :rss, :format => :rss
assert_response :success, "Should be able to get a diary RSS"
assert_select "rss", :count => 1 do
assert_select "channel", :count => 1 do
end
def test_rss_language
- get :rss, {:language => diary_entries(:normal_user_entry_1).language_code, :format => :rss}
+ get :rss, :language => diary_entries(:normal_user_entry_1).language_code, :format => :rss
assert_response :success, "Should be able to get a specific language diary RSS"
- assert_select "rss>channel>item", :count => 1 #, "Diary entries should be filtered by language"
+ assert_select "rss>channel>item", :count => 1 # , "Diary entries should be filtered by language"
end
-# def test_rss_nonexisting_language
-# get :rss, {:language => 'xx', :format => :rss}
-# assert_response :not_found, "Should not be able to get a nonexisting language diary RSS"
-# end
+ # def test_rss_nonexisting_language
+ # get :rss, {:language => 'xx', :format => :rss}
+ # assert_response :not_found, "Should not be able to get a nonexisting language diary RSS"
+ # end
def test_rss_language_with_no_entries
- get :rss, {:language => 'sl', :format => :rss}
+ get :rss, :language => 'sl', :format => :rss
assert_response :success, "Should be able to get a specific language diary RSS"
- assert_select "rss>channel>item", :count => 0 #, "Diary entries should be filtered by language"
+ assert_select "rss>channel>item", :count => 0 # , "Diary entries should be filtered by language"
end
def test_rss_user
- get :rss, {:display_name => users(:normal_user).display_name, :format => :rss}
+ get :rss, :display_name => users(:normal_user).display_name, :format => :rss
assert_response :success, "Should be able to get a specific users diary RSS"
- assert_select "rss>channel>item", :count => 2 #, "Diary entries should be filtered by user"
+ assert_select "rss>channel>item", :count => 2 # , "Diary entries should be filtered by user"
end
def test_rss_nonexisting_user
# Try a user that has never existed
- get :rss, {:display_name => 'fakeUsername76543', :format => :rss}
+ get :rss, :display_name => 'fakeUsername76543', :format => :rss
assert_response :not_found, "Should not be able to get a nonexisting users diary RSS"
# Try a suspended user
- get :rss, {:display_name => users(:suspended_user).display_name, :format => :rss}
+ get :rss, :display_name => users(:suspended_user).display_name, :format => :rss
assert_response :not_found, "Should not be able to get a suspended users diary RSS"
# Try a deleted user
- get :rss, {:display_name => users(:deleted_user).display_name, :format => :rss}
+ get :rss, :display_name => users(:deleted_user).display_name, :format => :rss
assert_response :not_found, "Should not be able to get a deleted users diary RSS"
end
def test_viewing_diary_entry
# Try a normal entry that should work
- get :view, {:display_name => users(:normal_user).display_name, :id => diary_entries(:normal_user_entry_1).id}
+ get :view, :display_name => users(:normal_user).display_name, :id => diary_entries(:normal_user_entry_1).id
assert_response :success
assert_template :view
# Try a deleted entry
- get :view, {:display_name => users(:normal_user).display_name, :id => diary_entries(:deleted_entry).id}
+ get :view, :display_name => users(:normal_user).display_name, :id => diary_entries(:deleted_entry).id
assert_response :not_found
# Try an entry by a suspended user
- get :view, {:display_name => users(:suspended_user).display_name, :id => diary_entries(:entry_by_suspended_user).id}
+ get :view, :display_name => users(:suspended_user).display_name, :id => diary_entries(:entry_by_suspended_user).id
assert_response :not_found
# Try an entry by a deleted user
- get :view, {:display_name => users(:deleted_user).display_name, :id => diary_entries(:entry_by_deleted_user).id}
+ get :view, :display_name => users(:deleted_user).display_name, :id => diary_entries(:entry_by_deleted_user).id
assert_response :not_found
end
def test_viewing_hidden_comments
# Get a diary entry that has hidden comments
- get :view, {:display_name => users(:normal_user).display_name, :id => diary_entries(:normal_user_geo_entry).id}
+ get :view, :display_name => users(:normal_user).display_name, :id => diary_entries(:normal_user_geo_entry).id
assert_response :success
assert_template :view
assert_select "div.comments" do
def test_hide
# Try without logging in
- post :hide, {:display_name => users(:normal_user).display_name, :id => diary_entries(:normal_user_entry_1).id}
+ post :hide, :display_name => users(:normal_user).display_name, :id => diary_entries(:normal_user_entry_1).id
assert_response :forbidden
assert_equal true, DiaryEntry.find(diary_entries(:normal_user_entry_1).id).visible
# Now try as a normal user
- post :hide, {:display_name => users(:normal_user).display_name, :id => diary_entries(:normal_user_entry_1).id}, {:user => users(:normal_user).id}
+ post :hide, { :display_name => users(:normal_user).display_name, :id => diary_entries(:normal_user_entry_1).id }, { :user => users(:normal_user).id }
assert_response :redirect
assert_redirected_to :action => :view, :display_name => users(:normal_user).display_name, :id => diary_entries(:normal_user_entry_1).id
assert_equal true, DiaryEntry.find(diary_entries(:normal_user_entry_1).id).visible
# Finally try as an administrator
- post :hide, {:display_name => users(:normal_user).display_name, :id => diary_entries(:normal_user_entry_1).id}, {:user => users(:administrator_user).id}
+ post :hide, { :display_name => users(:normal_user).display_name, :id => diary_entries(:normal_user_entry_1).id }, { :user => users(:administrator_user).id }
assert_response :redirect
assert_redirected_to :action => :list, :display_name => users(:normal_user).display_name
assert_equal false, DiaryEntry.find(diary_entries(:normal_user_entry_1).id).visible
def test_hidecomment
# Try without logging in
- post :hidecomment, {:display_name => users(:normal_user).display_name, :id => diary_entries(:normal_user_geo_entry).id, :comment => diary_comments(:comment_for_geo_post).id}
+ post :hidecomment, :display_name => users(:normal_user).display_name, :id => diary_entries(:normal_user_geo_entry).id, :comment => diary_comments(:comment_for_geo_post).id
assert_response :forbidden
assert_equal true, DiaryComment.find(diary_comments(:comment_for_geo_post).id).visible
# Now try as a normal user
- post :hidecomment, {:display_name => users(:normal_user).display_name, :id => diary_entries(:normal_user_geo_entry).id, :comment => diary_comments(:comment_for_geo_post).id}, {:user => users(:normal_user).id}
+ post :hidecomment, { :display_name => users(:normal_user).display_name, :id => diary_entries(:normal_user_geo_entry).id, :comment => diary_comments(:comment_for_geo_post).id }, { :user => users(:normal_user).id }
assert_response :redirect
assert_redirected_to :action => :view, :display_name => users(:normal_user).display_name, :id => diary_entries(:normal_user_geo_entry).id
assert_equal true, DiaryComment.find(diary_comments(:comment_for_geo_post).id).visible
# Finally try as an administrator
- post :hidecomment, {:display_name => users(:normal_user).display_name, :id => diary_entries(:normal_user_geo_entry).id, :comment => diary_comments(:comment_for_geo_post).id}, {:user => users(:administrator_user).id}
+ post :hidecomment, { :display_name => users(:normal_user).display_name, :id => diary_entries(:normal_user_geo_entry).id, :comment => diary_comments(:comment_for_geo_post).id }, { :user => users(:administrator_user).id }
assert_response :redirect
assert_redirected_to :action => :view, :display_name => users(:normal_user).display_name, :id => diary_entries(:normal_user_geo_entry).id
assert_equal false, DiaryComment.find(diary_comments(:comment_for_geo_post).id).visible
require 'test_helper'
class DirectionsControllerTest < ActionController::TestCase
-
##
# test all routes which lead to this controller
def test_routes
get :search
assert_response :success
end
-
end
require 'test_helper'
class ExportControllerTest < ActionController::TestCase
-
##
# test all routes which lead to this controller
def test_routes
###
# test the finish action for raw OSM data
def test_finish_osm
- get :finish, {:minlon => 0, :minlat => 50, :maxlon => 1, :maxlat => 51, :format => 'osm'}
+ get :finish, :minlon => 0, :minlat => 50, :maxlon => 1, :maxlat => 51, :format => 'osm'
assert_response :redirect
assert_redirected_to "http://api.openstreetmap.org/api/#{API_VERSION}/map?bbox=0.0,50.0,1.0,51.0"
end
###
# test the finish action for mapnik images
def test_finish_mapnik
- get :finish, {:minlon => 0, :minlat => 50, :maxlon => 1, :maxlat => 51, :format => 'mapnik', :mapnik_format => 'test', :mapnik_scale => '12'}
+ get :finish, :minlon => 0, :minlat => 50, :maxlon => 1, :maxlat => 51, :format => 'mapnik', :mapnik_format => 'test', :mapnik_scale => '12'
assert_response :redirect
assert_redirected_to "http://render.openstreetmap.org/cgi-bin/export?bbox=0.0,50.0,1.0,51.0&scale=12&format=test"
end
assert_response :success
assert_template "export/embed"
end
-
end
{ :controller => "geocoder", :action => "search" }
)
assert_routing(
- { :path => "/geocoder/search_latlon", :method => :get },
- { :controller => "geocoder", :action => "search_latlon" }
+ { :path => "/geocoder/search_latlon", :method => :get },
+ { :controller => "geocoder", :action => "search_latlon" }
)
assert_routing(
{ :path => "/geocoder/search_us_postcode", :method => :get },
# Test identification of basic lat/lon pairs
def test_identify_latlon_basic
[
- '50.06773 14.37742',
- '50.06773, 14.37742',
- '+50.06773 +14.37742',
- '+50.06773, +14.37742'
+ '50.06773 14.37742',
+ '50.06773, 14.37742',
+ '+50.06773 +14.37742',
+ '+50.06773, +14.37742'
].each do |code|
latlon_check code, 50.06773, 14.37742
end
# Test identification of lat/lon pairs using N/E with degrees
def test_identify_latlon_ne_d
[
- 'N50.06773 E14.37742',
- 'N50.06773, E14.37742',
- '50.06773N 14.37742E',
- '50.06773N, 14.37742E'
+ 'N50.06773 E14.37742',
+ 'N50.06773, E14.37742',
+ '50.06773N 14.37742E',
+ '50.06773N, 14.37742E'
].each do |code|
latlon_check code, 50.06773, 14.37742
end
# Test identification of lat/lon pairs using N/W with degrees
def test_identify_latlon_nw_d
[
- 'N50.06773 W14.37742',
- 'N50.06773, W14.37742',
- '50.06773N 14.37742W',
- '50.06773N, 14.37742W'
+ 'N50.06773 W14.37742',
+ 'N50.06773, W14.37742',
+ '50.06773N 14.37742W',
+ '50.06773N, 14.37742W'
].each do |code|
latlon_check code, 50.06773, -14.37742
end
# Test identification of lat/lon pairs using S/E with degrees
def test_identify_latlon_se_d
[
- 'S50.06773 E14.37742',
- 'S50.06773, E14.37742',
- '50.06773S 14.37742E',
- '50.06773S, 14.37742E'
+ 'S50.06773 E14.37742',
+ 'S50.06773, E14.37742',
+ '50.06773S 14.37742E',
+ '50.06773S, 14.37742E'
].each do |code|
latlon_check code, -50.06773, 14.37742
end
# Test identification of lat/lon pairs using S/W with degrees
def test_identify_latlon_sw_d
[
- 'S50.06773 W14.37742',
- 'S50.06773, W14.37742',
- '50.06773S 14.37742W',
- '50.06773S, 14.37742W'
+ 'S50.06773 W14.37742',
+ 'S50.06773, W14.37742',
+ '50.06773S 14.37742W',
+ '50.06773S, 14.37742W'
].each do |code|
latlon_check code, -50.06773, -14.37742
end
# Test identification of lat/lon pairs using N/E with degrees/mins
def test_identify_latlon_ne_dm
[
- 'N 50° 04.064 E 014° 22.645',
- "N 50° 04.064' E 014° 22.645",
- "N 50° 04.064', E 014° 22.645'",
- 'N50° 04.064 E14° 22.645',
- 'N 50 04.064 E 014 22.645',
- 'N50 4.064 E14 22.645',
- "50° 04.064' N, 014° 22.645' E"
+ 'N 50° 04.064 E 014° 22.645',
+ "N 50° 04.064' E 014° 22.645",
+ "N 50° 04.064', E 014° 22.645'",
+ 'N50° 04.064 E14° 22.645',
+ 'N 50 04.064 E 014 22.645',
+ 'N50 4.064 E14 22.645',
+ "50° 04.064' N, 014° 22.645' E"
].each do |code|
latlon_check code, 50.06773, 14.37742
end
# Test identification of lat/lon pairs using N/W with degrees/mins
def test_identify_latlon_nw_dm
[
- 'N 50° 04.064 W 014° 22.645',
- "N 50° 04.064' W 014° 22.645",
- "N 50° 04.064', W 014° 22.645'",
- 'N50° 04.064 W14° 22.645',
- 'N 50 04.064 W 014 22.645',
- 'N50 4.064 W14 22.645',
- "50° 04.064' N, 014° 22.645' W"
+ 'N 50° 04.064 W 014° 22.645',
+ "N 50° 04.064' W 014° 22.645",
+ "N 50° 04.064', W 014° 22.645'",
+ 'N50° 04.064 W14° 22.645',
+ 'N 50 04.064 W 014 22.645',
+ 'N50 4.064 W14 22.645',
+ "50° 04.064' N, 014° 22.645' W"
].each do |code|
latlon_check code, 50.06773, -14.37742
end
# Test identification of lat/lon pairs using S/E with degrees/mins
def test_identify_latlon_se_dm
[
- 'S 50° 04.064 E 014° 22.645',
- "S 50° 04.064' E 014° 22.645",
- "S 50° 04.064', E 014° 22.645'",
- 'S50° 04.064 E14° 22.645',
- 'S 50 04.064 E 014 22.645',
- 'S50 4.064 E14 22.645',
- "50° 04.064' S, 014° 22.645' E"
+ 'S 50° 04.064 E 014° 22.645',
+ "S 50° 04.064' E 014° 22.645",
+ "S 50° 04.064', E 014° 22.645'",
+ 'S50° 04.064 E14° 22.645',
+ 'S 50 04.064 E 014 22.645',
+ 'S50 4.064 E14 22.645',
+ "50° 04.064' S, 014° 22.645' E"
].each do |code|
latlon_check code, -50.06773, 14.37742
end
# Test identification of lat/lon pairs using S/W with degrees/mins
def test_identify_latlon_sw_dm
[
- 'S 50° 04.064 W 014° 22.645',
- "S 50° 04.064' W 014° 22.645",
- "S 50° 04.064', W 014° 22.645'",
- 'S50° 04.064 W14° 22.645',
- 'S 50 04.064 W 014 22.645',
- 'S50 4.064 W14 22.645',
- "50° 04.064' S, 014° 22.645' W"
+ 'S 50° 04.064 W 014° 22.645',
+ "S 50° 04.064' W 014° 22.645",
+ "S 50° 04.064', W 014° 22.645'",
+ 'S50° 04.064 W14° 22.645',
+ 'S 50 04.064 W 014 22.645',
+ 'S50 4.064 W14 22.645',
+ "50° 04.064' S, 014° 22.645' W"
].each do |code|
latlon_check code, -50.06773, -14.37742
end
# Test identification of lat/lon pairs using N/E with degrees/mins/secs
def test_identify_latlon_ne_dms
[
- "N 50° 4' 03.828\" E 14° 22' 38.712\"",
- "N 50° 4' 03.828\", E 14° 22' 38.712\"",
- "N 50° 4′ 03.828″, E 14° 22′ 38.712″",
- 'N50 4 03.828 E14 22 38.712',
- 'N50 4 03.828, E14 22 38.712',
- "50°4'3.828\"N 14°22'38.712\"E"
+ "N 50° 4' 03.828\" E 14° 22' 38.712\"",
+ "N 50° 4' 03.828\", E 14° 22' 38.712\"",
+ "N 50° 4′ 03.828″, E 14° 22′ 38.712″",
+ 'N50 4 03.828 E14 22 38.712',
+ 'N50 4 03.828, E14 22 38.712',
+ "50°4'3.828\"N 14°22'38.712\"E"
].each do |code|
latlon_check code, 50.06773, 14.37742
end
# Test identification of lat/lon pairs using N/W with degrees/mins/secs
def test_identify_latlon_nw_dms
[
- "N 50° 4' 03.828\" W 14° 22' 38.712\"",
- "N 50° 4' 03.828\", W 14° 22' 38.712\"",
- "N 50° 4′ 03.828″, W 14° 22′ 38.712″",
- 'N50 4 03.828 W14 22 38.712',
- 'N50 4 03.828, W14 22 38.712',
- "50°4'3.828\"N 14°22'38.712\"W"
+ "N 50° 4' 03.828\" W 14° 22' 38.712\"",
+ "N 50° 4' 03.828\", W 14° 22' 38.712\"",
+ "N 50° 4′ 03.828″, W 14° 22′ 38.712″",
+ 'N50 4 03.828 W14 22 38.712',
+ 'N50 4 03.828, W14 22 38.712',
+ "50°4'3.828\"N 14°22'38.712\"W"
].each do |code|
latlon_check code, 50.06773, -14.37742
end
# Test identification of lat/lon pairs using S/E with degrees/mins/secs
def test_identify_latlon_se_dms
[
- "S 50° 4' 03.828\" E 14° 22' 38.712\"",
- "S 50° 4' 03.828\", E 14° 22' 38.712\"",
- "S 50° 4′ 03.828″, E 14° 22′ 38.712″",
- 'S50 4 03.828 E14 22 38.712',
- 'S50 4 03.828, E14 22 38.712',
- "50°4'3.828\"S 14°22'38.712\"E"
+ "S 50° 4' 03.828\" E 14° 22' 38.712\"",
+ "S 50° 4' 03.828\", E 14° 22' 38.712\"",
+ "S 50° 4′ 03.828″, E 14° 22′ 38.712″",
+ 'S50 4 03.828 E14 22 38.712',
+ 'S50 4 03.828, E14 22 38.712',
+ "50°4'3.828\"S 14°22'38.712\"E"
].each do |code|
latlon_check code, -50.06773, 14.37742
end
# Test identification of lat/lon pairs using S/W with degrees/mins/secs
def test_identify_latlon_sw_dms
[
- "S 50° 4' 03.828\" W 14° 22' 38.712\"",
- "S 50° 4' 03.828\", W 14° 22' 38.712\"",
- "S 50° 4′ 03.828″, W 14° 22′ 38.712″",
- 'S50 4 03.828 W14 22 38.712',
- 'S50 4 03.828, W14 22 38.712',
- "50°4'3.828\"S 14°22'38.712\"W"
+ "S 50° 4' 03.828\" W 14° 22' 38.712\"",
+ "S 50° 4' 03.828\", W 14° 22' 38.712\"",
+ "S 50° 4′ 03.828″, W 14° 22′ 38.712″",
+ 'S50 4 03.828 W14 22 38.712',
+ 'S50 4 03.828, W14 22 38.712',
+ "50°4'3.828\"S 14°22'38.712\"W"
].each do |code|
latlon_check code, -50.06773, -14.37742
end
# Test identification of US zipcodes
def test_identify_us_postcode
[
- '12345',
- '12345-6789'
+ '12345',
+ '12345-6789'
].each do |code|
post :search, query: code
assert_response :success
- assert_equal ['us_postcode', 'osm_nominatim'], assigns(:sources)
+ assert_equal %w(us_postcode osm_nominatim), assigns(:sources)
end
end
# http://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom
def test_identify_uk_postcode
[
- 'EC1A 1BB',
- 'W1A 1HQ',
- 'M1 1AA',
- 'B33 8TH',
- 'CR2 6XH',
- 'DN55 1PT'
+ 'EC1A 1BB',
+ 'W1A 1HQ',
+ 'M1 1AA',
+ 'B33 8TH',
+ 'CR2 6XH',
+ 'DN55 1PT'
].each do |code|
- search_check code, ['uk_postcode', 'osm_nominatim']
+ search_check code, %w(uk_postcode osm_nominatim)
end
end
##
# Test identification of Canadian postcodes
def test_identify_ca_postcode
- search_check 'A1B 2C3', ['ca_postcode', 'osm_nominatim']
+ search_check 'A1B 2C3', %w(ca_postcode osm_nominatim)
end
##
search_check 'foo bar baz', ['osm_nominatim']
end
-private
+ private
+
def latlon_check(query, lat, lon)
post :search, :query => query
assert_response :success
assert_template "search"
assert_template :layout => "map"
- assert_equal ['latlon' ,'osm_nominatim_reverse'], assigns(:sources)
+ assert_equal %w(latlon osm_nominatim_reverse), assigns(:sources)
assert_nil @controller.params[:query]
assert_in_delta lat, @controller.params[:lat]
assert_in_delta lon, @controller.params[:lon]
assert_response :success
assert_template "search"
assert_template :layout => "xhr"
- assert_equal ['latlon' ,'osm_nominatim_reverse'], assigns(:sources)
+ assert_equal %w(latlon osm_nominatim_reverse), assigns(:sources)
assert_nil @controller.params[:query]
assert_in_delta lat, @controller.params[:lat]
assert_in_delta lon, @controller.params[:lon]
assert_difference "ActionMailer::Base.deliveries.size", 0 do
assert_difference "Message.count", 0 do
post :new,
- :display_name => users(:public_user).display_name,
- :message => { :title => "Test Message", :body => "" }
+ :display_name => users(:public_user).display_name,
+ :message => { :title => "Test Message", :body => "" }
end
end
assert_response :success
assert_difference "ActionMailer::Base.deliveries.size", 0 do
assert_difference "Message.count", 0 do
post :new,
- :display_name => users(:public_user).display_name,
- :message => { :title => "", :body => "Test message body" }
+ :display_name => users(:public_user).display_name,
+ :message => { :title => "", :body => "Test message body" }
end
end
assert_response :success
assert_difference "ActionMailer::Base.deliveries.size", 1 do
assert_difference "Message.count", 1 do
post :new,
- :display_name => users(:public_user).display_name,
- :message => { :title => "Test Message", :body => "Test message body" }
+ :display_name => users(:public_user).display_name,
+ :message => { :title => "Test Message", :body => "Test message body" }
end
end
assert_redirected_to inbox_path(:display_name => users(:normal_user).display_name)
assert_equal "Message sent", flash[:notice]
e = ActionMailer::Base.deliveries.first
- assert_equal [ users(:public_user).email ], e.to
+ assert_equal [users(:public_user).email], e.to
assert_equal "[OpenStreetMap] Test Message", e.subject
assert_match /Test message body/, e.text_part.decoded
assert_match /Test message body/, e.html_part.decoded
assert_no_difference "Message.count" do
with_message_limit(0) do
post :new,
- :display_name => users(:public_user).display_name,
- :message => { :title => "Test Message", :body => "Test message body" }
+ :display_name => users(:public_user).display_name,
+ :message => { :title => "Test Message", :body => "Test message body" }
assert_response :success
assert_template "new"
assert_select ".error", /wait a while/
assert_template "no_such_message"
end
-private
+ private
def with_message_limit(value)
max_messages_per_hour = Object.send("remove_const", "MAX_MESSAGES_PER_HOUR")
## First try with no auth
# create a node with random lat/lon
- lat = rand(100)-50 + rand
- lon = rand(100)-50 + rand
+ lat = rand(100) - 50 + rand
+ lon = rand(100) - 50 + rand
# normal user has a changeset open, so we'll use that.
changeset = changesets(:normal_user_first_change)
# create a minimal xml file
# hope for unauthorized
assert_response :unauthorized, "node upload did not return unauthorized status"
-
-
## Now try with the user which doesn't have their data public
basic_authorization(users(:normal_user).email, "test")
# create a node with random lat/lon
- lat = rand(100)-50 + rand
- lon = rand(100)-50 + rand
+ lat = rand(100) - 50 + rand
+ lon = rand(100) - 50 + rand
# normal user has a changeset open, so we'll use that.
changeset = changesets(:normal_user_first_change)
# create a minimal xml file
# hope for success
assert_require_public_data "node create did not return forbidden status"
-
-
## Now try with the user that has the public data
basic_authorization(users(:public_user).email, "test")
# create a node with random lat/lon
- lat = rand(100)-50 + rand
- lon = rand(100)-50 + rand
+ lat = rand(100) - 50 + rand
+ lon = rand(100) - 50 + rand
# normal user has a changeset open, so we'll use that.
changeset = changesets(:public_user_first_change)
# create a minimal xml file
assert_equal "Cannot parse valid node from xml string <node lat=\"#{lat}\" lon=\"abc\" changeset=\"#{changeset.id}\"/>. lon not a number", @response.body
# test that the upload is rejected when we have a tag which is too long
- content("<osm><node lat='#{lat}' lon='#{lon}' changeset='#{changeset.id}'><tag k='foo' v='#{'x'*256}'/></node></osm>")
+ content("<osm><node lat='#{lat}' lon='#{lon}' changeset='#{changeset.id}'><tag k='foo' v='#{'x' * 256}'/></node></osm>")
put :create
assert_response :bad_request, "node upload did not return bad_request status"
- assert_equal ["NodeTag ", " v: is too long (maximum is 255 characters) (\"#{'x'*256}\")"], @response.body.split(/[0-9]+,foo:/)
-
+ assert_equal ["NodeTag ", " v: is too long (maximum is 255 characters) (\"#{'x' * 256}\")"], @response.body.split(/[0-9]+,foo:/)
end
def test_read
delete :delete, :id => current_nodes(:visible_node).id
assert_response :unauthorized
-
## now set auth for the non-data public user
- basic_authorization(users(:normal_user).email, "test");
+ basic_authorization(users(:normal_user).email, "test")
# try to delete with an invalid (closed) changeset
content update_changeset(current_nodes(:visible_node).to_xml,
assert_require_public_data("non-public user shouldn't be able to delete node")
# try to delete with an invalid (non-existent) changeset
- content update_changeset(current_nodes(:visible_node).to_xml,0)
+ content update_changeset(current_nodes(:visible_node).to_xml, 0)
delete :delete, :id => current_nodes(:visible_node).id
assert_require_public_data("shouldn't be able to delete node, when user's data is private")
content(nodes(:used_node_1).to_xml)
delete :delete, :id => current_nodes(:used_node_1).id
assert_require_public_data
- "shouldn't be able to delete a node used in a way (#{@response.body})"
+ "shouldn't be able to delete a node used in a way (#{@response.body})"
# in a relation...
content(nodes(:node_used_by_relationship).to_xml)
delete :delete, :id => current_nodes(:node_used_by_relationship).id
assert_require_public_data
- "shouldn't be able to delete a node used in a relation (#{@response.body})"
-
-
+ "shouldn't be able to delete a node used in a relation (#{@response.body})"
## now set auth for the public data user
- basic_authorization(users(:public_user).email, "test");
+ basic_authorization(users(:public_user).email, "test")
# try to delete with an invalid (closed) changeset
content update_changeset(current_nodes(:visible_node).to_xml,
assert_response :conflict
# try to delete with an invalid (non-existent) changeset
- content update_changeset(current_nodes(:visible_node).to_xml,0)
+ content update_changeset(current_nodes(:visible_node).to_xml, 0)
delete :delete, :id => current_nodes(:visible_node).id
assert_response :conflict
content(nodes(:public_visible_node).to_xml)
delete :delete, :id => current_nodes(:visible_node).id
assert_response :bad_request,
- "should not be able to delete a node with a different ID from the XML"
+ "should not be able to delete a node with a different ID from the XML"
# try to delete a node rubbish in the payloads
content("<delete/>")
delete :delete, :id => current_nodes(:visible_node).id
assert_response :bad_request,
- "should not be able to delete a node without a valid XML payload"
+ "should not be able to delete a node without a valid XML payload"
# valid delete now takes a payload
content(nodes(:public_visible_node).to_xml)
# valid delete should return the new version number, which should
# be greater than the old version number
assert @response.body.to_i > current_nodes(:public_visible_node).version,
- "delete request should return a new version number for node"
+ "delete request should return a new version number for node"
# deleting the same node twice doesn't work
content(nodes(:public_visible_node).to_xml)
content(nodes(:used_node_1).to_xml)
delete :delete, :id => current_nodes(:used_node_1).id
assert_response :precondition_failed,
- "shouldn't be able to delete a node used in a way (#{@response.body})"
+ "shouldn't be able to delete a node used in a way (#{@response.body})"
assert_equal "Precondition failed: Node 3 is still used by ways 1,3.", @response.body
# in a relation...
content(nodes(:node_used_by_relationship).to_xml)
delete :delete, :id => current_nodes(:node_used_by_relationship).id
assert_response :precondition_failed,
- "shouldn't be able to delete a node used in a relation (#{@response.body})"
+ "shouldn't be able to delete a node used in a relation (#{@response.body})"
assert_equal "Precondition failed: Node 5 is still used by relations 1,3.", @response.body
end
put :update, :id => current_nodes(:visible_node).id
assert_response :unauthorized
-
-
## Second test with the private user
# setup auth
assert_require_public_data("update with changeset=0 should be forbidden, when data isn't public")
## try and submit invalid updates
- content xml_attr_rewrite(current_nodes(:visible_node).to_xml, 'lat', 91.0);
+ content xml_attr_rewrite(current_nodes(:visible_node).to_xml, 'lat', 91.0)
put :update, :id => current_nodes(:visible_node).id
assert_require_public_data "node at lat=91 should be forbidden, when data isn't public"
- content xml_attr_rewrite(current_nodes(:visible_node).to_xml, 'lat', -91.0);
+ content xml_attr_rewrite(current_nodes(:visible_node).to_xml, 'lat', -91.0)
put :update, :id => current_nodes(:visible_node).id
assert_require_public_data "node at lat=-91 should be forbidden, when data isn't public"
- content xml_attr_rewrite(current_nodes(:visible_node).to_xml, 'lon', 181.0);
+ content xml_attr_rewrite(current_nodes(:visible_node).to_xml, 'lon', 181.0)
put :update, :id => current_nodes(:visible_node).id
assert_require_public_data "node at lon=181 should be forbidden, when data isn't public"
- content xml_attr_rewrite(current_nodes(:visible_node).to_xml, 'lon', -181.0);
+ content xml_attr_rewrite(current_nodes(:visible_node).to_xml, 'lon', -181.0)
put :update, :id => current_nodes(:visible_node).id
assert_require_public_data "node at lon=-181 should be forbidden, when data isn't public"
# try and update in someone else's changeset
content update_changeset(current_nodes(:visible_node).to_xml,
- changesets(:normal_user_first_change).id)
+ changesets(:normal_user_first_change).id)
put :update, :id => current_nodes(:visible_node).id
assert_response :conflict, "update with other user's changeset should be rejected"
assert_response :conflict, "update with changeset=0 should be rejected"
## try and submit invalid updates
- content xml_attr_rewrite(current_nodes(:visible_node).to_xml, 'lat', 91.0);
+ content xml_attr_rewrite(current_nodes(:visible_node).to_xml, 'lat', 91.0)
put :update, :id => current_nodes(:visible_node).id
assert_response :bad_request, "node at lat=91 should be rejected"
- content xml_attr_rewrite(current_nodes(:visible_node).to_xml, 'lat', -91.0);
+ content xml_attr_rewrite(current_nodes(:visible_node).to_xml, 'lat', -91.0)
put :update, :id => current_nodes(:visible_node).id
assert_response :bad_request, "node at lat=-91 should be rejected"
- content xml_attr_rewrite(current_nodes(:visible_node).to_xml, 'lon', 181.0);
+ content xml_attr_rewrite(current_nodes(:visible_node).to_xml, 'lon', 181.0)
put :update, :id => current_nodes(:visible_node).id
assert_response :bad_request, "node at lon=181 should be rejected"
- content xml_attr_rewrite(current_nodes(:visible_node).to_xml, 'lon', -181.0);
+ content xml_attr_rewrite(current_nodes(:visible_node).to_xml, 'lon', -181.0)
put :update, :id => current_nodes(:visible_node).id
assert_response :bad_request, "node at lon=-181 should be rejected"
# try and submit a version behind
content xml_attr_rewrite(current_nodes(:visible_node).to_xml,
- 'version', current_node_version - 1);
+ 'version', current_node_version - 1)
put :update, :id => current_nodes(:visible_node).id
assert_response :conflict, "should have failed on old version number"
# try and submit a version ahead
content xml_attr_rewrite(current_nodes(:visible_node).to_xml,
- 'version', current_node_version + 1);
+ 'version', current_node_version + 1)
put :update, :id => current_nodes(:visible_node).id
assert_response :conflict, "should have failed on skipped version number"
# try and submit total crap in the version field
content xml_attr_rewrite(current_nodes(:visible_node).to_xml,
- 'version', 'p1r4t3s!');
+ 'version', 'p1r4t3s!')
put :update, :id => current_nodes(:visible_node).id
assert_response :conflict,
- "should not be able to put 'p1r4at3s!' in the version field"
+ "should not be able to put 'p1r4at3s!' in the version field"
## try an update with the wrong ID
content current_nodes(:public_visible_node).to_xml
put :update, :id => current_nodes(:visible_node).id
assert_response :bad_request,
- "should not be able to update a node with a different ID from the XML"
+ "should not be able to update a node with a different ID from the XML"
## try an update with a minimal valid XML doc which isn't a well-formed OSM doc.
content "<update/>"
put :update, :id => current_nodes(:visible_node).id
assert_response :bad_request,
- "should not be able to update a node with non-OSM XML doc."
+ "should not be able to update a node with non-OSM XML doc."
## finally, produce a good request which should work
content current_nodes(:public_visible_node).to_xml
content node_xml
put :update, :id => current_nodes(:public_visible_node).id
assert_response :bad_request,
- "adding duplicate tags to a node should fail with 'bad request'"
+ "adding duplicate tags to a node should fail with 'bad request'"
assert_equal "Element node/#{current_nodes(:public_visible_node).id} has duplicate tags with key #{current_node_tags(:t1).k}", @response.body
end
put :create
assert_require_public_data "Shouldn't be able to create with non-public user"
-
## Then try with the public data user
basic_authorization(users(:public_user).email, "test")
changeset_id = changesets(:public_user_first_change).id
# update an attribute in the node element
def xml_attr_rewrite(xml, name, value)
xml.find("//osm/node").first[name] = value.to_s
- return xml
+ xml
end
##
def test_create_success
assert_difference('Note.count') do
assert_difference('NoteComment.count') do
- post :create, {:lat => -1.0, :lon => -1.0, :text => "This is a comment", :format => "json"}
+ post :create, :lat => -1.0, :lon => -1.0, :text => "This is a comment", :format => "json"
end
end
assert_response :success
assert_nil js["properties"]["comments"].last["user"]
id = js["properties"]["id"]
- get :show, {:id => id, :format => "json"}
+ get :show, :id => id, :format => "json"
assert_response :success
js = ActiveSupport::JSON.decode(@response.body)
assert_not_nil js
def test_create_fail
assert_no_difference('Note.count') do
assert_no_difference('NoteComment.count') do
- post :create, {:lon => -1.0, :text => "This is a comment"}
+ post :create, :lon => -1.0, :text => "This is a comment"
end
end
assert_response :bad_request
assert_no_difference('Note.count') do
assert_no_difference('NoteComment.count') do
- post :create, {:lat => -1.0, :text => "This is a comment"}
+ post :create, :lat => -1.0, :text => "This is a comment"
end
end
assert_response :bad_request
assert_no_difference('Note.count') do
assert_no_difference('NoteComment.count') do
- post :create, {:lat => -1.0, :lon => -1.0}
+ post :create, :lat => -1.0, :lon => -1.0
end
end
assert_response :bad_request
assert_no_difference('Note.count') do
assert_no_difference('NoteComment.count') do
- post :create, {:lat => -1.0, :lon => -1.0, :text => ""}
+ post :create, :lat => -1.0, :lon => -1.0, :text => ""
end
end
assert_response :bad_request
assert_no_difference('Note.count') do
assert_no_difference('NoteComment.count') do
- post :create, {:lat => -100.0, :lon => -1.0, :text => "This is a comment"}
+ post :create, :lat => -100.0, :lon => -1.0, :text => "This is a comment"
end
end
assert_response :bad_request
assert_no_difference('Note.count') do
assert_no_difference('NoteComment.count') do
- post :create, {:lat => -1.0, :lon => -200.0, :text => "This is a comment"}
+ post :create, :lat => -1.0, :lon => -200.0, :text => "This is a comment"
end
end
assert_response :bad_request
assert_no_difference('Note.count') do
assert_no_difference('NoteComment.count') do
- post :create, {:lat => 'abc', :lon => -1.0, :text => "This is a comment"}
+ post :create, :lat => 'abc', :lon => -1.0, :text => "This is a comment"
end
end
assert_response :bad_request
assert_no_difference('Note.count') do
assert_no_difference('NoteComment.count') do
- post :create, {:lat => -1.0, :lon => 'abc', :text => "This is a comment"}
+ post :create, :lat => -1.0, :lon => 'abc', :text => "This is a comment"
end
end
assert_response :bad_request
def test_comment_success
assert_difference('NoteComment.count') do
- post :comment, {:id => notes(:open_note_with_comment).id, :text => "This is an additional comment", :format => "json"}
+ post :comment, :id => notes(:open_note_with_comment).id, :text => "This is an additional comment", :format => "json"
end
assert_response :success
js = ActiveSupport::JSON.decode(@response.body)
assert_equal "This is an additional comment", js["properties"]["comments"].last["text"]
assert_nil js["properties"]["comments"].last["user"]
- get :show, {:id => notes(:open_note_with_comment).id, :format => "json"}
+ get :show, :id => notes(:open_note_with_comment).id, :format => "json"
assert_response :success
js = ActiveSupport::JSON.decode(@response.body)
assert_not_nil js
def test_comment_fail
assert_no_difference('NoteComment.count') do
- post :comment, {:text => "This is an additional comment"}
+ post :comment, :text => "This is an additional comment"
end
assert_response :bad_request
assert_no_difference('NoteComment.count') do
- post :comment, {:id => notes(:open_note_with_comment).id}
+ post :comment, :id => notes(:open_note_with_comment).id
end
assert_response :bad_request
assert_no_difference('NoteComment.count') do
- post :comment, {:id => notes(:open_note_with_comment).id, :text => ""}
+ post :comment, :id => notes(:open_note_with_comment).id, :text => ""
end
assert_response :bad_request
assert_no_difference('NoteComment.count') do
- post :comment, {:id => 12345, :text => "This is an additional comment"}
+ post :comment, :id => 12345, :text => "This is an additional comment"
end
assert_response :not_found
assert_no_difference('NoteComment.count') do
- post :comment, {:id => notes(:hidden_note_with_comment).id, :text => "This is an additional comment"}
+ post :comment, :id => notes(:hidden_note_with_comment).id, :text => "This is an additional comment"
end
assert_response :gone
assert_no_difference('NoteComment.count') do
- post :comment, {:id => notes(:closed_note_with_comment).id, :text => "This is an additional comment"}
+ post :comment, :id => notes(:closed_note_with_comment).id, :text => "This is an additional comment"
end
assert_response :conflict
end
def test_close_success
- post :close, {:id => notes(:open_note_with_comment).id, :text => "This is a close comment", :format => "json"}
+ post :close, :id => notes(:open_note_with_comment).id, :text => "This is a close comment", :format => "json"
assert_response :unauthorized
basic_authorization(users(:public_user).email, "test")
- post :close, {:id => notes(:open_note_with_comment).id, :text => "This is a close comment", :format => "json"}
+ post :close, :id => notes(:open_note_with_comment).id, :text => "This is a close comment", :format => "json"
assert_response :success
js = ActiveSupport::JSON.decode(@response.body)
assert_not_nil js
assert_equal "This is a close comment", js["properties"]["comments"].last["text"]
assert_equal "test2", js["properties"]["comments"].last["user"]
- get :show, {:id => notes(:open_note_with_comment).id, :format => "json"}
+ get :show, :id => notes(:open_note_with_comment).id, :format => "json"
assert_response :success
js = ActiveSupport::JSON.decode(@response.body)
assert_not_nil js
post :close
assert_response :bad_request
- post :close, {:id => 12345}
+ post :close, :id => 12345
assert_response :not_found
- post :close, {:id => notes(:hidden_note_with_comment).id}
+ post :close, :id => notes(:hidden_note_with_comment).id
assert_response :gone
- post :close, {:id => notes(:closed_note_with_comment).id}
+ post :close, :id => notes(:closed_note_with_comment).id
assert_response :conflict
end
def test_reopen_success
- post :reopen, {:id => notes(:closed_note_with_comment).id, :text => "This is a reopen comment", :format => "json"}
+ post :reopen, :id => notes(:closed_note_with_comment).id, :text => "This is a reopen comment", :format => "json"
assert_response :unauthorized
basic_authorization(users(:public_user).email, "test")
- post :reopen, {:id => notes(:closed_note_with_comment).id, :text => "This is a reopen comment", :format => "json"}
+ post :reopen, :id => notes(:closed_note_with_comment).id, :text => "This is a reopen comment", :format => "json"
assert_response :success
js = ActiveSupport::JSON.decode(@response.body)
assert_not_nil js
assert_equal "This is a reopen comment", js["properties"]["comments"].last["text"]
assert_equal "test2", js["properties"]["comments"].last["user"]
- get :show, {:id => notes(:closed_note_with_comment).id, :format => "json"}
+ get :show, :id => notes(:closed_note_with_comment).id, :format => "json"
assert_response :success
js = ActiveSupport::JSON.decode(@response.body)
assert_not_nil js
end
def test_reopen_fail
- post :reopen, {:id => notes(:hidden_note_with_comment).id}
+ post :reopen, :id => notes(:hidden_note_with_comment).id
assert_response :unauthorized
basic_authorization(users(:public_user).email, "test")
- post :reopen, {:id => 12345}
+ post :reopen, :id => 12345
assert_response :not_found
- post :reopen, {:id => notes(:hidden_note_with_comment).id}
+ post :reopen, :id => notes(:hidden_note_with_comment).id
assert_response :gone
- post :reopen, {:id => notes(:open_note_with_comment).id}
+ post :reopen, :id => notes(:open_note_with_comment).id
assert_response :conflict
end
def test_show_success
- get :show, {:id => notes(:open_note).id, :format => "xml"}
+ get :show, :id => notes(:open_note).id, :format => "xml"
assert_response :success
assert_equal "application/xml", @response.content_type
assert_select "osm", :count => 1 do
end
end
- get :show, {:id => notes(:open_note).id, :format => "rss"}
+ get :show, :id => notes(:open_note).id, :format => "rss"
assert_response :success
assert_equal "application/rss+xml", @response.content_type
assert_select "rss", :count => 1 do
assert_select "link", browse_note_url(notes(:open_note))
assert_select "guid", note_url(notes(:open_note))
assert_select "pubDate", notes(:open_note).created_at.to_s(:rfc822)
-# assert_select "geo:lat", notes(:open_note).lat.to_s
-# assert_select "geo:long", notes(:open_note).lon
-# assert_select "georss:point", "#{notes(:open_note).lon} #{notes(:open_note).lon}"
+ # assert_select "geo:lat", notes(:open_note).lat.to_s
+ # assert_select "geo:long", notes(:open_note).lon
+ # assert_select "georss:point", "#{notes(:open_note).lon} #{notes(:open_note).lon}"
end
end
end
- get :show, {:id => notes(:open_note).id, :format => "json"}
+ get :show, :id => notes(:open_note).id, :format => "json"
assert_response :success
assert_equal "application/json", @response.content_type
js = ActiveSupport::JSON.decode(@response.body)
assert_equal notes(:open_note).created_at, js["properties"]["date_created"]
assert_equal notes(:open_note).status, js["properties"]["status"]
- get :show, {:id => notes(:open_note).id, :format => "gpx"}
+ get :show, :id => notes(:open_note).id, :format => "gpx"
assert_response :success
assert_equal "application/gpx+xml", @response.content_type
assert_select "gpx", :count => 1 do
end
def test_show_hidden_comment
- get :show, {:id => notes(:note_with_hidden_comment).id, :format => "json"}
+ get :show, :id => notes(:note_with_hidden_comment).id, :format => "json"
assert_response :success
js = ActiveSupport::JSON.decode(@response.body)
assert_not_nil js
end
def test_show_fail
- get :show, {:id => 12345}
+ get :show, :id => 12345
assert_response :not_found
- get :show, {:id => notes(:hidden_note_with_comment).id}
+ get :show, :id => notes(:hidden_note_with_comment).id
assert_response :gone
end
def test_destroy_success
- delete :destroy, {:id => notes(:open_note_with_comment).id, :text => "This is a hide comment", :format => "json"}
+ delete :destroy, :id => notes(:open_note_with_comment).id, :text => "This is a hide comment", :format => "json"
assert_response :unauthorized
basic_authorization(users(:public_user).email, "test")
- delete :destroy, {:id => notes(:open_note_with_comment).id, :text => "This is a hide comment", :format => "json"}
+ delete :destroy, :id => notes(:open_note_with_comment).id, :text => "This is a hide comment", :format => "json"
assert_response :forbidden
basic_authorization(users(:moderator_user).email, "test")
- delete :destroy, {:id => notes(:open_note_with_comment).id, :text => "This is a hide comment", :format => "json"}
+ delete :destroy, :id => notes(:open_note_with_comment).id, :text => "This is a hide comment", :format => "json"
assert_response :success
js = ActiveSupport::JSON.decode(@response.body)
assert_not_nil js
assert_equal "This is a hide comment", js["properties"]["comments"].last["text"]
assert_equal "moderator", js["properties"]["comments"].last["user"]
- get :show, {:id => notes(:open_note_with_comment).id, :format => 'json'}
+ get :show, :id => notes(:open_note_with_comment).id, :format => 'json'
assert_response :gone
end
def test_destroy_fail
- delete :destroy, {:id => 12345, :format => "json"}
+ delete :destroy, :id => 12345, :format => "json"
assert_response :unauthorized
basic_authorization(users(:public_user).email, "test")
- delete :destroy, {:id => 12345, :format => "json"}
+ delete :destroy, :id => 12345, :format => "json"
assert_response :forbidden
basic_authorization(users(:moderator_user).email, "test")
- delete :destroy, {:id => 12345, :format => "json"}
+ delete :destroy, :id => 12345, :format => "json"
assert_response :not_found
- delete :destroy, {:id => notes(:hidden_note_with_comment).id, :format => "json"}
+ delete :destroy, :id => notes(:hidden_note_with_comment).id, :format => "json"
assert_response :gone
end
def test_index_success
- get :index, {:bbox => '1,1,1.2,1.2', :format => 'rss'}
+ get :index, :bbox => '1,1,1.2,1.2', :format => 'rss'
assert_response :success
assert_equal "application/rss+xml", @response.content_type
assert_select "rss", :count => 1 do
end
end
- get :index, {:bbox => '1,1,1.2,1.2', :format => 'json'}
+ get :index, :bbox => '1,1,1.2,1.2', :format => 'json'
assert_response :success
assert_equal "application/json", @response.content_type
js = ActiveSupport::JSON.decode(@response.body)
assert_equal "FeatureCollection", js["type"]
assert_equal 2, js["features"].count
- get :index, {:bbox => '1,1,1.2,1.2', :format => 'xml'}
+ get :index, :bbox => '1,1,1.2,1.2', :format => 'xml'
assert_response :success
assert_equal "application/xml", @response.content_type
assert_select "osm", :count => 1 do
assert_select "note", :count => 2
end
- get :index, {:bbox => '1,1,1.2,1.2', :format => 'gpx'}
+ get :index, :bbox => '1,1,1.2,1.2', :format => 'gpx'
assert_response :success
assert_equal "application/gpx+xml", @response.content_type
assert_select "gpx", :count => 1 do
end
def test_index_empty_area
- get :index, {:bbox => '5,5,5.1,5.1', :format => 'rss'}
+ get :index, :bbox => '5,5,5.1,5.1', :format => 'rss'
assert_response :success
assert_equal "application/rss+xml", @response.content_type
assert_select "rss", :count => 1 do
end
end
- get :index, {:bbox => '5,5,5.1,5.1', :format => 'json'}
+ get :index, :bbox => '5,5,5.1,5.1', :format => 'json'
assert_response :success
assert_equal "application/json", @response.content_type
js = ActiveSupport::JSON.decode(@response.body)
assert_equal "FeatureCollection", js["type"]
assert_equal 0, js["features"].count
- get :index, {:bbox => '5,5,5.1,5.1', :format => 'xml'}
+ get :index, :bbox => '5,5,5.1,5.1', :format => 'xml'
assert_response :success
assert_equal "application/xml", @response.content_type
assert_select "osm", :count => 1 do
assert_select "note", :count => 0
end
- get :index, {:bbox => '5,5,5.1,5.1', :format => 'gpx'}
+ get :index, :bbox => '5,5,5.1,5.1', :format => 'gpx'
assert_response :success
assert_equal "application/gpx+xml", @response.content_type
assert_select "gpx", :count => 1 do
end
def test_index_large_area
- get :index, {:bbox => '-2.5,-2.5,2.5,2.5', :format => :json}
+ get :index, :bbox => '-2.5,-2.5,2.5,2.5', :format => :json
assert_response :success
assert_equal "application/json", @response.content_type
- get :index, {:l => '-2.5', :b => '-2.5', :r => '2.5', :t => '2.5', :format => :json}
+ get :index, :l => '-2.5', :b => '-2.5', :r => '2.5', :t => '2.5', :format => :json
assert_response :success
assert_equal "application/json", @response.content_type
- get :index, {:bbox => '-10,-10,12,12', :format => :json}
+ get :index, :bbox => '-10,-10,12,12', :format => :json
assert_response :bad_request
assert_equal "text/plain", @response.content_type
- get :index, {:l => '-10', :b => '-10', :r => '12', :t => '12', :format => :json}
+ get :index, :l => '-10', :b => '-10', :r => '12', :t => '12', :format => :json
assert_response :bad_request
assert_equal "text/plain", @response.content_type
end
def test_index_closed
- get :index, {:bbox => '1,1,1.7,1.7', :closed => '7', :format => 'json'}
+ get :index, :bbox => '1,1,1.7,1.7', :closed => '7', :format => 'json'
assert_response :success
assert_equal "application/json", @response.content_type
js = ActiveSupport::JSON.decode(@response.body)
assert_equal "FeatureCollection", js["type"]
assert_equal 4, js["features"].count
- get :index, {:bbox => '1,1,1.7,1.7', :closed => '0', :format => 'json'}
+ get :index, :bbox => '1,1,1.7,1.7', :closed => '0', :format => 'json'
assert_response :success
assert_equal "application/json", @response.content_type
js = ActiveSupport::JSON.decode(@response.body)
assert_equal "FeatureCollection", js["type"]
assert_equal 4, js["features"].count
- get :index, {:bbox => '1,1,1.7,1.7', :closed => '-1', :format => 'json'}
+ get :index, :bbox => '1,1,1.7,1.7', :closed => '-1', :format => 'json'
assert_response :success
assert_equal "application/json", @response.content_type
js = ActiveSupport::JSON.decode(@response.body)
end
def test_index_bad_params
- get :index, {:bbox => '-2.5,-2.5,2.5'}
+ get :index, :bbox => '-2.5,-2.5,2.5'
assert_response :bad_request
- get :index, {:bbox => '-2.5,-2.5,2.5,2.5,2.5'}
+ get :index, :bbox => '-2.5,-2.5,2.5,2.5,2.5'
assert_response :bad_request
- get :index, {:b => '-2.5', :r => '2.5', :t => '2.5'}
+ get :index, :b => '-2.5', :r => '2.5', :t => '2.5'
assert_response :bad_request
- get :index, {:l => '-2.5', :r => '2.5', :t => '2.5'}
+ get :index, :l => '-2.5', :r => '2.5', :t => '2.5'
assert_response :bad_request
- get :index, {:l => '-2.5', :b => '-2.5', :t => '2.5'}
+ get :index, :l => '-2.5', :b => '-2.5', :t => '2.5'
assert_response :bad_request
- get :index, {:l => '-2.5', :b => '-2.5', :r => '2.5'}
+ get :index, :l => '-2.5', :b => '-2.5', :r => '2.5'
assert_response :bad_request
- get :index, {:bbox => '1,1,1.7,1.7', :limit => '0', :format => 'json'}
+ get :index, :bbox => '1,1,1.7,1.7', :limit => '0', :format => 'json'
assert_response :bad_request
- get :index, {:bbox => '1,1,1.7,1.7', :limit => '10001', :format => 'json'}
+ get :index, :bbox => '1,1,1.7,1.7', :limit => '10001', :format => 'json'
assert_response :bad_request
end
def test_search_success
- get :search, {:q => 'note 1', :format => 'xml'}
+ get :search, :q => 'note 1', :format => 'xml'
assert_response :success
assert_equal "application/xml", @response.content_type
assert_select "osm", :count => 1 do
assert_select "note", :count => 1
end
- get :search, {:q => 'note 1', :format => 'json'}
+ get :search, :q => 'note 1', :format => 'json'
assert_response :success
assert_equal "application/json", @response.content_type
js = ActiveSupport::JSON.decode(@response.body)
assert_equal "FeatureCollection", js["type"]
assert_equal 1, js["features"].count
- get :search, {:q => 'note 1', :format => 'rss'}
+ get :search, :q => 'note 1', :format => 'rss'
assert_response :success
assert_equal "application/rss+xml", @response.content_type
assert_select "rss", :count => 1 do
end
end
- get :search, {:q => 'note 1', :format => 'gpx'}
+ get :search, :q => 'note 1', :format => 'gpx'
assert_response :success
assert_equal "application/gpx+xml", @response.content_type
assert_select "gpx", :count => 1 do
end
def test_search_no_match
- get :search, {:q => 'no match', :format => 'xml'}
+ get :search, :q => 'no match', :format => 'xml'
assert_response :success
assert_equal "application/xml", @response.content_type
assert_select "osm", :count => 1 do
assert_select "note", :count => 0
end
- get :search, {:q => 'no match', :format => 'json'}
+ get :search, :q => 'no match', :format => 'json'
assert_response :success
assert_equal "application/json", @response.content_type
js = ActiveSupport::JSON.decode(@response.body)
assert_equal "FeatureCollection", js["type"]
assert_equal 0, js["features"].count
- get :search, {:q => 'no match', :format => 'rss'}
+ get :search, :q => 'no match', :format => 'rss'
assert_response :success
assert_equal "application/rss+xml", @response.content_type
assert_select "rss", :count => 1 do
end
end
- get :search, {:q => 'no match', :format => 'gpx'}
+ get :search, :q => 'no match', :format => 'gpx'
assert_response :success
assert_equal "application/gpx+xml", @response.content_type
assert_select "gpx", :count => 1 do
get :search
assert_response :bad_request
- get :search, {:q => 'no match', :limit => '0', :format => 'json'}
+ get :search, :q => 'no match', :limit => '0', :format => 'json'
assert_response :bad_request
- get :search, {:q => 'no match', :limit => '10001', :format => 'json'}
+ get :search, :q => 'no match', :limit => '10001', :format => 'json'
assert_response :bad_request
end
def test_feed_success
- get :feed, {:format => "rss"}
+ get :feed, :format => "rss"
assert_response :success
assert_equal "application/rss+xml", @response.content_type
assert_select "rss", :count => 1 do
end
end
- get :feed, {:bbox => "1,1,1.2,1.2", :format => "rss"}
+ get :feed, :bbox => "1,1,1.2,1.2", :format => "rss"
assert_response :success
assert_equal "application/rss+xml", @response.content_type
assert_select "rss", :count => 1 do
end
def test_feed_fail
- get :feed, {:bbox => "1,1,1.2", :format => "rss"}
+ get :feed, :bbox => "1,1,1.2", :format => "rss"
assert_response :bad_request
- get :feed, {:bbox => "1,1,1.2,1.2,1.2", :format => "rss"}
+ get :feed, :bbox => "1,1,1.2,1.2,1.2", :format => "rss"
assert_response :bad_request
- get :feed, {:bbox => "1,1,1.2,1.2", :limit => '0', :format => "rss"}
+ get :feed, :bbox => "1,1,1.2,1.2", :limit => '0', :format => "rss"
assert_response :bad_request
- get :feed, {:bbox => "1,1,1.2,1.2", :limit => '10001', :format => "rss"}
+ get :feed, :bbox => "1,1,1.2,1.2", :limit => '10001', :format => "rss"
assert_response :bad_request
end
def test_mine_success
- get :mine, {:display_name => "test"}
+ get :mine, :display_name => "test"
assert_response :success
- get :mine, {:display_name => "pulibc_test2"}
+ get :mine, :display_name => "pulibc_test2"
assert_response :success
- get :mine, {:display_name => "non-existent"}
+ get :mine, :display_name => "non-existent"
assert_response :not_found
end
end
def test_index
user = users(:public_user)
- get :index, { :display_name => user.display_name }
+ get :index, :display_name => user.display_name
assert_response :redirect
assert_redirected_to login_path(:referer => oauth_clients_path(:display_name => user.display_name))
def test_new
user = users(:public_user)
- get :new, { :display_name => user.display_name }
+ get :new, :display_name => user.display_name
assert_response :redirect
assert_redirected_to login_path(:referer => new_oauth_client_path(:display_name => user.display_name))
user = users(:public_user)
assert_difference "ClientApplication.count", 0 do
- post :create, { :display_name => user.display_name }
+ post :create, :display_name => user.display_name
end
assert_response :forbidden
post :create, {
:display_name => user.display_name,
:client_application => {
- :name => "Test Application"
+ :name => "Test Application"
}
- }, {
- :user => user
- }
+ }, { :user => user }
end
assert_response :success
assert_template "new"
:name => "Test Application",
:url => "http://test.example.com/"
}
- }, {
- :user => user
- }
+ }, { :user => user }
end
assert_response :redirect
assert_redirected_to oauth_client_path(:id => ClientApplication.find_by_name("Test Application").id)
user = users(:public_user)
client = client_applications(:oauth_web_app)
- get :show, { :display_name => user.display_name, :id => client.id }
+ get :show, :display_name => user.display_name, :id => client.id
assert_response :redirect
assert_redirected_to login_path(:referer => oauth_client_path(:display_name => user.display_name, :id => client.id))
user = users(:public_user)
client = client_applications(:oauth_web_app)
- get :edit, { :display_name => user.display_name, :id => client.id }
+ get :edit, :display_name => user.display_name, :id => client.id
assert_response :redirect
assert_redirected_to login_path(:referer => edit_oauth_client_path(:display_name => user.display_name, :id => client.id))
user = users(:public_user)
client = client_applications(:oauth_web_app)
- put :update, { :display_name => user.display_name, :id => client.id }
+ put :update, :display_name => user.display_name, :id => client.id
assert_response :forbidden
put :update, { :display_name => user.display_name, :id => client_applications(:normal_user_app).id }, { :user => user }
:name => "New Name",
:url => nil
}
- }, {
- :user => user
- }
+ }, { :user => user }
assert_response :success
assert_template "edit"
:name => "New Name",
:url => "http://new.example.com/url"
}
- }, {
- :user => user
- }
+ }, { :user => user }
assert_response :redirect
assert_redirected_to oauth_client_path(:id => client.id)
end
client = client_applications(:oauth_web_app)
assert_difference "ClientApplication.count", 0 do
- delete :destroy, { :display_name => user.display_name, :id => client.id }
+ delete :destroy, :display_name => user.display_name, :id => client.id
end
assert_response :forbidden
# keep a hash of the versions => string, as we'll need something
# to test against later
- versions = Hash.new
+ versions = {}
# save a version for later checking
versions[xml_node['version']] = xml_doc.to_s
content xml_doc
put :update, :id => nodeid
assert_response :forbidden,
- "should have rejected node #{nodeid} (#{@response.body}) with forbidden"
+ "should have rejected node #{nodeid} (#{@response.body}) with forbidden"
xml_node['version'] = @response.body.to_s
end
# save a version for later checking
# probably should check that they didn't get written to the database
-
## Now do it with the public user
basic_authorization(users(:public_user).email, "test")
changeset_id = changesets(:public_user_first_change).id
# keep a hash of the versions => string, as we'll need something
# to test against later
- versions = Hash.new
+ versions = {}
# save a version for later checking
versions[xml_node['version']] = xml_doc.to_s
content xml_doc
put :update, :id => nodeid
assert_response :success,
- "couldn't update node #{nodeid} (#{@response.body})"
+ "couldn't update node #{nodeid} (#{@response.body})"
xml_node['version'] = @response.body.to_s
end
# save a version for later checking
get :version, :id => nodeid, :version => key.to_i
assert_response :success,
- "couldn't get version #{key.to_i} of node #{nodeid}"
+ "couldn't get version #{key.to_i} of node #{nodeid}"
check_node = Node.from_xml(versions[key])
api_node = Node.from_xml(@response.body.to_s)
end
def test_not_found_version
- check_not_found_id_version(70000,312344)
+ check_not_found_id_version(70000, 312344)
check_not_found_id_version(-1, -13)
check_not_found_id_version(nodes(:visible_node).id, 24354)
check_not_found_id_version(24356, nodes(:visible_node).version)
# returns a 16 character long string with some nasty characters in it.
# this ought to stress-test the tag handling as well as the versioning.
def random_string
- letters = [['!','"','$','&',';','@'],
+ letters = [['!', '"', '$', '&', ';', '@'],
('a'..'z').to_a,
('A'..'Z').to_a,
('0'..'9').to_a].flatten
- (1..16).map { |i| letters[ rand(letters.length) ] }.join
+ (1..16).map { |_i| letters[rand(letters.length)] }.join
end
##
# the database. otherwise rounding errors can produce failing unit
# tests when they shouldn't.
def precision(f)
- return (f * GeoRecord::SCALE).round.to_f / GeoRecord::SCALE
+ (f * GeoRecord::SCALE).round.to_f / GeoRecord::SCALE
end
end
assert_response :unauthorized, "should need to be authenticated to redact."
end
- ##
+ ##
# test the redaction of an old version of a relation, while being
# authorised as a normal user.
def test_redact_relation_normal_user
assert_response :unauthorized, "should need to be authenticated to redact."
end
- ##
+ ##
# test the redaction of an old version of a way, while being
# authorised as a normal user.
def test_redact_way_normal_user
basic_authorization(users(:moderator_user).email, "test")
do_redact_way(ways(:way_with_versions_v4),
- redactions(:example))
+ redactions(:example))
assert_response :bad_request, "shouldn't be OK to redact current version as moderator."
end
# now redact it
post :redact, :id => way.way_id, :version => way.version, :redaction => redaction.id
end
-
end
def test_relations_for_node
check_relations_for_element(:relations_for_node, "node",
current_nodes(:node_used_by_relationship).id,
- [ :visible_relation, :used_relation ])
+ [:visible_relation, :used_relation])
end
def test_relations_for_way
check_relations_for_element(:relations_for_way, "way",
current_ways(:used_way).id,
- [ :visible_relation ])
+ [:visible_relation])
end
def test_relations_for_relation
check_relations_for_element(:relations_for_relation, "relation",
current_relations(:used_relation).id,
- [ :visible_relation ])
+ [:visible_relation])
end
def check_relations_for_element(method, type, id, expected_relations)
assert_response :success
# FIXME check whether this contains the stuff we want!
if $VERBOSE
- print @response.body
+ print @response.body
end
end
put :create
# hope for forbidden, due to user
assert_response :forbidden,
- "relation upload should have failed with forbidden"
+ "relation upload should have failed with forbidden"
###
# create an relation with a node as member
put :create
# hope for forbidden due to user
assert_response :forbidden,
- "relation upload did not return forbidden status"
+ "relation upload did not return forbidden status"
###
# create an relation with a node as member, this time test that we don't
# need a role attribute to be included
nid = current_nodes(:used_node_1).id
content "<osm><relation changeset='#{changeset_id}'>" +
- "<member ref='#{nid}' type='node'/>"+
- "<tag k='test' v='yes' /></relation></osm>"
+ "<member ref='#{nid}' type='node'/>" + "<tag k='test' v='yes' /></relation></osm>"
put :create
# hope for forbidden due to user
assert_response :forbidden,
- "relation upload did not return forbidden status"
+ "relation upload did not return forbidden status"
###
# create an relation with a way and a node as members
put :create
# hope for forbidden, due to user
assert_response :forbidden,
- "relation upload did not return success status"
-
-
+ "relation upload did not return success status"
## Now try with the public user
basic_authorization users(:public_user).email, "test"
put :create
# hope for success
assert_response :success,
- "relation upload did not return success status"
+ "relation upload did not return success status"
# read id of created relation and search for it
relationid = @response.body
checkrelation = Relation.find(relationid)
assert_not_nil checkrelation,
- "uploaded relation not found in data base after upload"
+ "uploaded relation not found in data base after upload"
# compare values
assert_equal checkrelation.members.length, 0,
- "saved relation contains members but should not"
+ "saved relation contains members but should not"
assert_equal checkrelation.tags.length, 1,
- "saved relation does not contain exactly one tag"
+ "saved relation does not contain exactly one tag"
assert_equal changeset_id, checkrelation.changeset.id,
- "saved relation does not belong in the changeset it was assigned to"
+ "saved relation does not belong in the changeset it was assigned to"
assert_equal users(:public_user).id, checkrelation.changeset.user_id,
- "saved relation does not belong to user that created it"
+ "saved relation does not belong to user that created it"
assert_equal true, checkrelation.visible,
- "saved relation is not visible"
+ "saved relation is not visible"
# ok the relation is there but can we also retrieve it?
get :read, :id => relationid
assert_response :success
-
###
# create an relation with a node as member
# This time try with a role attribute in the relation
put :create
# hope for success
assert_response :success,
- "relation upload did not return success status"
+ "relation upload did not return success status"
# read id of created relation and search for it
relationid = @response.body
checkrelation = Relation.find(relationid)
assert_not_nil checkrelation,
- "uploaded relation not found in data base after upload"
+ "uploaded relation not found in data base after upload"
# compare values
assert_equal checkrelation.members.length, 1,
- "saved relation does not contain exactly one member"
+ "saved relation does not contain exactly one member"
assert_equal checkrelation.tags.length, 1,
- "saved relation does not contain exactly one tag"
+ "saved relation does not contain exactly one tag"
assert_equal changeset_id, checkrelation.changeset.id,
- "saved relation does not belong in the changeset it was assigned to"
+ "saved relation does not belong in the changeset it was assigned to"
assert_equal users(:public_user).id, checkrelation.changeset.user_id,
- "saved relation does not belong to user that created it"
+ "saved relation does not belong to user that created it"
assert_equal true, checkrelation.visible,
- "saved relation is not visible"
+ "saved relation is not visible"
# ok the relation is there but can we also retrieve it?
get :read, :id => relationid
assert_response :success
-
###
# create an relation with a node as member, this time test that we don't
# need a role attribute to be included
nid = current_nodes(:used_node_1).id
content "<osm><relation changeset='#{changeset_id}'>" +
- "<member ref='#{nid}' type='node'/>"+
- "<tag k='test' v='yes' /></relation></osm>"
+ "<member ref='#{nid}' type='node'/>" + "<tag k='test' v='yes' /></relation></osm>"
put :create
# hope for success
assert_response :success,
- "relation upload did not return success status"
+ "relation upload did not return success status"
# read id of created relation and search for it
relationid = @response.body
checkrelation = Relation.find(relationid)
assert_not_nil checkrelation,
- "uploaded relation not found in data base after upload"
+ "uploaded relation not found in data base after upload"
# compare values
assert_equal checkrelation.members.length, 1,
- "saved relation does not contain exactly one member"
+ "saved relation does not contain exactly one member"
assert_equal checkrelation.tags.length, 1,
- "saved relation does not contain exactly one tag"
+ "saved relation does not contain exactly one tag"
assert_equal changeset_id, checkrelation.changeset.id,
- "saved relation does not belong in the changeset it was assigned to"
+ "saved relation does not belong in the changeset it was assigned to"
assert_equal users(:public_user).id, checkrelation.changeset.user_id,
- "saved relation does not belong to user that created it"
+ "saved relation does not belong to user that created it"
assert_equal true, checkrelation.visible,
- "saved relation is not visible"
+ "saved relation is not visible"
# ok the relation is there but can we also retrieve it?
get :read, :id => relationid
put :create
# hope for success
assert_response :success,
- "relation upload did not return success status"
+ "relation upload did not return success status"
# read id of created relation and search for it
relationid = @response.body
checkrelation = Relation.find(relationid)
assert_not_nil checkrelation,
- "uploaded relation not found in data base after upload"
+ "uploaded relation not found in data base after upload"
# compare values
assert_equal checkrelation.members.length, 2,
- "saved relation does not have exactly two members"
+ "saved relation does not have exactly two members"
assert_equal checkrelation.tags.length, 1,
- "saved relation does not contain exactly one tag"
+ "saved relation does not contain exactly one tag"
assert_equal changeset_id, checkrelation.changeset.id,
- "saved relation does not belong in the changeset it was assigned to"
+ "saved relation does not belong in the changeset it was assigned to"
assert_equal users(:public_user).id, checkrelation.changeset.user_id,
- "saved relation does not belong to user that created it"
+ "saved relation does not belong to user that created it"
assert_equal true, checkrelation.visible,
- "saved relation is not visible"
+ "saved relation is not visible"
# ok the relation is there but can we also retrieve it?
get :read, :id => relationid
assert_response :success
-
end
# ------------------------------------
put :create
# expect failure
assert_response :precondition_failed,
- "relation upload with invalid node did not return 'precondition failed'"
+ "relation upload with invalid node did not return 'precondition failed'"
assert_equal "Precondition failed: Relation with id cannot be saved due to Node with id 0", @response.body
end
# create some xml that should return an error
content "<osm><relation changeset='#{changeset_id}'>" +
- "<member type='type' ref='#{current_nodes(:used_node_1).id}' role=''/>" +
- "<tag k='tester' v='yep'/></relation></osm>"
+ "<member type='type' ref='#{current_nodes(:used_node_1).id}' role=''/>" +
+ "<tag k='tester' v='yep'/></relation></osm>"
put :create
# expect failure
assert_response :bad_request
assert_match(/The type is not allowed only, /, @response.body)
end
-
# -------------------------------------
# Test deleting relations.
# -------------------------------------
delete :delete, :id => current_relations(:visible_relation).id
assert_response :unauthorized
-
## Then try with the private user, to make sure that you get a forbidden
basic_authorization(users(:normal_user).email, "test")
assert_response :forbidden
# try to delete with an invalid (non-existent) changeset
- content update_changeset(current_relations(:visible_relation).to_xml,0)
+ content update_changeset(current_relations(:visible_relation).to_xml, 0)
delete :delete, :id => current_relations(:visible_relation).id
assert_response :forbidden
delete :delete, :id => 0
assert_response :forbidden
-
-
## now set auth for the public user
- basic_authorization(users(:public_user).email, "test");
+ basic_authorization(users(:public_user).email, "test")
# this shouldn't work, as we should need the payload...
delete :delete, :id => current_relations(:visible_relation).id
assert_response :conflict
# try to delete with an invalid (non-existent) changeset
- content update_changeset(current_relations(:visible_relation).to_xml,0)
+ content update_changeset(current_relations(:visible_relation).to_xml, 0)
delete :delete, :id => current_relations(:visible_relation).id
assert_response :conflict
content(relations(:used_relation).to_xml)
delete :delete, :id => current_relations(:used_relation).id
assert_response :conflict,
- "shouldn't be able to delete a relation in a changeset owned by someone else (#{@response.body})"
+ "shouldn't be able to delete a relation in a changeset owned by someone else (#{@response.body})"
# this won't work because the relation in the payload is different to that passed
content(relations(:public_used_relation).to_xml)
content(relations(:public_used_relation).to_xml)
delete :delete, :id => current_relations(:public_used_relation).id
assert_response :precondition_failed,
- "shouldn't be able to delete a relation used in a relation (#{@response.body})"
+ "shouldn't be able to delete a relation used in a relation (#{@response.body})"
assert_equal "Precondition failed: The relation 5 is used in relation 6.", @response.body
# this should work when we provide the appropriate payload...
# valid delete should return the new version number, which should
# be greater than the old version number
assert @response.body.to_i > current_relations(:visible_relation).version,
- "delete request should return a new version number for relation"
+ "delete request should return a new version number for relation"
# this won't work since the relation is already deleted
content(relations(:invisible_relation).to_xml)
content(relations(:public_used_relation).to_xml)
delete :delete, :id => current_relations(:public_used_relation).id
assert_response :success,
- "should be able to delete a relation used in an old relation (#{@response.body})"
+ "should be able to delete a relation used in an old relation (#{@response.body})"
# this won't work since the relation never existed
delete :delete, :id => 0
def test_tag_modify_bounding_box
# in current fixtures, relation 5 contains nodes 3 and 5 (node 3
# indirectly via way 3), so the bbox should be [3,3,5,5].
- check_changeset_modify(BoundingBox.new(3,3,5,5)) do |changeset_id|
+ check_changeset_modify(BoundingBox.new(3, 3, 5, 5)) do |changeset_id|
# add a tag to an existing relation
relation_xml = current_relations(:visible_relation).to_xml
relation_element = relation_xml.find("//osm/relation").first
current_nodes(:used_node_2),
current_ways(:used_way),
current_ways(:way_with_versions)
- ].each_with_index do |element, version|
+ ].each_with_index do |element, _version|
bbox = element.bbox.to_unscaled
check_changeset_modify(bbox) do |changeset_id|
relation_xml = Relation.find(relation_id).to_xml
# remove a member from a relation and check the bounding box is
# only that element.
def test_remove_member_bounding_box
- check_changeset_modify(BoundingBox.new(5,5,5,5)) do |changeset_id|
+ check_changeset_modify(BoundingBox.new(5, 5, 5, 5)) do |changeset_id|
# remove node 5 (5,5) from an existing relation
relation_xml = current_relations(:visible_relation).to_xml
- relation_xml.
- find("//osm/relation/member[@type='node'][@ref='5']").
- first.remove!
+ relation_xml
+ .find("//osm/relation/member[@type='node'][@ref='5']")
+ .first.remove!
# update changeset ID to point to new changeset
update_changeset(relation_xml, changeset_id)
doc = XML::Parser.string(doc_str).parse
## First try with the private user
- basic_authorization(users(:normal_user).email, "test");
+ basic_authorization(users(:normal_user).email, "test")
content doc
put :create
assert_response :forbidden
## Now try with the public user
- basic_authorization(users(:public_user).email, "test");
+ basic_authorization(users(:public_user).email, "test")
content doc
put :create
</osm>
OSM
doc = XML::Parser.string(doc_str).parse
- basic_authorization(users(:public_user).email, "test");
+ basic_authorization(users(:public_user).email, "test")
content doc
put :create
# remove all the members from a relation. the result is pretty useless, but
# still technically valid.
def test_remove_all_members
- check_changeset_modify(BoundingBox.new(3,3,5,5)) do |changeset_id|
+ check_changeset_modify(BoundingBox.new(3, 3, 5, 5)) do |changeset_id|
relation_xml = current_relations(:visible_relation).to_xml
- relation_xml.
- find("//osm/relation/member").
- each {|m| m.remove!}
+ relation_xml
+ .find("//osm/relation/member")
+ .each(&:remove!)
# update changeset ID to point to new changeset
update_changeset(relation_xml, changeset_id)
# that the changeset bounding box is +bbox+.
def check_changeset_modify(bbox)
## First test with the private user to check that you get a forbidden
- basic_authorization(users(:normal_user).email, "test");
+ basic_authorization(users(:normal_user).email, "test")
# create a new changeset for this operation, so we are assured
# that the bounding box will be newly-generated.
assert_response :forbidden, "shouldn't be able to create changeset for modify test, as should get forbidden"
end
-
## Now do the whole thing with the public user
basic_authorization(users(:public_user).email, "test")
yield new_rel
- return version
+ version
end
##
yield new_rel
- return version
+ version
end
##
# returns a k->v hash of tags from an xml doc
def get_tags_as_hash(a)
- a.find("//osm/relation/tag").sort_by { |v| v['k'] }.inject({}) do |h,v|
+ a.find("//osm/relation/tag").sort_by { |v| v['k'] }.inject({}) do |h, v|
h[v['k']] = v['v']
h
end
assert_equal a_tags.keys, b_tags.keys, "Tag keys should be identical."
a_tags.each do |k, v|
assert_equal v, b_tags[k],
- "Tags which were not altered should be the same. " +
- "#{a_tags.inspect} != #{b_tags.inspect}"
+ "Tags which were not altered should be the same. " +
+ "#{a_tags.inspect} != #{b_tags.inspect}"
end
end
# update an attribute in the node element
def xml_attr_rewrite(xml, name, value)
xml.find("//osm/relation").first[name] = value.to_s
- return xml
+ xml
end
##
# Test the right editor gets used when the user hasn't set a preference
def test_edit_without_preference
- get :edit, nil, { :user => users(:public_user).id }
+ get :edit, nil, :user => users(:public_user).id
assert_response :success
assert_template "edit"
assert_template :partial => "_#{DEFAULT_EDITOR}", :count => 1
user.preferred_editor = "id"
user.save!
- get :edit, nil, { :user => user.id }
+ get :edit, nil, :user => user.id
assert_response :success
assert_template "edit"
assert_template :partial => "_id", :count => 1
user.preferred_editor = "potlatch2"
user.save!
- get :edit, nil, { :user => user.id }
+ get :edit, nil, :user => user.id
assert_response :success
assert_template "edit"
assert_template :partial => "_potlatch2", :count => 1
user.preferred_editor = "potlatch"
user.save!
- get :edit, nil, { :user => user.id }
+ get :edit, nil, :user => user.id
assert_response :success
assert_template "edit"
assert_template :partial => "_potlatch", :count => 1
user.preferred_editor = "remote"
user.save!
- get :edit, nil, { :user => user.id }
+ get :edit, nil, :user => user.id
assert_response :success
assert_template "index"
end
assert_response :redirect
assert_redirected_to :controller => :user, :action => :login, :referer => "/welcome"
- get :welcome, nil, { :user => users(:public_user).id }
+ get :welcome, nil, :user => users(:public_user).id
assert_response :success
assert_template "welcome"
end
# Test the id frame
def test_id
- get :id, nil, { :user => users(:public_user).id }
+ get :id, nil, :user => users(:public_user).id
assert_response :success
assert_template "id"
assert_template :layout => false
assert_redirected_to :controller => 'user', :action => 'login', :referer => '/traces/mine'
# Now try when logged in
- get :mine, {}, {:user => users(:public_user).id}
+ get :mine, {}, { :user => users(:public_user).id }
assert_redirected_to :controller => 'trace', :action => 'list', :display_name => users(:public_user).display_name
# Fetch the actual list
- get :list, {:display_name => users(:public_user).display_name}, {:user => users(:public_user).id}
+ get :list, { :display_name => users(:public_user).display_name }, { :user => users(:public_user).id }
check_trace_list users(:public_user).traces
end
check_trace_list users(:public_user).traces.visible_to_all
# Should still see only public ones when authenticated as another user
- get :list, {:display_name => users(:public_user).display_name}, {:user => users(:normal_user).id}
+ get :list, { :display_name => users(:public_user).display_name }, { :user => users(:normal_user).id }
check_trace_list users(:public_user).traces.visible_to_all
# Should see all traces when authenticated as the target user
- get :list, {:display_name => users(:public_user).display_name}, {:user => users(:public_user).id}
+ get :list, { :display_name => users(:public_user).display_name }, { :user => users(:public_user).id }
check_trace_list users(:public_user).traces
# Should only see traces with the correct tag when a tag is specified
- get :list, {:display_name => users(:public_user).display_name, :tag => "London"}, {:user => users(:public_user).id}
+ get :list, { :display_name => users(:public_user).display_name, :tag => "London" }, { :user => users(:public_user).id }
check_trace_list users(:public_user).traces.tagged("London")
end
# Test viewing a trace
def test_view
# First with no auth, which should work since the trace is public
- get :view, {:display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id}
+ get :view, :display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id
check_trace_view gpx_files(:public_trace_file)
# Now with some other user, which should work since the trace is public
- get :view, {:display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id}, {:user => users(:public_user).id}
+ get :view, { :display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id }, { :user => users(:public_user).id }
check_trace_view gpx_files(:public_trace_file)
# And finally we should be able to do it with the owner of the trace
- get :view, {:display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id}, {:user => users(:normal_user).id}
+ get :view, { :display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id }, { :user => users(:normal_user).id }
check_trace_view gpx_files(:public_trace_file)
end
# Check an anonymous trace can't be viewed by another user
def test_view_anon
# First with no auth
- get :view, {:display_name => users(:public_user).display_name, :id => gpx_files(:anon_trace_file).id}
+ get :view, :display_name => users(:public_user).display_name, :id => gpx_files(:anon_trace_file).id
assert_response :redirect
assert_redirected_to :action => :list
# Now with some other user, which should work since the trace is anon
- get :view, {:display_name => users(:public_user).display_name, :id => gpx_files(:anon_trace_file).id}, {:user => users(:normal_user).id}
+ get :view, { :display_name => users(:public_user).display_name, :id => gpx_files(:anon_trace_file).id }, { :user => users(:normal_user).id }
assert_response :redirect
assert_redirected_to :action => :list
# And finally we should be able to do it with the owner of the trace
- get :view, {:display_name => users(:public_user).display_name, :id => gpx_files(:anon_trace_file).id}, {:user => users(:public_user).id}
+ get :view, { :display_name => users(:public_user).display_name, :id => gpx_files(:anon_trace_file).id }, { :user => users(:public_user).id }
check_trace_view gpx_files(:anon_trace_file)
end
# Test viewing a trace that doesn't exist
def test_view_not_found
# First with no auth, which should work since the trace is public
- get :view, {:display_name => users(:public_user).display_name, :id => 0}
+ get :view, :display_name => users(:public_user).display_name, :id => 0
assert_response :redirect
assert_redirected_to :action => :list
# Now with some other user, which should work since the trace is public
- get :view, {:display_name => users(:public_user).display_name, :id => 0}, {:user => users(:public_user).id}
+ get :view, { :display_name => users(:public_user).display_name, :id => 0 }, { :user => users(:public_user).id }
assert_response :redirect
assert_redirected_to :action => :list
# And finally we should be able to do it with the owner of the trace
- get :view, {:display_name => users(:public_user).display_name, :id => 5}, {:user => users(:public_user).id}
+ get :view, { :display_name => users(:public_user).display_name, :id => 5 }, { :user => users(:public_user).id }
assert_response :redirect
assert_redirected_to :action => :list
end
# Test downloading a trace
def test_data
# First with no auth, which should work since the trace is public
- get :data, {:display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id}
+ get :data, :display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id
check_trace_data gpx_files(:public_trace_file)
# Now with some other user, which should work since the trace is public
- get :data, {:display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id}, {:user => users(:public_user).id}
+ get :data, { :display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id }, { :user => users(:public_user).id }
check_trace_data gpx_files(:public_trace_file)
# And finally we should be able to do it with the owner of the trace
- get :data, {:display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id}, {:user => users(:normal_user).id}
+ get :data, { :display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id }, { :user => users(:normal_user).id }
check_trace_data gpx_files(:public_trace_file)
end
# Test downloading a compressed trace
def test_data_compressed
# First get the data as is
- get :data, {:display_name => users(:public_user).display_name, :id => gpx_files(:identifiable_trace_file).id}
+ get :data, :display_name => users(:public_user).display_name, :id => gpx_files(:identifiable_trace_file).id
check_trace_data gpx_files(:identifiable_trace_file), "application/x-gzip", "gpx.gz"
# Now ask explicitly for XML format
- get :data, {:display_name => users(:public_user).display_name, :id => gpx_files(:identifiable_trace_file).id, :format => "xml"}
+ get :data, :display_name => users(:public_user).display_name, :id => gpx_files(:identifiable_trace_file).id, :format => "xml"
check_trace_data gpx_files(:identifiable_trace_file), "application/xml", "xml"
# Now ask explicitly for GPX format
- get :data, {:display_name => users(:public_user).display_name, :id => gpx_files(:identifiable_trace_file).id, :format => "gpx"}
+ get :data, :display_name => users(:public_user).display_name, :id => gpx_files(:identifiable_trace_file).id, :format => "gpx"
check_trace_data gpx_files(:identifiable_trace_file)
end
# Check an anonymous trace can't be downloaded by another user
def test_data_anon
# First with no auth
- get :data, {:display_name => users(:public_user).display_name, :id => gpx_files(:anon_trace_file).id}
+ get :data, :display_name => users(:public_user).display_name, :id => gpx_files(:anon_trace_file).id
assert_response :not_found
# Now with some other user, which should work since the trace is anon
- get :data, {:display_name => users(:public_user).display_name, :id => gpx_files(:anon_trace_file).id}, {:user => users(:normal_user).id}
+ get :data, { :display_name => users(:public_user).display_name, :id => gpx_files(:anon_trace_file).id }, { :user => users(:normal_user).id }
assert_response :not_found
# And finally we should be able to do it with the owner of the trace
- get :data, {:display_name => users(:public_user).display_name, :id => gpx_files(:anon_trace_file).id}, {:user => users(:public_user).id}
+ get :data, { :display_name => users(:public_user).display_name, :id => gpx_files(:anon_trace_file).id }, { :user => users(:public_user).id }
check_trace_data gpx_files(:anon_trace_file)
end
# Test downloading a trace that doesn't exist
def test_data_not_found
# First with no auth, which should work since the trace is public
- get :data, {:display_name => users(:public_user).display_name, :id => 0}
+ get :data, :display_name => users(:public_user).display_name, :id => 0
assert_response :not_found
# Now with some other user, which should work since the trace is public
- get :data, {:display_name => users(:public_user).display_name, :id => 0}, {:user => users(:public_user).id}
+ get :data, { :display_name => users(:public_user).display_name, :id => 0 }, { :user => users(:public_user).id }
assert_response :not_found
# And finally we should be able to do it with the owner of the trace
- get :data, {:display_name => users(:public_user).display_name, :id => 5}, {:user => users(:public_user).id}
+ get :data, { :display_name => users(:public_user).display_name, :id => 5 }, { :user => users(:public_user).id }
assert_response :not_found
end
# Test fetching the edit page for a trace
def test_edit_get
# First with no auth
- get :edit, {:display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id}
+ get :edit, :display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id
assert_response :redirect
assert_redirected_to :controller => :user, :action => :login, :referer => trace_edit_path(:display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id)
# Now with some other user, which should fail
- get :edit, {:display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id}, {:user => users(:public_user).id}
+ get :edit, { :display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id }, { :user => users(:public_user).id }
assert_response :forbidden
# Now with a trace which doesn't exist
- get :edit, {:display_name => users(:public_user).display_name, :id => 0}, {:user => users(:public_user).id}
+ get :edit, { :display_name => users(:public_user).display_name, :id => 0 }, { :user => users(:public_user).id }
assert_response :not_found
# Now with a trace which has been deleted
- get :edit, {:display_name => users(:public_user).display_name, :id => gpx_files(:deleted_trace_file).id}, {:user => users(:public_user).id}
+ get :edit, { :display_name => users(:public_user).display_name, :id => gpx_files(:deleted_trace_file).id }, { :user => users(:public_user).id }
assert_response :not_found
# Finally with a trace that we are allowed to edit
- get :edit, {:display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id}, {:user => users(:normal_user).id}
+ get :edit, { :display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id }, { :user => users(:normal_user).id }
assert_response :success
end
new_details = { :description => "Changed description", :tagstring => "new_tag", :visibility => "private" }
# First with no auth
- post :edit, {:display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id, :trace => new_details}
+ post :edit, :display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id, :trace => new_details
assert_response :forbidden
# Now with some other user, which should fail
- post :edit, {:display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id, :trace => new_details}, {:user => users(:public_user).id}
+ post :edit, { :display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id, :trace => new_details }, { :user => users(:public_user).id }
assert_response :forbidden
# Now with a trace which doesn't exist
- post :edit, {:display_name => users(:public_user).display_name, :id => 0}, {:user => users(:public_user).id, :trace => new_details}
+ post :edit, { :display_name => users(:public_user).display_name, :id => 0 }, { :user => users(:public_user).id, :trace => new_details }
assert_response :not_found
# Now with a trace which has been deleted
- post :edit, {:display_name => users(:public_user).display_name, :id => gpx_files(:deleted_trace_file).id, :trace => new_details}, {:user => users(:public_user).id}
+ post :edit, { :display_name => users(:public_user).display_name, :id => gpx_files(:deleted_trace_file).id, :trace => new_details }, { :user => users(:public_user).id }
assert_response :not_found
# Finally with a trace that we are allowed to edit
- post :edit, {:display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id, :trace => new_details}, {:user => users(:normal_user).id}
+ post :edit, { :display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id, :trace => new_details }, { :user => users(:normal_user).id }
assert_response :redirect
assert_redirected_to :action => :view, :display_name => users(:normal_user).display_name
trace = Trace.find(gpx_files(:public_trace_file).id)
# Test deleting a trace
def test_delete
# First with no auth
- post :delete, {:display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id,}
+ post :delete, :display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id
assert_response :forbidden
# Now with some other user, which should fail
- post :delete, {:display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id}, {:user => users(:public_user).id}
+ post :delete, { :display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id }, { :user => users(:public_user).id }
assert_response :forbidden
# Now with a trace which doesn't exist
- post :delete, {:display_name => users(:public_user).display_name, :id => 0}, {:user => users(:public_user).id}
+ post :delete, { :display_name => users(:public_user).display_name, :id => 0 }, { :user => users(:public_user).id }
assert_response :not_found
# Now with a trace has already been deleted
- post :delete, {:display_name => users(:public_user).display_name, :id => gpx_files(:deleted_trace_file).id}, {:user => users(:public_user).id}
+ post :delete, { :display_name => users(:public_user).display_name, :id => gpx_files(:deleted_trace_file).id }, { :user => users(:public_user).id }
assert_response :not_found
# Finally with a trace that we are allowed to delete
- post :delete, {:display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id}, {:user => users(:normal_user).id}
+ post :delete, { :display_name => users(:normal_user).display_name, :id => gpx_files(:public_trace_file).id }, { :user => users(:normal_user).id }
assert_response :redirect
assert_redirected_to :action => :list, :display_name => users(:normal_user).display_name
trace = Trace.find(gpx_files(:public_trace_file).id)
content gpx_files(:anon_trace_file).to_xml
put :api_update, :id => gpx_files(:public_trace_file).id
assert_response :bad_request,
- "should not be able to update a trace with a different ID from the XML"
+ "should not be able to update a trace with a different ID from the XML"
# And finally try an update that should work
basic_authorization(users(:normal_user).display_name, "test")
assert_response :not_found
end
-private
+ private
def check_trace_feed(traces)
assert_response :success
assert_select "link"
assert_select "image"
assert_select "item", :count => traces.visible.count do |items|
- traces.visible.order("timestamp DESC").zip(items).each do |trace,item|
+ traces.visible.order("timestamp DESC").zip(items).each do |trace, item|
assert_select item, "title", trace.name
assert_select item, "link", "http://test.host/user/#{trace.user.display_name}/traces/#{trace.id}"
assert_select item, "guid", "http://test.host/user/#{trace.user.display_name}/traces/#{trace.id}"
assert_select item, "description"
-# assert_select item, "dc:creator", trace.user.display_name
+ # assert_select item, "dc:creator", trace.user.display_name
assert_select item, "pubDate", trace.timestamp.rfc822
end
end
if traces.count > 0
assert_select "table#trace_list tbody", :count => 1 do
assert_select "tr", :count => traces.visible.count do |rows|
- traces.visible.order("timestamp DESC").zip(rows).each do |trace,row|
+ traces.visible.order("timestamp DESC").zip(rows).each do |trace, row|
assert_select row, "span.trace_summary", Regexp.new(Regexp.escape("(#{trace.size} points)"))
assert_select row, "td", Regexp.new(Regexp.escape(trace.description))
assert_select row, "td", Regexp.new(Regexp.escape("by #{trace.user.display_name}"))
# A bogus block period should result in an error
assert_no_difference "UserBlock.count" do
post :create,
- :display_name => users(:unblocked_user).display_name,
- :user_block_period => "99"
+ :display_name => users(:unblocked_user).display_name,
+ :user_block_period => "99"
end
assert_redirected_to new_user_block_path(:display_name => users(:unblocked_user).display_name)
assert_equal "The blocking period must be one of the values selectable in the drop-down list.", flash[:error]
# Check that creating a block works
assert_difference "UserBlock.count", 1 do
post :create,
- :display_name => users(:unblocked_user).display_name,
- :user_block_period => "12",
- :user_block => { :needs_view => false, :reason => "Vandalism" }
+ :display_name => users(:unblocked_user).display_name,
+ :user_block_period => "12",
+ :user_block => { :needs_view => false, :reason => "Vandalism" }
end
id = UserBlock.order(:id).ids.last
assert_redirected_to user_block_path(:id => id)
# Check that only the person who created a block can update it
assert_no_difference "UserBlock.count" do
put :update,
- :id => user_blocks(:active_block).id,
- :user_block_period => "12",
- :user_block => { :needs_view => true, :reason => "Vandalism" }
+ :id => user_blocks(:active_block).id,
+ :user_block_period => "12",
+ :user_block => { :needs_view => true, :reason => "Vandalism" }
end
assert_redirected_to edit_user_block_path(:id => user_blocks(:active_block).id)
assert_equal "Only the moderator who created this block can edit it.", flash[:error]
# A bogus block period should result in an error
assert_no_difference "UserBlock.count" do
put :update,
- :id => user_blocks(:active_block).id,
- :user_block_period => "99"
+ :id => user_blocks(:active_block).id,
+ :user_block_period => "99"
end
assert_redirected_to edit_user_block_path(:id => user_blocks(:active_block).id)
assert_equal "The blocking period must be one of the values selectable in the drop-down list.", flash[:error]
# Check that updating a block works
assert_no_difference "UserBlock.count" do
put :update,
- :id => user_blocks(:active_block).id,
- :user_block_period => "12",
- :user_block => { :needs_view => true, :reason => "Vandalism" }
+ :id => user_blocks(:active_block).id,
+ :user_block_period => "12",
+ :user_block => { :needs_view => true, :reason => "Vandalism" }
end
assert_redirected_to user_block_path(:id => user_blocks(:active_block).id)
assert_equal "Block updated.", flash[:notice]
assert_difference('User.count', 1) do
assert_difference('ActionMailer::Base.deliveries.size', 1) do
- post :save, {}, {:new_user => user}
+ post :save, {}, { :new_user => user }
end
end
assert_no_difference('User.count') do
assert_no_difference('ActionMailer::Base.deliveries.size') do
- post :save, {}, {:new_user => user}
+ post :save, {}, { :new_user => user }
end
end
assert_no_difference('User.count') do
assert_no_difference('ActionMailer::Base.deliveries.size') do
- post :save, {}, {:new_user => user}
+ post :save, {}, { :new_user => user }
end
end
assert_no_difference('User.count') do
assert_no_difference('ActionMailer::Base.deliveries.size') do
- post :save, {}, {:new_user => user}
+ post :save, {}, { :new_user => user }
end
end
assert_no_difference('User.count') do
assert_no_difference('ActionMailer::Base.deliveries.size') do
- post :save, {}, {:new_user => user}
+ post :save, {}, { :new_user => user }
end
end
assert_difference('User.count', 1) do
assert_difference('ActionMailer::Base.deliveries.size', 1) do
- post :save, {}, {:new_user => user,
- :referer => '/edit?editor=id#map=1/2/3'}
- end
+ post :save, {}, { :new_user => user,
+ :referer => '/edit?editor=id#map=1/2/3' }
+ end
end
assert_equal welcome_path(:editor => 'id', :zoom => 1, :lat => 2, :lon => 3),
# Make sure that you are redirected to the login page when
# you are not logged in
- get :account, { :display_name => user.display_name }
+ get :account, :display_name => user.display_name
assert_response :redirect
assert_redirected_to :controller => :user, :action => "login", :referer => "/user/test/account"
# information for the user
def test_user_view_account
# Test a non-existent user
- get :view, {:display_name => "unknown"}
+ get :view, :display_name => "unknown"
assert_response :not_found
# Test a normal user
- get :view, {:display_name => "test"}
+ get :view, :display_name => "test"
assert_response :success
assert_select "div#userinformation" do
assert_select "a[href^='/user/test/history']", 1
end
# Test a user who has been blocked
- get :view, {:display_name => "blocked"}
+ get :view, :display_name => "blocked"
assert_response :success
assert_select "div#userinformation" do
assert_select "a[href^='/user/blocked/history']", 1
end
# Test a moderator who has applied blocks
- get :view, {:display_name => "moderator"}
+ get :view, :display_name => "moderator"
assert_response :success
assert_select "div#userinformation" do
assert_select "a[href^='/user/moderator/history']", 1
session[:user] = users(:normal_user).id
# Test the normal user
- get :view, {:display_name => "test"}
+ get :view, :display_name => "test"
assert_response :success
assert_select "div#userinformation" do
assert_select "a[href^='/user/test/history']", 1
session[:user] = users(:moderator_user).id
# Test the normal user
- get :view, {:display_name => "test"}
+ get :view, :display_name => "test"
assert_response :success
assert_select "div#userinformation" do
assert_select "a[href^='/user/test/history']", 1
assert_nil Friend.where(:user_id => user.id, :friend_user_id => friend.id).first
# When not logged in a GET should ask us to login
- get :make_friend, {:display_name => friend.display_name}
+ get :make_friend, :display_name => friend.display_name
assert_redirected_to :controller => :user, :action => "login", :referer => make_friend_path(:display_name => friend.display_name)
# When not logged in a POST should error
- post :make_friend, {:display_name => friend.display_name}
+ post :make_friend, :display_name => friend.display_name
assert_response :forbidden
assert_nil Friend.where(:user_id => user.id, :friend_user_id => friend.id).first
# When logged in a GET should get a confirmation page
- get :make_friend, {:display_name => friend.display_name}, {"user" => user}
+ get :make_friend, { :display_name => friend.display_name }, { "user" => user }
assert_response :success
assert_template :make_friend
assert_select "form" do
assert_nil Friend.where(:user_id => user.id, :friend_user_id => friend.id).first
# The GET should preserve any referer
- get :make_friend, {:display_name => friend.display_name, :referer => "/test"}, {"user" => user}
+ get :make_friend, { :display_name => friend.display_name, :referer => "/test" }, { "user" => user }
assert_response :success
assert_template :make_friend
assert_select "form" do
# When logged in a POST should add the friendship
assert_difference('ActionMailer::Base.deliveries.size', 1) do
- post :make_friend, {:display_name => friend.display_name}, {"user" => user}
+ post :make_friend, { :display_name => friend.display_name }, { "user" => user }
end
assert_redirected_to user_path(:display_name => friend.display_name)
assert_match /is now your friend/, flash[:notice]
# A second POST should report that the friendship already exists
assert_no_difference('ActionMailer::Base.deliveries.size') do
- post :make_friend, {:display_name => friend.display_name}, {"user" => user}
+ post :make_friend, { :display_name => friend.display_name }, { "user" => user }
end
assert_redirected_to user_path(:display_name => friend.display_name)
assert_match /You are already friends with/, flash[:warning]
assert Friend.where(:user_id => user.id, :friend_user_id => friend.id).first
# When not logged in a GET should ask us to login
- get :remove_friend, {:display_name => friend.display_name}
+ get :remove_friend, :display_name => friend.display_name
assert_redirected_to :controller => :user, :action => "login", :referer => remove_friend_path(:display_name => friend.display_name)
# When not logged in a POST should error
- post :remove_friend, {:display_name => friend.display_name}
+ post :remove_friend, :display_name => friend.display_name
assert_response :forbidden
assert Friend.where(:user_id => user.id, :friend_user_id => friend.id).first
# When logged in a GET should get a confirmation page
- get :remove_friend, {:display_name => friend.display_name}, {"user" => user}
+ get :remove_friend, { :display_name => friend.display_name }, { "user" => user }
assert_response :success
assert_template :remove_friend
assert_select "form" do
assert Friend.where(:user_id => user.id, :friend_user_id => friend.id).first
# The GET should preserve any referer
- get :remove_friend, {:display_name => friend.display_name, :referer => "/test"}, {"user" => user}
+ get :remove_friend, { :display_name => friend.display_name, :referer => "/test" }, { "user" => user }
assert_response :success
assert_template :remove_friend
assert_select "form" do
assert Friend.where(:user_id => user.id, :friend_user_id => friend.id).first
# When logged in a POST should remove the friendship
- post :remove_friend, {:display_name => friend.display_name}, {"user" => user}
+ post :remove_friend, { :display_name => friend.display_name }, { "user" => user }
assert_redirected_to user_path(:display_name => friend.display_name)
assert_match /was removed from your friends/, flash[:notice]
assert_nil Friend.where(:user_id => user.id, :friend_user_id => friend.id).first
# A second POST should report that the friendship does not exist
- post :remove_friend, {:display_name => friend.display_name}, {"user" => user}
+ post :remove_friend, { :display_name => friend.display_name }, { "user" => user }
assert_redirected_to user_path(:display_name => friend.display_name)
assert_match /is not one of your friends/, flash[:error]
assert_nil Friend.where(:user_id => user.id, :friend_user_id => friend.id).first
def test_set_status
# Try without logging in
- get :set_status, {:display_name => users(:normal_user).display_name, :status => "suspended"}
+ get :set_status, :display_name => users(:normal_user).display_name, :status => "suspended"
assert_response :redirect
assert_redirected_to :action => :login, :referer => set_status_user_path(:status => "suspended")
# Now try as a normal user
- get :set_status, {:display_name => users(:normal_user).display_name, :status => "suspended"}, {:user => users(:normal_user).id}
+ get :set_status, { :display_name => users(:normal_user).display_name, :status => "suspended" }, { :user => users(:normal_user).id }
assert_response :redirect
assert_redirected_to :action => :view, :display_name => users(:normal_user).display_name
# Finally try as an administrator
- get :set_status, {:display_name => users(:normal_user).display_name, :status => "suspended"}, {:user => users(:administrator_user).id}
+ get :set_status, { :display_name => users(:normal_user).display_name, :status => "suspended" }, { :user => users(:administrator_user).id }
assert_response :redirect
assert_redirected_to :action => :view, :display_name => users(:normal_user).display_name
assert_equal "suspended", User.find(users(:normal_user).id).status
def test_delete
# Try without logging in
- get :delete, {:display_name => users(:normal_user).display_name, :status => "suspended"}
+ get :delete, :display_name => users(:normal_user).display_name, :status => "suspended"
assert_response :redirect
assert_redirected_to :action => :login, :referer => delete_user_path(:status => "suspended")
# Now try as a normal user
- get :delete, {:display_name => users(:normal_user).display_name, :status => "suspended"}, {:user => users(:normal_user).id}
+ get :delete, { :display_name => users(:normal_user).display_name, :status => "suspended" }, { :user => users(:normal_user).id }
assert_response :redirect
assert_redirected_to :action => :view, :display_name => users(:normal_user).display_name
# Finally try as an administrator
- get :delete, {:display_name => users(:normal_user).display_name, :status => "suspended"}, {:user => users(:administrator_user).id}
+ get :delete, { :display_name => users(:normal_user).display_name, :status => "suspended" }, { :user => users(:administrator_user).id }
assert_response :redirect
assert_redirected_to :action => :view, :display_name => users(:normal_user).display_name
session[:user] = users(:administrator_user).id
UserRole::ALL_ROLES.each do |role|
-
# Granting a role to a non-existent user should fail
assert_difference "UserRole.count", 0 do
post :grant, :display_name => "non_existent_user", :role => role
end
assert_redirected_to user_path(users(:normal_user).display_name)
assert_equal "The user already has role #{role}.", flash[:error]
-
end
# Granting a non-existent role should fail
session[:user] = users(:administrator_user).id
UserRole::ALL_ROLES.each do |role|
-
# Removing a role from a non-existent user should fail
assert_difference "UserRole.count", 0 do
post :revoke, :display_name => "non_existent_user", :role => role
end
assert_redirected_to user_path(users(:super_user).display_name)
assert_equal "The user does not have role #{role}.", flash[:error]
-
end
# Revoking a non-existent role should fail
put :create
# hope for success
assert_response :forbidden,
- "way upload did not return success status"
+ "way upload did not return success status"
# read id of created way and search for it
wayid = @response.body
put :create
# hope for success
assert_response :success,
- "way upload did not return success status"
+ "way upload did not return success status"
# read id of created way and search for it
wayid = @response.body
checkway = Way.find(wayid)
assert_not_nil checkway,
- "uploaded way not found in data base after upload"
+ "uploaded way not found in data base after upload"
# compare values
assert_equal checkway.nds.length, 2,
- "saved way does not contain exactly one node"
+ "saved way does not contain exactly one node"
assert_equal checkway.nds[0], nid1,
- "saved way does not contain the right node on pos 0"
+ "saved way does not contain the right node on pos 0"
assert_equal checkway.nds[1], nid2,
- "saved way does not contain the right node on pos 1"
+ "saved way does not contain the right node on pos 1"
assert_equal checkway.changeset_id, changeset_id,
- "saved way does not belong to the correct changeset"
+ "saved way does not belong to the correct changeset"
assert_equal users(:public_user).id, checkway.changeset.user_id,
- "saved way does not belong to user that created it"
+ "saved way does not belong to user that created it"
assert_equal true, checkway.visible,
- "saved way is not visible"
+ "saved way is not visible"
end
# -------------------------------------
put :create
# expect failure
assert_response :forbidden,
- "way upload with invalid node using a private user did not return 'forbidden'"
+ "way upload with invalid node using a private user did not return 'forbidden'"
# create a way with no nodes
content "<osm><way changeset='#{open_changeset_id}'>" +
put :create
# expect failure
assert_response :forbidden,
- "way upload with no node using a private userdid not return 'forbidden'"
+ "way upload with no node using a private userdid not return 'forbidden'"
# create a way inside a closed changeset
content "<osm><way changeset='#{closed_changeset_id}'>" +
put :create
# expect failure
assert_response :forbidden,
- "way upload to closed changeset with a private user did not return 'forbidden'"
-
+ "way upload to closed changeset with a private user did not return 'forbidden'"
## Now test with a public user
basic_authorization users(:public_user).email, "test"
put :create
# expect failure
assert_response :precondition_failed,
- "way upload with invalid node did not return 'precondition failed'"
+ "way upload with invalid node did not return 'precondition failed'"
assert_equal "Precondition failed: Way requires the nodes with id in (0), which either do not exist, or are not visible.", @response.body
# create a way with no nodes
put :create
# expect failure
assert_response :precondition_failed,
- "way upload with no node did not return 'precondition failed'"
+ "way upload with no node did not return 'precondition failed'"
assert_equal "Precondition failed: Cannot create way: data is invalid.", @response.body
# create a way inside a closed changeset
put :create
# expect failure
assert_response :conflict,
- "way upload to closed changeset did not return 'conflict'"
+ "way upload to closed changeset did not return 'conflict'"
# create a way with a tag which is too long
content "<osm><way changeset='#{open_changeset_id}'>" +
"<nd ref='#{nid1}'/>" +
- "<tag k='foo' v='#{'x'*256}'/>" +
+ "<tag k='foo' v='#{'x' * 256}'/>" +
"</way></osm>"
put :create
# expect failure
assert_response :bad_request,
- "way upload to with too long tag did not return 'bad_request'"
+ "way upload to with too long tag did not return 'bad_request'"
end
# -------------------------------------
assert_response :unauthorized
# now set auth using the private user
- basic_authorization(users(:normal_user).email, "test");
+ basic_authorization(users(:normal_user).email, "test")
# this shouldn't work as with the 0.6 api we need pay load to delete
delete :delete, :id => current_ways(:visible_way).id
assert_response :forbidden
# try to delete with an invalid (non-existent) changeset
- content update_changeset(current_ways(:visible_way).to_xml,0)
+ content update_changeset(current_ways(:visible_way).to_xml, 0)
delete :delete, :id => current_ways(:visible_way).id
assert_response :forbidden
# check the returned value - should be the new version number
# valid delete should return the new version number, which should
# be greater than the old version number
- #assert @response.body.to_i > current_ways(:visible_way).version,
+ # assert @response.body.to_i > current_ways(:visible_way).version,
# "delete request should return a new version number for way"
# this won't work since the way is already deleted
content current_ways(:used_way).to_xml
delete :delete, :id => current_ways(:used_way).id
assert_response :forbidden,
- "shouldn't be able to delete a way used in a relation (#{@response.body}), when done by a private user"
+ "shouldn't be able to delete a way used in a relation (#{@response.body}), when done by a private user"
# this won't work since the way never existed
delete :delete, :id => 0
assert_response :forbidden
-
### Now check with a public user
# now set auth
- basic_authorization(users(:public_user).email, "test");
+ basic_authorization(users(:public_user).email, "test")
# this shouldn't work as with the 0.6 api we need pay load to delete
delete :delete, :id => current_ways(:visible_way).id
assert_response :conflict
# try to delete with an invalid (non-existent) changeset
- content update_changeset(current_ways(:visible_way).to_xml,0)
+ content update_changeset(current_ways(:visible_way).to_xml, 0)
delete :delete, :id => current_ways(:visible_way).id
assert_response :conflict
# valid delete should return the new version number, which should
# be greater than the old version number
assert @response.body.to_i > current_ways(:visible_way).version,
- "delete request should return a new version number for way"
+ "delete request should return a new version number for way"
# this won't work since the way is already deleted
content current_ways(:invisible_way).to_xml
content current_ways(:used_way).to_xml
delete :delete, :id => current_ways(:used_way).id
assert_response :precondition_failed,
- "shouldn't be able to delete a way used in a relation (#{@response.body})"
+ "shouldn't be able to delete a way used in a relation (#{@response.body})"
assert_equal "Precondition failed: Way 3 is still used by relations 1.", @response.body
# this won't work since the way never existed
content way_xml
put :update, :id => current_ways(:visible_way).id
assert_response :forbidden,
- "adding a duplicate tag to a way for a non-public should fail with 'forbidden'"
+ "adding a duplicate tag to a way for a non-public should fail with 'forbidden'"
## Now try with the public user
# setup auth
content way_xml
put :update, :id => current_ways(:visible_way).id
assert_response :bad_request,
- "adding a duplicate tag to a way should fail with 'bad request'"
+ "adding a duplicate tag to a way should fail with 'bad request'"
assert_equal "Element way/#{current_ways(:visible_way).id} has duplicate tags with key #{current_way_tags(:t1).k}", @response.body
end
content way_xml
put :update, :id => current_ways(:visible_way).id
assert_response :forbidden,
- "adding new duplicate tags to a way using a non-public user should fail with 'forbidden'"
+ "adding new duplicate tags to a way using a non-public user should fail with 'forbidden'"
## Now test with the public user
# setup auth
content way_xml
put :update, :id => current_ways(:visible_way).id
assert_response :bad_request,
- "adding new duplicate tags to a way should fail with 'bad request'"
+ "adding new duplicate tags to a way should fail with 'bad request'"
assert_equal "Element way/#{current_ways(:visible_way).id} has duplicate tags with key i_am_a_duplicate", @response.body
-
end
##
way_str = "<osm><way changeset='1'>"
way_str << "<tag k='addr:housenumber' v='1'/>"
way_str << "<tag k='addr:housenumber' v='2'/>"
- way_str << "</way></osm>";
+ way_str << "</way></osm>"
# try and upload it
content way_str
put :create
assert_response :forbidden,
- "adding new duplicate tags to a way with a non-public user should fail with 'forbidden'"
+ "adding new duplicate tags to a way with a non-public user should fail with 'forbidden'"
## Now do it with a public user
# setup auth
way_str = "<osm><way changeset='1'>"
way_str << "<tag k='addr:housenumber' v='1'/>"
way_str << "<tag k='addr:housenumber' v='2'/>"
- way_str << "</way></osm>";
+ way_str << "</way></osm>"
# try and upload it
content way_str
put :create
assert_response :bad_request,
- "adding new duplicate tags to a way should fail with 'bad request'"
+ "adding new duplicate tags to a way should fail with 'bad request'"
assert_equal "Element way/ has duplicate tags with key addr:housenumber", @response.body
end
assert_not_nil ways_xml, "failed to parse ways_for_node response"
# check that the set of IDs match expectations
- expected_way_ids = [ current_ways(:visible_way).id,
- current_ways(:used_way).id
+ expected_way_ids = [current_ways(:visible_way).id,
+ current_ways(:used_way).id
]
found_way_ids = ways_xml.find("//osm/way").collect { |w| w["id"].to_i }
assert_equal expected_way_ids.sort, found_way_ids.sort,
- "expected ways for node #{current_nodes(:used_node_1).id} did not match found"
+ "expected ways for node #{current_nodes(:used_node_1).id} did not match found"
# check the full ways to ensure we're not missing anything
expected_way_ids.each do |id|
# update an attribute in the node element
def xml_attr_rewrite(xml, name, value)
xml.find("//osm/way").first[name] = value.to_s
- return xml
+ xml
end
end
class AssetHelperTest < ActionView::TestCase
def test_assets
- assert assets("iD").kind_of?(Hash)
+ assert assets("iD").is_a?(Hash)
end
end
def test_icon_tags
tags = icon_tags(current_nodes(:node_with_name))
assert_equal 3, tags.count
- assert tags.include?(["building", "yes"])
- assert tags.include?(["tourism", "museum"])
- assert tags.include?(["shop", "gift"])
+ assert tags.include?(%w(building yes))
+ assert tags.include?(%w(tourism museum))
+ assert tags.include?(%w(shop gift))
tags = icon_tags(nodes(:node_with_name_current_version))
assert_equal 3, tags.count
- assert tags.include?(["building", "yes"])
- assert tags.include?(["tourism", "museum"])
- assert tags.include?(["shop", "gift"])
+ assert tags.include?(%w(building yes))
+ assert tags.include?(%w(tourism museum))
+ assert tags.include?(%w(shop gift))
tags = icon_tags(nodes(:node_with_name_redacted_version))
assert_equal 3, tags.count
- assert tags.include?(["building", "yes"])
- assert tags.include?(["tourism", "museum"])
- assert tags.include?(["shop", "gift"])
+ assert tags.include?(%w(building yes))
+ assert tags.include?(%w(tourism museum))
+ assert tags.include?(%w(shop gift))
end
def test_wiki_link
assert_redirected_to "controller" => "user", "action" => "login", "cookie_test" => "true"
follow_redirect!
assert_response :success
- post '/login', {'username' => "test@example.com", 'password' => "test", :referer => '/user/test2'}
+ post '/login', 'username' => "test@example.com", 'password' => "test", :referer => '/user/test2'
assert_response :redirect
follow_redirect!
assert_response :success
end
assert_in_body do
assert_select "form[action='/user/test2/oauth_clients']" do
- [ :name, :url, :callback_url, :support_url ].each do |inp|
+ [:name, :url, :callback_url, :support_url].each do |inp|
assert_select "input[name=?]", "client_application[#{inp}]"
end
ClientApplication.all_permissions.each do |perm|
end
end
- post '/user/test2/oauth_clients', {
- 'client_application[name]' => 'My New App',
- 'client_application[url]' => 'http://my.new.app.org/',
- 'client_application[callback_url]' => 'http://my.new.app.org/callback',
- 'client_application[support_url]' => 'http://my.new.app.org/support'}
+ post '/user/test2/oauth_clients', 'client_application[name]' => 'My New App',
+ 'client_application[url]' => 'http://my.new.app.org/',
+ 'client_application[callback_url]' => 'http://my.new.app.org/callback',
+ 'client_application[support_url]' => 'http://my.new.app.org/support'
assert_response :redirect
follow_redirect!
assert_response :success
client = client_applications(:oauth_web_app)
post_via_redirect "/login",
- :username => client.user.email, :password => "test"
+ :username => client.user.email, :password => "test"
assert_response :success
signed_get "/oauth/request_token", :consumer => client
assert_allowed token, client.permissions
post "/oauth/authorize",
- :oauth_token => token.token,
- :allow_read_prefs => true, :allow_write_prefs => true
+ :oauth_token => token.token,
+ :allow_read_prefs => true, :allow_write_prefs => true
assert_response :redirect
assert_redirected_to "http://some.web.app.org/callback?oauth_token=#{token.token}"
token.reload
assert_not_nil token.created_at
assert_not_nil token.authorized_at
assert_nil token.invalidated_at
- assert_allowed token, [ :allow_read_prefs ]
+ assert_allowed token, [:allow_read_prefs]
signed_get "/oauth/access_token", :consumer => client, :token => token
assert_response :success
assert_not_nil token.created_at
assert_not_nil token.authorized_at
assert_nil token.invalidated_at
- assert_allowed token, [ :allow_read_prefs ]
+ assert_allowed token, [:allow_read_prefs]
signed_get "/api/0.6/user/preferences", :consumer => client, :token => token
assert_response :success
assert_allowed token, client.permissions
post "/oauth/authorize",
- :oauth_token => token.token,
- :oauth_callback => "http://another.web.app.org/callback",
- :allow_write_api => true, :allow_read_gpx => true
+ :oauth_token => token.token,
+ :oauth_callback => "http://another.web.app.org/callback",
+ :allow_write_api => true, :allow_read_gpx => true
assert_response :redirect
assert_redirected_to "http://another.web.app.org/callback?oauth_token=#{token.token}"
token.reload
assert_not_nil token.created_at
assert_not_nil token.authorized_at
assert_nil token.invalidated_at
- assert_allowed token, [ :allow_write_api, :allow_read_gpx ]
+ assert_allowed token, [:allow_write_api, :allow_read_gpx]
signed_get "/oauth/access_token", :consumer => client, :token => token
assert_response :success
assert_not_nil token.created_at
assert_not_nil token.authorized_at
assert_nil token.invalidated_at
- assert_allowed token, [ :allow_write_api, :allow_read_gpx ]
+ assert_allowed token, [:allow_write_api, :allow_read_gpx]
signed_get "/api/0.6/gpx/2", :consumer => client, :token => token
assert_response :success
client = client_applications(:oauth_desktop_app)
post_via_redirect "/login",
- :username => client.user.email, :password => "test"
+ :username => client.user.email, :password => "test"
assert_response :success
signed_get "/oauth/request_token", :consumer => client
assert_allowed token, client.permissions
post "/oauth/authorize",
- :oauth_token => token.token,
- :allow_read_prefs => true, :allow_write_prefs => true
+ :oauth_token => token.token,
+ :allow_read_prefs => true, :allow_write_prefs => true
assert_response :success
assert_template "authorize_success"
token.reload
assert_not_nil token.created_at
assert_not_nil token.authorized_at
assert_nil token.invalidated_at
- assert_allowed token, [ :allow_read_prefs ]
+ assert_allowed token, [:allow_read_prefs]
signed_get "/oauth/access_token", :consumer => client, :token => token
assert_response :success
assert_not_nil token.created_at
assert_not_nil token.authorized_at
assert_nil token.invalidated_at
- assert_allowed token, [ :allow_read_prefs ]
+ assert_allowed token, [:allow_read_prefs]
signed_get "/api/0.6/user/preferences", :consumer => client, :token => token
assert_response :success
client = client_applications(:oauth_web_app)
post_via_redirect "/login",
- :username => client.user.email, :password => "test"
+ :username => client.user.email, :password => "test"
assert_response :success
signed_get "/oauth/request_token",
- :consumer => client, :oauth_callback => "oob"
+ :consumer => client, :oauth_callback => "oob"
assert_response :success
token = parse_token(response)
assert_instance_of RequestToken, token
assert_allowed token, client.permissions
post "/oauth/authorize",
- :oauth_token => token.token,
- :allow_read_prefs => true, :allow_write_prefs => true
+ :oauth_token => token.token,
+ :allow_read_prefs => true, :allow_write_prefs => true
assert_response :redirect
verifier = parse_verifier(response)
assert_redirected_to "http://some.web.app.org/callback?oauth_token=#{token.token}&oauth_verifier=#{verifier}"
assert_not_nil token.created_at
assert_not_nil token.authorized_at
assert_nil token.invalidated_at
- assert_allowed token, [ :allow_read_prefs ]
+ assert_allowed token, [:allow_read_prefs]
signed_get "/oauth/access_token", :consumer => client, :token => token
assert_response :unauthorized
signed_get "/oauth/access_token",
- :consumer => client, :token => token, :oauth_verifier => verifier
+ :consumer => client, :token => token, :oauth_verifier => verifier
assert_response :success
token.reload
assert_not_nil token.created_at
assert_not_nil token.created_at
assert_not_nil token.authorized_at
assert_nil token.invalidated_at
- assert_allowed token, [ :allow_read_prefs ]
+ assert_allowed token, [:allow_read_prefs]
signed_get "/api/0.6/user/preferences", :consumer => client, :token => token
assert_response :success
assert_response :unauthorized
signed_get "/oauth/request_token",
- :consumer => client,
- :oauth_callback => "http://another.web.app.org/callback"
+ :consumer => client,
+ :oauth_callback => "http://another.web.app.org/callback"
assert_response :success
token = parse_token(response)
assert_instance_of RequestToken, token
assert_allowed token, client.permissions
post "/oauth/authorize",
- :oauth_token => token.token,
- :allow_write_api => true, :allow_read_gpx => true
+ :oauth_token => token.token,
+ :allow_write_api => true, :allow_read_gpx => true
assert_response :redirect
verifier = parse_verifier(response)
assert_redirected_to "http://another.web.app.org/callback?oauth_token=#{token.token}&oauth_verifier=#{verifier}"
assert_not_nil token.created_at
assert_not_nil token.authorized_at
assert_nil token.invalidated_at
- assert_allowed token, [ :allow_write_api, :allow_read_gpx ]
+ assert_allowed token, [:allow_write_api, :allow_read_gpx]
signed_get "/oauth/access_token", :consumer => client, :token => token
assert_response :unauthorized
signed_get "/oauth/access_token",
- :consumer => client, :token => token, :oauth_verifier => verifier
+ :consumer => client, :token => token, :oauth_verifier => verifier
assert_response :success
token.reload
assert_not_nil token.created_at
assert_not_nil token.created_at
assert_not_nil token.authorized_at
assert_nil token.invalidated_at
- assert_allowed token, [ :allow_write_api, :allow_read_gpx ]
+ assert_allowed token, [:allow_write_api, :allow_read_gpx]
signed_get "/api/0.6/gpx/2", :consumer => client, :token => token
assert_response :success
client = client_applications(:oauth_desktop_app)
post_via_redirect "/login",
- :username => client.user.email, :password => "test"
+ :username => client.user.email, :password => "test"
assert_response :success
signed_get "/oauth/request_token",
- :consumer => client, :oauth_callback => "oob"
+ :consumer => client, :oauth_callback => "oob"
assert_response :success
token = parse_token(response)
assert_instance_of RequestToken, token
assert_allowed token, client.permissions
post "/oauth/authorize",
- :oauth_token => token.token,
- :allow_read_prefs => true, :allow_write_prefs => true
+ :oauth_token => token.token,
+ :allow_read_prefs => true, :allow_write_prefs => true
assert_response :success
assert_template "authorize_success"
m = response.body.match("<p>The verification code is ([A-Za-z0-9]+).</p>")
assert_not_nil token.created_at
assert_not_nil token.authorized_at
assert_nil token.invalidated_at
- assert_allowed token, [ :allow_read_prefs ]
+ assert_allowed token, [:allow_read_prefs]
signed_get "/oauth/access_token", :consumer => client, :token => token
assert_response :unauthorized
signed_get "/oauth/access_token",
- :consumer => client, :token => token, :oauth_verifier => verifier
+ :consumer => client, :token => token, :oauth_verifier => verifier
assert_response :success
token.reload
assert_not_nil token.created_at
assert_not_nil token.created_at
assert_not_nil token.authorized_at
assert_nil token.invalidated_at
- assert_allowed token, [ :allow_read_prefs ]
+ assert_allowed token, [:allow_read_prefs]
signed_get "/api/0.6/user/preferences", :consumer => client, :token => token
assert_response :success
assert_response :unauthorized
end
-private
+ private
def signed_get(uri, options)
uri = URI.parse(uri)
# kept in the redirect.
def test_short_link_params
assert_short_link_redirect('1N8H@P_5W')
- assert_short_link_redirect(ShortLink::encode(-0.107846, 51.50771, 18))
+ assert_short_link_redirect(ShortLink.encode(-0.107846, 51.50771, 18))
end
##
# utility method to test short links
def assert_short_link_redirect(short_link)
- lon, lat, zoom = ShortLink::decode(short_link)
+ lon, lat, zoom = ShortLink.decode(short_link)
anchor = "map=#{zoom}/#{lat}/#{lon}"
# test without marker
fixtures :users, :user_blocks, :user_roles
def auth_header(user, pass)
- {"HTTP_AUTHORIZATION" => "Basic %s" % Base64.encode64("#{user}:#{pass}")}
+ { "HTTP_AUTHORIZATION" => "Basic %s" % Base64.encode64("#{user}:#{pass}") }
end
def test_api_blocked
# revoke the ban
get '/login'
assert_response :success
- post '/login', {'username' => moderator.email, 'password' => "test", :referer => "/blocks/#{block.id}/revoke"}
+ post '/login', 'username' => moderator.email, 'password' => "test", :referer => "/blocks/#{block.id}/revoke"
assert_response :redirect
follow_redirect!
assert_response :success
assert_template 'user_blocks/revoke'
- post "/blocks/#{block.id}/revoke", {'confirm' => "yes"}
+ post "/blocks/#{block.id}/revoke", 'confirm' => "yes"
assert_response :redirect
follow_redirect!
assert_response :success
assert_response :success
assert_template 'user/login'
# We can now login
- post '/login', {'username' => "test@openstreetmap.org", 'password' => "test"}
+ post '/login', 'username' => "test@openstreetmap.org", 'password' => "test"
assert_response :redirect
get "/changeset/#{changesets(:normal_user_closed_change).id}"
def test_create_user_form
I18n.available_locales.each do |locale|
- get_via_redirect '/user/new', {}, {"HTTP_ACCEPT_LANGUAGE" => locale.to_s}
+ get_via_redirect '/user/new', {}, { "HTTP_ACCEPT_LANGUAGE" => locale.to_s }
assert_response :success
assert_template 'user/new'
end
def test_user_create_submit_duplicate_email
I18n.available_locales.each do |locale|
dup_email = users(:public_user).email
- display_name = "#{locale.to_s}_new_tester"
+ display_name = "#{locale}_new_tester"
assert_difference('User.count', 0) do
assert_difference('ActionMailer::Base.deliveries.size', 0) do
post '/user/new',
- {:user => { :email => dup_email, :email_confirmation => dup_email, :display_name => display_name, :pass_crypt => "testtest", :pass_crypt_confirmation => "testtest"}},
- {"HTTP_ACCEPT_LANGUAGE" => locale.to_s}
+ { :user => { :email => dup_email, :email_confirmation => dup_email, :display_name => display_name, :pass_crypt => "testtest", :pass_crypt_confirmation => "testtest" } },
+ { "HTTP_ACCEPT_LANGUAGE" => locale.to_s }
end
end
assert_response :success
def test_user_create_submit_duplicate_username
I18n.available_locales.each do |locale|
dup_display_name = users(:public_user).display_name
- email = "#{locale.to_s}_new_tester"
+ email = "#{locale}_new_tester"
assert_difference('User.count', 0) do
assert_difference('ActionMailer::Base.deliveries.size', 0) do
post '/user/new',
- {:user => {:email => email, :email_confirmation => email, :display_name => dup_display_name, :pass_crypt => "testtest", :pass_crypt_confirmation => "testtest"}},
- {"HTTP_ACCEPT_LANGUAGE" => locale.to_s}
+ { :user => { :email => email, :email_confirmation => email, :display_name => dup_display_name, :pass_crypt => "testtest", :pass_crypt_confirmation => "testtest" } },
+ { "HTTP_ACCEPT_LANGUAGE" => locale.to_s }
end
end
assert_response :success
def test_user_create_success
I18n.available_locales.each do |locale|
- new_email = "#{locale.to_s}newtester@osm.org"
- display_name = "#{locale.to_s}_new_tester"
+ new_email = "#{locale}newtester@osm.org"
+ display_name = "#{locale}_new_tester"
assert_difference('User.count', 0) do
assert_difference('ActionMailer::Base.deliveries.size', 0) do
post "/user/new",
- {:user => { :email => new_email, :email_confirmation => new_email, :display_name => display_name, :pass_crypt => "testtest", :pass_crypt_confirmation => "testtest"}}
- end
+ :user => { :email => new_email, :email_confirmation => new_email, :display_name => display_name, :pass_crypt => "testtest", :pass_crypt_confirmation => "testtest" }
+ end
end
assert_redirected_to "/user/terms"
assert_difference('User.count') do
assert_difference('ActionMailer::Base.deliveries.size', 1) do
post_via_redirect "/user/save", {},
- {"HTTP_ACCEPT_LANGUAGE" => "#{locale.to_s}"}
+ { "HTTP_ACCEPT_LANGUAGE" => "#{locale}" }
end
end
assert_difference('User.count') do
assert_difference('ActionMailer::Base.deliveries.size', 1) do
post "/user/new",
- {:user => { :email => new_email, :email_confirmation => new_email, :display_name => display_name, :pass_crypt => password, :pass_crypt_confirmation => password}, :referer => referer }
+ :user => { :email => new_email, :email_confirmation => new_email, :display_name => display_name, :pass_crypt => password, :pass_crypt_confirmation => password }, :referer => referer
assert_redirected_to "/user/terms"
post_via_redirect "/user/save",
- {:user => { :email => new_email, :email_confirmation => new_email, :display_name => display_name, :pass_crypt => password, :pass_crypt_confirmation => password} }
+ :user => { :email => new_email, :email_confirmation => new_email, :display_name => display_name, :pass_crypt => password, :pass_crypt_confirmation => password }
end
end
ActionMailer::Base.deliveries.clear
# Go to the confirmation page
- get "/user/#{display_name}/confirm", { :confirm_string => confirm_string }
+ get "/user/#{display_name}/confirm", :confirm_string => confirm_string
assert_response :success
assert_template 'user/confirm'
- post "/user/#{display_name}/confirm", { :confirm_string => confirm_string }
+ post "/user/#{display_name}/confirm", :confirm_string => confirm_string
assert_response :redirect
follow_redirect!
assert_response :success
assert_difference('User.count') do
assert_difference('ActionMailer::Base.deliveries.size', 1) do
post "/user/new",
- {:user => { :email => new_email, :email_confirmation => new_email, :display_name => display_name, :openid_url => "http://localhost:1123/john.doe?openid.success=newuser", :pass_crypt => "", :pass_crypt_confirmation => ""}}
+ :user => { :email => new_email, :email_confirmation => new_email, :display_name => display_name, :openid_url => "http://localhost:1123/john.doe?openid.success=newuser", :pass_crypt => "", :pass_crypt_confirmation => "" }
assert_response :redirect
res = openid_request(@response.redirect_url)
get "/user/new", res
assert_redirected_to "/user/terms"
post '/user/save',
- {:user => { :email => new_email, :email_confirmation => new_email, :display_name => display_name, :openid_url => "http://localhost:1123/john.doe?openid.success=newuser", :pass_crypt => password, :pass_crypt_confirmation => password}}
+ :user => { :email => new_email, :email_confirmation => new_email, :display_name => display_name, :openid_url => "http://localhost:1123/john.doe?openid.success=newuser", :pass_crypt => password, :pass_crypt_confirmation => password }
assert_response :redirect
follow_redirect!
end
new_email = "newtester-openid2@osm.org"
display_name = "new_tester-openid2"
password = "testtest2"
- assert_difference('User.count',0) do
- assert_difference('ActionMailer::Base.deliveries.size',0) do
+ assert_difference('User.count', 0) do
+ assert_difference('ActionMailer::Base.deliveries.size', 0) do
post "/user/new",
- {:user => { :email => new_email, :email_confirmation => new_email, :display_name => display_name, :openid_url => "http://localhost:1123/john.doe?openid.failure=newuser", :pass_crypt => "", :pass_crypt_confirmation => ""}}
+ :user => { :email => new_email, :email_confirmation => new_email, :display_name => display_name, :openid_url => "http://localhost:1123/john.doe?openid.failure=newuser", :pass_crypt => "", :pass_crypt_confirmation => "" }
assert_response :redirect
res = openid_request(@response.redirect_url)
get '/user/new', res
assert_difference('User.count') do
assert_difference('ActionMailer::Base.deliveries.size', 1) do
post "/user/new",
- {:user => { :email => new_email, :email_confirmation => new_email, :display_name => display_name, :openid_url => "http://localhost:1123/john.doe?openid.success=newuser", :pass_crypt => "", :pass_crypt_confirmation => ""}, :referer => referer }
+ :user => { :email => new_email, :email_confirmation => new_email, :display_name => display_name, :openid_url => "http://localhost:1123/john.doe?openid.success=newuser", :pass_crypt => "", :pass_crypt_confirmation => "" }, :referer => referer
assert_response :redirect
res = openid_request(@response.location)
get "/user/new", res
assert_redirected_to "/user/terms"
post_via_redirect "/user/save",
- {:user => { :email => new_email, :email_confirmation => new_email, :display_name => display_name, :openid_url => "http://localhost:1123/john.doe?openid.success=newuser", :pass_crypt => "testtest", :pass_crypt_confirmation => "testtest"} }
+ :user => { :email => new_email, :email_confirmation => new_email, :display_name => display_name, :openid_url => "http://localhost:1123/john.doe?openid.success=newuser", :pass_crypt => "testtest", :pass_crypt_confirmation => "testtest" }
end
end
ActionMailer::Base.deliveries.clear
# Go to the confirmation page
- get "/user/#{display_name}/confirm", { :confirm_string => confirm_string }
+ get "/user/#{display_name}/confirm", :confirm_string => confirm_string
assert_response :success
assert_template 'user/confirm'
- post "/user/#{display_name}/confirm", { :confirm_string => confirm_string }
+ post "/user/#{display_name}/confirm", :confirm_string => confirm_string
assert_response :redirect
follow_redirect!
assert_response :success
assert_response :success
assert_template 'user/login'
# We can now login
- post '/login', {'username' => "test@openstreetmap.org", 'password' => "test", :referer => '/diary/new'}
+ post '/login', 'username' => "test@openstreetmap.org", 'password' => "test", :referer => '/diary/new'
assert_response :redirect
- #print @response.body
+ # print @response.body
# Check that there is some payload alerting the user to the redirect
# and allowing them to get to the page they are being directed to
assert_select "html:root" do
assert_response :success
assert_template 'diary_entry/edit'
- #print @response.body
- #print @html_document.to_yaml
+ # print @response.body
+ # print @html_document.to_yaml
# We will make sure that the form exists here, full
# assert testing of the full form should be done in the
follow_redirect!
assert_response :success
- post '/login', {'username' => user.email, 'password' => "wrong", :referer => "/history"}
+ post '/login', 'username' => user.email, 'password' => "wrong", :referer => "/history"
assert_response :redirect
follow_redirect!
assert_response :success
assert_template 'login'
- post '/login', {'username' => user.email, 'password' => "test", :referer => "/history"}
+ post '/login', 'username' => user.email, 'password' => "test", :referer => "/history"
assert_response :redirect
follow_redirect!
assert_response :success
follow_redirect!
assert_response :success
- post '/login', {'username' => user.email.upcase, 'password' => "wrong", :referer => "/history"}
+ post '/login', 'username' => user.email.upcase, 'password' => "wrong", :referer => "/history"
assert_response :redirect
follow_redirect!
assert_response :success
assert_template 'login'
- post '/login', {'username' => user.email.upcase, 'password' => "test", :referer => "/history"}
+ post '/login', 'username' => user.email.upcase, 'password' => "test", :referer => "/history"
assert_response :redirect
follow_redirect!
assert_response :success
follow_redirect!
assert_response :success
- post '/login', {'username' => user.email.titlecase, 'password' => "wrong", :referer => "/history"}
+ post '/login', 'username' => user.email.titlecase, 'password' => "wrong", :referer => "/history"
assert_response :redirect
follow_redirect!
assert_response :success
assert_template 'login'
- post '/login', {'username' => user.email.titlecase, 'password' => "test", :referer => "/history"}
+ post '/login', 'username' => user.email.titlecase, 'password' => "test", :referer => "/history"
assert_response :redirect
follow_redirect!
assert_response :success
follow_redirect!
assert_response :success
- post '/login', {'username' => user.email, 'password' => "wrong", :referer => "/history"}
+ post '/login', 'username' => user.email, 'password' => "wrong", :referer => "/history"
assert_response :redirect
follow_redirect!
assert_response :success
assert_template 'login'
- post '/login', {'username' => user.email, 'password' => "test", :referer => "/history"}
+ post '/login', 'username' => user.email, 'password' => "test", :referer => "/history"
assert_response :redirect
follow_redirect!
assert_response :success
follow_redirect!
assert_response :success
- post '/login', {'username' => user.email.upcase, 'password' => "wrong", :referer => "/history"}
+ post '/login', 'username' => user.email.upcase, 'password' => "wrong", :referer => "/history"
assert_response :redirect
follow_redirect!
assert_response :success
assert_template 'login'
- post '/login', {'username' => user.email.upcase, 'password' => "test", :referer => "/history"}
+ post '/login', 'username' => user.email.upcase, 'password' => "test", :referer => "/history"
assert_response :redirect
follow_redirect!
assert_response :success
follow_redirect!
assert_response :success
- post '/login', {'username' => user.email.titlecase, 'password' => "wrong", :referer => "/history"}
+ post '/login', 'username' => user.email.titlecase, 'password' => "wrong", :referer => "/history"
assert_response :redirect
follow_redirect!
assert_response :success
assert_template 'login'
- post '/login', {'username' => user.email.titlecase, 'password' => "test", :referer => "/history"}
+ post '/login', 'username' => user.email.titlecase, 'password' => "test", :referer => "/history"
assert_response :redirect
follow_redirect!
assert_response :success
follow_redirect!
assert_response :success
- post '/login', {'username' => user.display_name, 'password' => "wrong", :referer => "/history"}
+ post '/login', 'username' => user.display_name, 'password' => "wrong", :referer => "/history"
assert_response :redirect
follow_redirect!
assert_response :success
assert_template 'login'
- post '/login', {'username' => user.display_name, 'password' => "test", :referer => "/history"}
+ post '/login', 'username' => user.display_name, 'password' => "test", :referer => "/history"
assert_response :redirect
follow_redirect!
assert_response :success
follow_redirect!
assert_response :success
- post '/login', {'username' => user.display_name.upcase, 'password' => "wrong", :referer => "/history"}
+ post '/login', 'username' => user.display_name.upcase, 'password' => "wrong", :referer => "/history"
assert_response :redirect
follow_redirect!
assert_response :success
assert_template 'login'
- post '/login', {'username' => user.display_name.upcase, 'password' => "test", :referer => "/history"}
+ post '/login', 'username' => user.display_name.upcase, 'password' => "test", :referer => "/history"
assert_response :redirect
follow_redirect!
assert_response :success
follow_redirect!
assert_response :success
- post '/login', {'username' => user.display_name.titlecase, 'password' => "wrong", :referer => "/history"}
+ post '/login', 'username' => user.display_name.titlecase, 'password' => "wrong", :referer => "/history"
assert_response :redirect
follow_redirect!
assert_response :success
assert_template 'login'
- post '/login', {'username' => user.display_name.titlecase, 'password' => "test", :referer => "/history"}
+ post '/login', 'username' => user.display_name.titlecase, 'password' => "test", :referer => "/history"
assert_response :redirect
follow_redirect!
assert_response :success
follow_redirect!
assert_response :success
- post '/login', {'username' => user.display_name, 'password' => "wrong", :referer => "/history"}
+ post '/login', 'username' => user.display_name, 'password' => "wrong", :referer => "/history"
assert_response :redirect
follow_redirect!
assert_response :success
assert_template 'login'
- post '/login', {'username' => user.display_name, 'password' => "test", :referer => "/history"}
+ post '/login', 'username' => user.display_name, 'password' => "test", :referer => "/history"
assert_response :redirect
follow_redirect!
assert_response :success
follow_redirect!
assert_response :success
- post '/login', {'username' => user.display_name.upcase, 'password' => "wrong", :referer => "/history"}
+ post '/login', 'username' => user.display_name.upcase, 'password' => "wrong", :referer => "/history"
assert_response :redirect
follow_redirect!
assert_response :success
assert_template 'login'
- post '/login', {'username' => user.display_name.upcase, 'password' => "test", :referer => "/history"}
+ post '/login', 'username' => user.display_name.upcase, 'password' => "test", :referer => "/history"
assert_response :redirect
follow_redirect!
assert_response :success
follow_redirect!
assert_response :success
- post '/login', {'username' => user.display_name.titlecase, 'password' => "wrong", :referer => "/history"}
+ post '/login', 'username' => user.display_name.titlecase, 'password' => "wrong", :referer => "/history"
assert_response :redirect
follow_redirect!
assert_response :success
assert_template 'login'
- post '/login', {'username' => user.display_name.titlecase, 'password' => "test", :referer => "/history"}
+ post '/login', 'username' => user.display_name.titlecase, 'password' => "test", :referer => "/history"
assert_response :redirect
follow_redirect!
assert_response :success
assert_redirected_to "controller" => "user", "action" => "login", "cookie_test" => "true"
follow_redirect!
assert_response :success
- post '/login', {'openid_url' => "http://localhost:1123/john.doe?openid.success=true", :referer => "/history"}
+ post '/login', 'openid_url' => "http://localhost:1123/john.doe?openid.success=true", :referer => "/history"
assert_response :redirect
res = openid_request(@response.redirect_url)
assert_redirected_to "controller" => "user", "action" => "login", "cookie_test" => "true"
follow_redirect!
assert_response :success
- post '/login', {'openid_url' => "http://localhost:1123/john.doe", :referer => "/diary"}
+ post '/login', 'openid_url' => "http://localhost:1123/john.doe", :referer => "/diary"
assert_response :redirect
res = openid_request(@response.redirect_url)
assert_redirected_to "controller" => "user", "action" => "login", "cookie_test" => "true"
follow_redirect!
assert_response :success
- #Use a different port that doesn't have the OpenID provider running on to test an invalid openID
- post '/login', {'openid_url' => "http://localhost:1124/john.doe", :referer => "/diary"}
+ # Use a different port that doesn't have the OpenID provider running on to test an invalid openID
+ post '/login', 'openid_url' => "http://localhost:1124/john.doe", :referer => "/diary"
assert_response :redirect
follow_redirect!
assert_response :success
assert_redirected_to "controller" => "user", "action" => "login", "cookie_test" => "true"
follow_redirect!
assert_response :success
- #Use a url with an invalid protocol to make sure it handles that correctly too
- post '/login', {'openid_url' => "htt://localhost:1123/john.doe", :referer => "/diary"}
+ # Use a url with an invalid protocol to make sure it handles that correctly too
+ post '/login', 'openid_url' => "htt://localhost:1123/john.doe", :referer => "/diary"
assert_response :redirect
follow_redirect!
assert_response :success
assert_redirected_to "controller" => "user", "action" => "login", "cookie_test" => "true"
follow_redirect!
assert_response :success
- post '/login', {'openid_url' => "http://localhost:1123/john.doe?openid.success=true_somethingelse", :referer => "/diary"}
+ post '/login', 'openid_url' => "http://localhost:1123/john.doe?openid.success=true_somethingelse", :referer => "/diary"
assert_response :redirect
res = openid_request(@response.redirect_url)
check_fail(:revoke, :administrator_user, :moderator)
end
-private
+ private
def check_fail(action, user, role)
get '/login'
assert_redirected_to "controller" => "user", "action" => "login", "cookie_test" => "true"
follow_redirect!
assert_response :success
- post '/login', {'username' => users(user).email, 'password' => "test", :referer => "/"}
+ post '/login', 'username' => users(user).email, 'password' => "test", :referer => "/"
assert_response :redirect
follow_redirect!
assert_response :success
assert_redirected_to "controller" => "user", "action" => "login", "cookie_test" => "true"
follow_redirect!
assert_response :success
- post '/login', {'username' => users(user).email, 'password' => "test", :referer => "/"}
+ post '/login', 'username' => users(user).email, 'password' => "test", :referer => "/"
assert_response :redirect
follow_redirect!
assert_response :success
get_via_redirect "/login"
assert_response :success
assert_template 'user/login'
- post "/login", {'username' => user.email, 'password' => 'test', :referer => "/"}
+ post "/login", 'username' => user.email, 'password' => 'test', :referer => "/"
assert_response :redirect
# but now we need to look at the terms
assert_redirected_to "controller" => "user", "action" => "terms", :referer => "/"
assert_response :success
# don't agree to the terms, but hit decline
- post "/user/save", {'decline' => 'decline', 'referer' => '/'}
+ post "/user/save", 'decline' => 'decline', 'referer' => '/'
assert_redirected_to "/"
follow_redirect!
get_via_redirect "/login"
assert_response :success
assert_template 'user/login'
- post "/login", {'username' => user.email, 'password' => 'test', :referer => "/"}
+ post "/login", 'username' => user.email, 'password' => 'test', :referer => "/"
assert_response :redirect
# but now we need to look at the terms
assert_redirected_to "controller" => "user", "action" => "terms", :referer => "/"
end
end
-private
+ private
def auth_header(user, pass)
- {"HTTP_AUTHORIZATION" => "Basic %s" % Base64.encode64("#{user}:#{pass}")}
+ { "HTTP_AUTHORIZATION" => "Basic %s" % Base64.encode64("#{user}:#{pass}") }
end
def with_terms_seen(value)
@nil_error_message = "Should not contain nil"
@bbox_from_nils = BoundingBox.new(nil, nil, nil, nil)
- @bbox_expand = BoundingBox.new(0,0,0,0)
- @bbox_expand_ten = BoundingBox.new(10,10,10,10)
- @bbox_expand_minus_two = BoundingBox.new(-2,-2,-2,-2)
+ @bbox_expand = BoundingBox.new(0, 0, 0, 0)
+ @bbox_expand_ten = BoundingBox.new(10, 10, 10, 10)
+ @bbox_expand_minus_two = BoundingBox.new(-2, -2, -2, -2)
@bbox_from_string = BoundingBox.from_s("1,2,3,4")
@min_lon = 1.0
@min_lat = 2.0
@max_lon = 3.0
@max_lat = 4.0
- @bad_positive_boundary_bbox = %w{ 181,91,0,0 0,0,181,91 }
- @bad_negative_boundary_bbox = %w{ -181,-91,0,0 0,0,-181,-91 }
- @bad_big_bbox = %w{ -0.1,-0.1,1.1,1.1 10,10,11,11 }
- @bad_malformed_bbox = %w{ -0.1 hello 10N2W10.1N2.1W }
- @bad_lat_mixed_bbox = %w{ 0,0.1,0.1,0 -0.1,80,0.1,70 0.24,54.34,0.25,54.33 }
- @bad_lon_mixed_bbox = %w{ 80,-0.1,70,0.1 54.34,0.24,54.33,0.25 }
- @bad_limit_bbox = %w{ -180.1,-90,180,90 -180,-90.1,180,90 -180,-90,180.1,90 -180,-90,180,90.1}
- @good_bbox = %w{ -0.1,-0.1,0.1,0.1 51.1,-0.1,51.2,0 -0.1,%20-0.1,%200.1,%200.1
- -0.1edcd,-0.1d,0.1,0.1 -0.1E,-0.1E,0.1S,0.1N S0.1,W0.1,N0.1,E0.1}
-
- @expand_min_lon_array = %w{ 2,10,10,10 1,10,10,10 0,10,10,10 -1,10,10,10 -2,10,10,10 -8,10,10,10 }
- @expand_min_lat_array = %w{ 10,2,10,10 10,1,10,10 10,0,10,10 10,-1,10,10 10,-2,10,10 10,-8,10,10 }
- @expand_max_lon_array = %w{ -2,-2,-1,-2 -2,-2,0,-2 -2,-2,1,-2 -2,-2,2,-2 }
- @expand_max_lat_array = %w{ -2,-2,-2,-1 -2,-2,-2,0 -2,-2,-2,1 -2,-2,-2,2 }
- @expand_min_lon_margin_response = [[2,10,10,10], [-7,10,10,10], [-7,10,10,10], [-7,10,10,10], [-7,10,10,10], [-25,10,10,10]]
- @expand_min_lat_margin_response = [[10,2,10,10], [10,-7,10,10], [10,-7,10,10], [10,-7,10,10], [10,-7,10,10], [10,-25,10,10]]
- @expand_max_lon_margin_response = [[-2,-2,-1,-2], [-2,-2,1,-2], [-2,-2,1,-2], [-2,-2,5,-2]]
- @expand_max_lat_margin_response = [[-2,-2,-2,-1], [-2,-2,-2,1], [-2,-2,-2,1], [-2,-2,-2,5]]
+ @bad_positive_boundary_bbox = %w(181,91,0,0 0,0,181,91)
+ @bad_negative_boundary_bbox = %w(-181,-91,0,0 0,0,-181,-91)
+ @bad_big_bbox = %w(-0.1,-0.1,1.1,1.1 10,10,11,11)
+ @bad_malformed_bbox = %w(-0.1 hello 10N2W10.1N2.1W)
+ @bad_lat_mixed_bbox = %w(0,0.1,0.1,0 -0.1,80,0.1,70 0.24,54.34,0.25,54.33)
+ @bad_lon_mixed_bbox = %w(80,-0.1,70,0.1 54.34,0.24,54.33,0.25)
+ @bad_limit_bbox = %w(-180.1,-90,180,90 -180,-90.1,180,90 -180,-90,180.1,90 -180,-90,180,90.1)
+ @good_bbox = %w(-0.1,-0.1,0.1,0.1 51.1,-0.1,51.2,0 -0.1,%20-0.1,%200.1,%200.1
+ -0.1edcd,-0.1d,0.1,0.1 -0.1E,-0.1E,0.1S,0.1N S0.1,W0.1,N0.1,E0.1)
+
+ @expand_min_lon_array = %w(2,10,10,10 1,10,10,10 0,10,10,10 -1,10,10,10 -2,10,10,10 -8,10,10,10)
+ @expand_min_lat_array = %w(10,2,10,10 10,1,10,10 10,0,10,10 10,-1,10,10 10,-2,10,10 10,-8,10,10)
+ @expand_max_lon_array = %w(-2,-2,-1,-2 -2,-2,0,-2 -2,-2,1,-2 -2,-2,2,-2)
+ @expand_max_lat_array = %w(-2,-2,-2,-1 -2,-2,-2,0 -2,-2,-2,1 -2,-2,-2,2)
+ @expand_min_lon_margin_response = [[2, 10, 10, 10], [-7, 10, 10, 10], [-7, 10, 10, 10], [-7, 10, 10, 10], [-7, 10, 10, 10], [-25, 10, 10, 10]]
+ @expand_min_lat_margin_response = [[10, 2, 10, 10], [10, -7, 10, 10], [10, -7, 10, 10], [10, -7, 10, 10], [10, -7, 10, 10], [10, -25, 10, 10]]
+ @expand_max_lon_margin_response = [[-2, -2, -1, -2], [-2, -2, 1, -2], [-2, -2, 1, -2], [-2, -2, 5, -2]]
+ @expand_max_lat_margin_response = [[-2, -2, -2, -1], [-2, -2, -2, 1], [-2, -2, -2, 1], [-2, -2, -2, 5]]
end
def test_good_bbox_from_string
@good_bbox.each do |string|
bbox = BoundingBox.from_s(string)
- array = string.split(',').collect {|s| s.to_f}
+ array = string.split(',').collect(&:to_f)
check_bbox(bbox, array)
end
end
def test_good_bbox_from_params
@good_bbox.each do |string|
- bbox = BoundingBox.from_bbox_params({:bbox => string})
- array = string.split(',').collect {|s| s.to_f}
+ bbox = BoundingBox.from_bbox_params(:bbox => string)
+ array = string.split(',').collect(&:to_f)
check_bbox(bbox, array)
end
end
def test_good_bbox_from_lon_lat_params
@good_bbox.each do |string|
array = string.split(',')
- bbox = BoundingBox.from_lon_lat_params({:minlon => array[0], :minlat => array[1], :maxlon => array[2], :maxlat => array[3]})
- check_bbox(bbox, array.collect {|s| s.to_f})
+ bbox = BoundingBox.from_lon_lat_params(:minlon => array[0], :minlat => array[1], :maxlon => array[2], :maxlat => array[3])
+ check_bbox(bbox, array.collect(&:to_f))
end
end
def test_bbox_from_params_malformed
@bad_malformed_bbox.each do |bbox_string|
- exception = assert_raise(OSM::APIBadUserInput) {BoundingBox.from_bbox_params({:bbox => bbox_string})}
+ exception = assert_raise(OSM::APIBadUserInput) { BoundingBox.from_bbox_params(:bbox => bbox_string) }
assert_equal(@malformed_error_message, exception.message)
end
end
@good_bbox.each do |string|
array = string.split(',')
bbox = BoundingBox.new(array[0], array[1], array[2], array[3])
- check_bbox(bbox, array.collect {|s| s.to_f})
+ check_bbox(bbox, array.collect(&:to_f))
end
end
end
def test_expand_min_lon_boundary
- @bbox_expand.expand!(BoundingBox.new(-1810000000,0,0,0))
+ @bbox_expand.expand!(BoundingBox.new(-1810000000, 0, 0, 0))
check_expand(@bbox_expand, "-1800000000,0,0,0")
end
def test_expand_min_lat_boundary
- @bbox_expand.expand!(BoundingBox.new(0,-910000000,0,0))
+ @bbox_expand.expand!(BoundingBox.new(0, -910000000, 0, 0))
check_expand(@bbox_expand, "0,-900000000,0,0")
end
def test_expand_max_lon_boundary
- @bbox_expand.expand!(BoundingBox.new(0,0,1810000000,0))
+ @bbox_expand.expand!(BoundingBox.new(0, 0, 1810000000, 0))
check_expand(@bbox_expand, "0,0,1800000000,0")
end
def test_expand_max_lat_boundary
- @bbox_expand.expand!(BoundingBox.new(0,0,0,910000000))
+ @bbox_expand.expand!(BoundingBox.new(0, 0, 0, 910000000))
check_expand(@bbox_expand, "0,0,0,900000000")
end
def test_expand_min_lon_without_margin
- @expand_min_lon_array.each {|array_string| check_expand(@bbox_expand_ten, array_string)}
+ @expand_min_lon_array.each { |array_string| check_expand(@bbox_expand_ten, array_string) }
end
def test_expand_min_lon_with_margin
end
def test_expand_min_lat_without_margin
- @expand_min_lat_array.each {|array_string| check_expand(@bbox_expand_ten, array_string)}
+ @expand_min_lat_array.each { |array_string| check_expand(@bbox_expand_ten, array_string) }
end
def test_expand_min_lat_with_margin
end
def test_expand_max_lon_without_margin
- @expand_max_lon_array.each {|array_string| check_expand(@bbox_expand_minus_two, array_string)}
+ @expand_max_lon_array.each { |array_string| check_expand(@bbox_expand_minus_two, array_string) }
end
def test_expand_max_lon_with_margin
end
def test_expand_max_lat_without_margin
- @expand_max_lat_array.each {|array_string| check_expand(@bbox_expand_minus_two, array_string)}
+ @expand_max_lat_array.each { |array_string| check_expand(@bbox_expand_minus_two, array_string) }
end
def test_expand_max_lat_with_margin
def test_good_bbox_boundaries
@good_bbox.each do |bbox_string|
- assert_nothing_raised(OSM::APIBadBoundingBox) {BoundingBox.from_s(bbox_string).check_boundaries}
+ assert_nothing_raised(OSM::APIBadBoundingBox) { BoundingBox.from_s(bbox_string).check_boundaries }
end
end
def test_from_params_with_positive_out_of_boundary
@bad_positive_boundary_bbox.each do |bbox_string|
- bbox = BoundingBox.from_bbox_params({:bbox => bbox_string})
+ bbox = BoundingBox.from_bbox_params(:bbox => bbox_string)
array = bbox.to_a
assert_equal 180, [array[0], array[2]].max
assert_equal 90, [array[1], array[3]].max
def test_from_params_with_negative_out_of_boundary
@bad_negative_boundary_bbox.each do |bbox_string|
- bbox = BoundingBox.from_bbox_params({:bbox => bbox_string})
+ bbox = BoundingBox.from_bbox_params(:bbox => bbox_string)
array = bbox.to_a
assert_equal -180, [array[0], array[2]].min
assert_equal -90, [array[1], array[3]].min
def test_boundaries_mixed_lon
@bad_lon_mixed_bbox.each do |bbox_string|
- exception = assert_raise(OSM::APIBadBoundingBox) {BoundingBox.from_s(bbox_string).check_boundaries}
+ exception = assert_raise(OSM::APIBadBoundingBox) { BoundingBox.from_s(bbox_string).check_boundaries }
assert_equal(@lon_order_error_message, exception.message)
end
end
def test_boundaries_mixed_lat
@bad_lat_mixed_bbox.each do |bbox_string|
- exception = assert_raise(OSM::APIBadBoundingBox) {BoundingBox.from_s(bbox_string).check_boundaries}
+ exception = assert_raise(OSM::APIBadBoundingBox) { BoundingBox.from_s(bbox_string).check_boundaries }
assert_equal(@lat_order_error_message, exception.message)
end
end
def test_boundaries_out_of_limits
@bad_limit_bbox.each do |bbox_string|
- exception = assert_raise(OSM::APIBadBoundingBox) {BoundingBox.from_s(bbox_string).check_boundaries}
+ exception = assert_raise(OSM::APIBadBoundingBox) { BoundingBox.from_s(bbox_string).check_boundaries }
assert_equal(@bbox_out_of_limits_error_message, exception.message)
end
end
def test_good_bbox_size
@good_bbox.each do |bbox_string|
- assert_nothing_raised(OSM::APIBadBoundingBox) {BoundingBox.from_s(bbox_string).check_size}
+ assert_nothing_raised(OSM::APIBadBoundingBox) { BoundingBox.from_s(bbox_string).check_size }
end
end
def test_size_to_big
@bad_big_bbox.each do |bbox_string|
bbox = nil
- assert_nothing_raised(OSM::APIBadBoundingBox) {bbox = BoundingBox.from_bbox_params({:bbox => bbox_string}).check_boundaries}
- exception = assert_raise(OSM::APIBadBoundingBox) {bbox.check_size}
+ assert_nothing_raised(OSM::APIBadBoundingBox) { bbox = BoundingBox.from_bbox_params(:bbox => bbox_string).check_boundaries }
+ exception = assert_raise(OSM::APIBadBoundingBox) { bbox.check_size }
assert_equal(@size_error_message, exception.message)
end
end
end
def test_to_a
- assert_equal [1.0,2.0,3.0,4.0], @bbox_from_string.to_a
+ assert_equal [1.0, 2.0, 3.0, 4.0], @bbox_from_string.to_a
end
def test_to_string
end
private
+
def check_expand(bbox, array_string, margin = 0, result = nil)
- array = array_string.split(',').collect {|s| s.to_f}
+ array = array_string.split(',').collect(&:to_f)
result = array unless result
bbox.expand!(BoundingBox.new(array[0], array[1], array[2], array[3]), margin)
check_bbox(bbox, result)
if default_value.is_a?(Hash)
variables.push("count")
- default_value.each do |subkey,subvalue|
+ default_value.each do |_subkey, subvalue|
subvalue.scan(/%\{(\w+)\}/) do
variables.push($1)
end
value = I18n.t(key, :locale => locale, :fallback => true)
if value.is_a?(Hash)
- value.each do |subkey,subvalue|
-# assert plural_keys.include?(subkey), "#{key}.#{subkey} is not a valid plural key"
+ value.each do |subkey, subvalue|
+ # assert plural_keys.include?(subkey), "#{key}.#{subkey} is not a valid plural key"
unless subvalue.nil?
subvalue.scan(/%\{(\w+)\}/) do
end
end
- assert ["ltr", "rtl"].include?(I18n.t("html.dir", :locale => locale)), "html.dir must be ltr or rtl"
+ assert %w(ltr rtl).include?(I18n.t("html.dir", :locale => locale)), "html.dir must be ltr or rtl"
end
end
-private
+
+ private
+
def translation_keys(scope = nil)
plural_keys = plural_keys(I18n.default_locale)
- I18n.t(scope || ".", :locale => I18n.default_locale).map do |key,value|
+ I18n.t(scope || ".", :locale => I18n.default_locale).map do |key, value|
scoped_key = scope ? "#{scope}.#{key}" : key
- if value.kind_of?(Hash)
+ if value.is_a?(Hash)
if value.keys - plural_keys == []
scoped_key
else
translation_keys(scoped_key)
end
- elsif value.kind_of?(String)
+ elsif value.is_a?(String)
scoped_key
end
end.flatten
end
def plural_keys(locale)
- I18n.t("i18n.plural.keys", :locale => locale, :raise => true) + [ :zero ]
+ I18n.t("i18n.plural.keys", :locale => locale, :raise => true) + [:zero]
rescue I18n::MissingTranslationData
- [ :zero, :one, :other ]
+ [:zero, :one, :other]
end
end
end
end
-private
+ private
def assert_html(richtext, &block)
html = richtext.to_html
# tests that encoding and decoding are working to within
# the acceptable quantisation range.
def test_encode_decode
- cases = Array.new
+ cases = []
1000.times do
- cases << [ 180.0 * rand - 90.0, 360.0 * rand - 180.0, (18 * rand).to_i ]
+ cases << [180.0 * rand - 90.0, 360.0 * rand - 180.0, (18 * rand).to_i]
end
cases.each do |lat, lon, zoom|
# one pixel (i.e: zoom + 8). the sqrt(5) is because each position
# has an extra bit of accuracy in the lat coordinate, due to the
# smaller range.
- distance = Math.sqrt((lat - lat2) ** 2 + (lon - lon2) ** 2)
+ distance = Math.sqrt((lat - lat2)**2 + (lon - lon2)**2)
max_distance = 360.0 / (1 << (zoom + 8)) * 0.5 * Math.sqrt(5)
assert max_distance > distance, "Maximum expected error exceeded: #{max_distance} <= #{distance} for (#{lat}, #{lon}, #{zoom})."
end
cases.each do |new_code, old_code|
assert_equal ShortLink.decode(old_code), ShortLink.decode(new_code),
- "old (#{old_code}) and new (#{new_code}) should decode to the same location."
+ "old (#{old_code}) and new (#{new_code}) should decode to the same location."
end
end
end
(0..255).each do |i|
tag = ChangesetTag.new
tag.changeset_id = 1
- tag.k = key*i
+ tag.k = key * i
tag.v = "v"
assert tag.valid?
end
tag = ChangesetTag.new
tag.changeset_id = 1
tag.k = "k"
- tag.v = val*i
+ tag.v = val * i
assert tag.valid?
end
end
def test_length_key_invalid
- ["k"*256].each do |k|
+ ["k" * 256].each do |k|
tag = ChangesetTag.new
tag.changeset_id = 1
tag.k = k
end
def test_length_value_invalid
- ["v"*256].each do |v|
+ ["v" * 256].each do |v|
tag = ChangesetTag.new
tag.changeset_id = 1
tag.k = "k"
tag.v = changeset_tags(:changeset_1_tag_1).v
assert tag.new_record?
assert !tag.valid?
- assert_raise(ActiveRecord::RecordInvalid) {tag.save!}
+ assert_raise(ActiveRecord::RecordInvalid) { tag.save! }
assert tag.new_record?
end
end
def test_from_xml_no_text
no_text = ""
- message_create = assert_raise(OSM::APIBadXMLError) {
+ message_create = assert_raise(OSM::APIBadXMLError) do
Changeset.from_xml(no_text, true)
- }
+ end
assert_match /Must specify a string with one or more characters/, message_create.message
- message_update = assert_raise(OSM::APIBadXMLError) {
+ message_update = assert_raise(OSM::APIBadXMLError) do
Changeset.from_xml(no_text, false)
- }
+ end
assert_match /Must specify a string with one or more characters/, message_update.message
end
def test_from_xml_no_changeset
nocs = "<osm></osm>"
- message_create = assert_raise(OSM::APIBadXMLError) {
+ message_create = assert_raise(OSM::APIBadXMLError) do
Changeset.from_xml(nocs, true)
- }
+ end
assert_match /XML doesn't contain an osm\/changeset element/, message_create.message
- message_update = assert_raise(OSM::APIBadXMLError) {
+ message_update = assert_raise(OSM::APIBadXMLError) do
Changeset.from_xml(nocs, false)
- }
+ end
assert_match /XML doesn't contain an osm\/changeset element/, message_update.message
end
def test_from_xml_no_k_v
nokv = "<osm><changeset><tag /></changeset></osm>"
- message_create = assert_raise(OSM::APIBadXMLError) {
+ message_create = assert_raise(OSM::APIBadXMLError) do
Changeset.from_xml(nokv, true)
- }
+ end
assert_match /tag is missing key/, message_create.message
- message_update = assert_raise(OSM::APIBadXMLError) {
+ message_update = assert_raise(OSM::APIBadXMLError) do
Changeset.from_xml(nokv, false)
- }
+ end
assert_match /tag is missing key/, message_create.message
end
def test_from_xml_no_v
no_v = "<osm><changeset><tag k='key' /></changeset></osm>"
- message_create = assert_raise(OSM::APIBadXMLError) {
+ message_create = assert_raise(OSM::APIBadXMLError) do
Changeset.from_xml(no_v, true)
- }
+ end
assert_match /tag is missing value/, message_create.message
- message_update = assert_raise(OSM::APIBadXMLError) {
+ message_update = assert_raise(OSM::APIBadXMLError) do
Changeset.from_xml(no_v, false)
- }
+ end
assert_match /tag is missing value/, message_update.message
end
def test_from_xml_duplicate_k
dupk = "<osm><changeset><tag k='dup' v='test' /><tag k='dup' v='value' /></changeset></osm>"
- message_create = assert_raise(OSM::APIDuplicateTagsError) {
+ message_create = assert_raise(OSM::APIDuplicateTagsError) do
Changeset.from_xml(dupk, true)
- }
+ end
assert_equal "Element changeset/ has duplicate tags with key dup", message_create.message
- message_update = assert_raise(OSM::APIDuplicateTagsError) {
+ message_update = assert_raise(OSM::APIDuplicateTagsError) do
Changeset.from_xml(dupk, false)
- }
+ end
assert_equal "Element changeset/ has duplicate tags with key dup", message_update.message
end
def test_from_xml_valid
# Example taken from the Update section on the API_v0.6 docs on the wiki
xml = "<osm><changeset><tag k=\"comment\" v=\"Just adding some streetnames and a restaurant\"/></changeset></osm>"
- assert_nothing_raised(OSM::APIBadXMLError) {
+ assert_nothing_raised(OSM::APIBadXMLError) do
Changeset.from_xml(xml, false)
- }
- assert_nothing_raised(OSM::APIBadXMLError) {
+ end
+ assert_nothing_raised(OSM::APIBadXMLError) do
Changeset.from_xml(xml, true)
- }
+ end
end
end
def test_diary_entry_validations
diary_entry_valid({})
- diary_entry_valid({:title => ''}, false)
- diary_entry_valid({:title => 'a'*255})
- diary_entry_valid({:title => 'a'*256}, false)
- diary_entry_valid({:body => ''}, false)
- diary_entry_valid({:latitude => 90})
- diary_entry_valid({:latitude => 90.00001}, false)
- diary_entry_valid({:latitude => -90})
- diary_entry_valid({:latitude => -90.00001}, false)
- diary_entry_valid({:longitude => 180})
- diary_entry_valid({:longitude => 180.00001}, false)
- diary_entry_valid({:longitude => -180})
- diary_entry_valid({:longitude => -180.00001}, false)
+ diary_entry_valid({ :title => '' }, false)
+ diary_entry_valid(:title => 'a' * 255)
+ diary_entry_valid({ :title => 'a' * 256 }, false)
+ diary_entry_valid({ :body => '' }, false)
+ diary_entry_valid(:latitude => 90)
+ diary_entry_valid({ :latitude => 90.00001 }, false)
+ diary_entry_valid(:latitude => -90)
+ diary_entry_valid({ :latitude => -90.00001 }, false)
+ diary_entry_valid(:longitude => 180)
+ diary_entry_valid({ :longitude => 180.00001 }, false)
+ diary_entry_valid(:longitude => -180)
+ diary_entry_valid({ :longitude => -180.00001 }, false)
end
def test_diary_entry_visible
assert_equal 1, diary_entries(:normal_user_geo_entry).visible_comments.count
end
-private
+ private
def diary_entry_valid(attrs, result = true)
entry = DiaryEntry.new(diary_entries(:normal_user_entry_1).attributes)
def test_friend_count
assert_equal 1, Friend.count
end
-
end
api_fixtures
fixtures :messages
- EURO = "\xe2\x82\xac" #euro symbol
+ EURO = "\xe2\x82\xac" # euro symbol
# This needs to be updated when new fixtures are added
# or removed.
assert_raise(ActiveRecord::RecordNotFound) { User.find(0) }
message.from_user_id = 0
message.to_user_id = 0
- assert_raise(ActiveRecord::RecordInvalid) {message.save!}
+ assert_raise(ActiveRecord::RecordInvalid) { message.save! }
end
def test_utf8_roundtrip
assert_equal "text", message.body_format
end
-private
+ private
def make_message(char, count)
message = messages(:unread_message)
message.title = char * count
- return message
+ message
end
def assert_message_ok(char, count)
message = make_message(char, count)
assert message.save!
response = message.class.find(message.id) # stand by for some über-generalisation...
- assert_equal char * count, response.title, "message with #{count} #{char} chars (i.e. #{char.length*count} bytes) fails"
+ assert_equal char * count, response.title, "message with #{count} #{char} chars (i.e. #{char.length * count} bytes) fails"
end
end
node_tag_count(:node_with_versions, 2)
end
- def node_tag_count (node, count)
+ def node_tag_count(node, count)
nod = current_nodes(node)
assert_equal count, nod.node_tags.count
end
(0..255).each do |i|
tag = NodeTag.new
tag.node_id = current_node_tags(:t1).node_id
- tag.k = key*i
+ tag.k = key * i
tag.v = "v"
assert tag.valid?
end
tag = NodeTag.new
tag.node_id = current_node_tags(:t1).node_id
tag.k = "k"
- tag.v = val*i
+ tag.v = val * i
assert tag.valid?
end
end
def test_length_key_invalid
- ["k"*256].each do |i|
+ ["k" * 256].each do |i|
tag = NodeTag.new
tag.node_id = current_node_tags(:t1).node_id
tag.k = i
end
def test_length_value_invalid
- ["k"*256].each do |i|
+ ["k" * 256].each do |i|
tag = NodeTag.new
tag.node_id = current_node_tags(:t1).node_id
tag.k = "k"
tag.v = current_node_tags(:t1).v
assert tag.new_record?
assert !tag.valid?
- assert_raise(ActiveRecord::RecordInvalid) {tag.save!}
+ assert_raise(ActiveRecord::RecordInvalid) { tag.save! }
assert tag.new_record?
end
end
assert_equal dbnode.timestamp, node.timestamp
assert_equal dbnode.version, node.version
assert_equal dbnode.visible, node.visible
- #assert_equal node.tile, QuadTile.tile_for_point(node.lat, node.lon)
+ # assert_equal node.tile, QuadTile.tile_for_point(node.lat, node.lon)
assert node.valid?
end
assert_equal dbnode.timestamp, node.timestamp
assert_equal dbnode.version, node.version
assert_equal dbnode.visible, node.visible
- #assert_equal node.tile, QuadTile.tile_for_point(node.lat, node.lon)
+ # assert_equal node.tile, QuadTile.tile_for_point(node.lat, node.lon)
assert_equal false, dbnode.valid?
end
node_template.latitude = 12.3456
node_template.longitude = 65.4321
- #node_template.tags = "updated=yes"
+ # node_template.tags = "updated=yes"
assert node.update_from(node_template, users(:normal_user))
node = Node.find(node_template.id)
assert_equal node_template.longitude, node.longitude
assert_equal node_template.changeset_id, node.changeset_id
assert_equal node_template.visible, node.visible
- #assert_equal node_template.tags, node.tags
+ # assert_equal node_template.tags, node.tags
assert_equal OldNode.where(:node_id => node_template.id).count, 2
old_node = OldNode.where(:node_id => node_template.id, :version => 2).first
assert_equal node_template.longitude, old_node.longitude
assert_equal node_template.changeset_id, old_node.changeset_id
assert_equal node_template.visible, old_node.visible
- #assert_equal node_template.tags, old_node.tags
+ # assert_equal node_template.tags, old_node.tags
end
def test_delete
assert_equal node_template.longitude, node.longitude
assert_equal node_template.changeset_id, node.changeset_id
assert_equal false, node.visible
- #assert_equal node_template.tags, node.tags
+ # assert_equal node_template.tags, node.tags
assert_equal OldNode.where(:node_id => node_template.id).count, 2
old_node = OldNode.where(:node_id => node_template.id, :version => 2).first
assert_equal node_template.longitude, old_node.longitude
assert_equal node_template.changeset_id, old_node.changeset_id
assert_equal false, old_node.visible
- #assert_equal node_template.tags, old_node.tags
+ # assert_equal node_template.tags, old_node.tags
end
def test_from_xml_no_id
version = 1
noid = "<osm><node lat='#{lat}' lon='#{lon}' changeset='#{changeset}' version='#{version}' /></osm>"
# First try a create which doesn't need the id
- assert_nothing_raised(OSM::APIBadXMLError) {
+ assert_nothing_raised(OSM::APIBadXMLError) do
Node.from_xml(noid, true)
- }
+ end
# Now try an update with no id, and make sure that it gives the appropriate exception
- message = assert_raise(OSM::APIBadXMLError) {
+ message = assert_raise(OSM::APIBadXMLError) do
Node.from_xml(noid, false)
- }
+ end
assert_match /ID is required when updating./, message.message
end
def test_from_xml_no_lat
nolat = "<osm><node id='1' lon='23.3' changeset='2' version='23' /></osm>"
- message_create = assert_raise(OSM::APIBadXMLError) {
+ message_create = assert_raise(OSM::APIBadXMLError) do
Node.from_xml(nolat, true)
- }
+ end
assert_match /lat missing/, message_create.message
- message_update = assert_raise(OSM::APIBadXMLError) {
+ message_update = assert_raise(OSM::APIBadXMLError) do
Node.from_xml(nolat, false)
- }
+ end
assert_match /lat missing/, message_update.message
end
def test_from_xml_no_lon
nolon = "<osm><node id='1' lat='23.1' changeset='2' version='23' /></osm>"
- message_create = assert_raise(OSM::APIBadXMLError) {
+ message_create = assert_raise(OSM::APIBadXMLError) do
Node.from_xml(nolon, true)
- }
+ end
assert_match /lon missing/, message_create.message
- message_update = assert_raise(OSM::APIBadXMLError) {
+ message_update = assert_raise(OSM::APIBadXMLError) do
Node.from_xml(nolon, false)
- }
+ end
assert_match /lon missing/, message_update.message
end
def test_from_xml_no_changeset_id
nocs = "<osm><node id='123' lon='23.23' lat='23.1' version='23' /></osm>"
- message_create = assert_raise(OSM::APIBadXMLError) {
+ message_create = assert_raise(OSM::APIBadXMLError) do
Node.from_xml(nocs, true)
- }
+ end
assert_match /Changeset id is missing/, message_create.message
- message_update = assert_raise(OSM::APIBadXMLError) {
+ message_update = assert_raise(OSM::APIBadXMLError) do
Node.from_xml(nocs, false)
- }
+ end
assert_match /Changeset id is missing/, message_update.message
end
def test_from_xml_no_version
no_version = "<osm><node id='123' lat='23' lon='23' changeset='23' /></osm>"
- assert_nothing_raised(OSM::APIBadXMLError) {
+ assert_nothing_raised(OSM::APIBadXMLError) do
Node.from_xml(no_version, true)
- }
- message_update = assert_raise(OSM::APIBadXMLError) {
+ end
+ message_update = assert_raise(OSM::APIBadXMLError) do
Node.from_xml(no_version, false)
- }
+ end
assert_match /Version is required when updating/, message_update.message
end
def test_from_xml_double_lat
nocs = "<osm><node id='123' lon='23.23' lat='23.1' lat='12' changeset='23' version='23' /></osm>"
- message_create = assert_raise(OSM::APIBadXMLError) {
+ message_create = assert_raise(OSM::APIBadXMLError) do
Node.from_xml(nocs, true)
- }
+ end
assert_match /Fatal error: Attribute lat redefined at/, message_create.message
- message_update = assert_raise(OSM::APIBadXMLError) {
+ message_update = assert_raise(OSM::APIBadXMLError) do
Node.from_xml(nocs, false)
- }
+ end
assert_match /Fatal error: Attribute lat redefined at/, message_update.message
end
id_list = ["", "0", "00", "0.0", "a"]
id_list.each do |id|
zero_id = "<osm><node id='#{id}' lat='12.3' lon='12.3' changeset='33' version='23' /></osm>"
- assert_nothing_raised(OSM::APIBadUserInput) {
+ assert_nothing_raised(OSM::APIBadUserInput) do
Node.from_xml(zero_id, true)
- }
- message_update = assert_raise(OSM::APIBadUserInput) {
+ end
+ message_update = assert_raise(OSM::APIBadUserInput) do
Node.from_xml(zero_id, false)
- }
+ end
assert_match /ID of node cannot be zero when updating/, message_update.message
end
end
def test_from_xml_no_text
no_text = ""
- message_create = assert_raise(OSM::APIBadXMLError) {
+ message_create = assert_raise(OSM::APIBadXMLError) do
Node.from_xml(no_text, true)
- }
+ end
assert_match /Must specify a string with one or more characters/, message_create.message
- message_update = assert_raise(OSM::APIBadXMLError) {
+ message_update = assert_raise(OSM::APIBadXMLError) do
Node.from_xml(no_text, false)
- }
+ end
assert_match /Must specify a string with one or more characters/, message_update.message
end
def test_from_xml_no_node
no_node = "<osm></osm>"
- message_create = assert_raise(OSM::APIBadXMLError) {
+ message_create = assert_raise(OSM::APIBadXMLError) do
Node.from_xml(no_node, true)
- }
+ end
assert_match /XML doesn't contain an osm\/node element/, message_create.message
- message_update = assert_raise(OSM::APIBadXMLError) {
+ message_update = assert_raise(OSM::APIBadXMLError) do
Node.from_xml(no_node, false)
- }
+ end
assert_match /XML doesn't contain an osm\/node element/, message_update.message
end
def test_from_xml_no_k_v
nokv = "<osm><node id='23' lat='12.3' lon='23.4' changeset='12' version='23'><tag /></node></osm>"
- message_create = assert_raise(OSM::APIBadXMLError) {
+ message_create = assert_raise(OSM::APIBadXMLError) do
Node.from_xml(nokv, true)
- }
+ end
assert_match /tag is missing key/, message_create.message
- message_update = assert_raise(OSM::APIBadXMLError) {
+ message_update = assert_raise(OSM::APIBadXMLError) do
Node.from_xml(nokv, false)
- }
+ end
assert_match /tag is missing key/, message_update.message
end
def test_from_xml_no_v
no_v = "<osm><node id='23' lat='23.43' lon='23.32' changeset='23' version='32'><tag k='key' /></node></osm>"
- message_create = assert_raise(OSM::APIBadXMLError) {
+ message_create = assert_raise(OSM::APIBadXMLError) do
Node.from_xml(no_v, true)
- }
+ end
assert_match /tag is missing value/, message_create.message
- message_update = assert_raise(OSM::APIBadXMLError) {
+ message_update = assert_raise(OSM::APIBadXMLError) do
Node.from_xml(no_v, false)
- }
+ end
assert_match /tag is missing value/, message_update.message
end
def test_from_xml_duplicate_k
dupk = "<osm><node id='23' lat='23.2' lon='23' changeset='34' version='23'><tag k='dup' v='test' /><tag k='dup' v='tester' /></node></osm>"
- message_create = assert_raise(OSM::APIDuplicateTagsError) {
+ message_create = assert_raise(OSM::APIDuplicateTagsError) do
Node.from_xml(dupk, true)
- }
+ end
assert_equal "Element node/ has duplicate tags with key dup", message_create.message
- message_update = assert_raise(OSM::APIDuplicateTagsError) {
+ message_update = assert_raise(OSM::APIDuplicateTagsError) do
Node.from_xml(dupk, false)
- }
+ end
assert_equal "Element node/23 has duplicate tags with key dup", message_update.message
end
def test_containing_relation_members
node = current_nodes(:node_used_by_relationship)
crm = Node.find(node.id).containing_relation_members.order(:relation_id)
-# assert_equal 3, crm.size
+ # assert_equal 3, crm.size
assert_equal 1, crm.first.relation_id
assert_equal "Node", crm.first.member_type
assert_equal node.id, crm.first.member_id
fixtures :users, :notes, :note_comments
def test_event_valid
- ok = [ "opened", "closed", "reopened", "commented", "hidden" ]
- bad = [ "expropriated", "fubared" ]
+ ok = %w(opened closed reopened commented hidden)
+ bad = %w(expropriated fubared)
ok.each do |event|
note_comment = note_comments(:t1)
end
def test_body_valid
- ok = [ "Name", "vergrößern", "foo\x0abar",
- "ルシステムにも対応します", "輕觸搖晃的遊戲", ]
- bad = [ "foo\x00bar", "foo\x08bar", "foo\x1fbar", "foo\x7fbar",
- "foo\ufffebar", "foo\uffffbar" ]
+ ok = ["Name", "vergrößern", "foo\x0abar",
+ "ルシステムにも対応します", "輕觸搖晃的遊戲"]
+ bad = ["foo\x00bar", "foo\x08bar", "foo\x1fbar", "foo\x7fbar",
+ "foo\ufffebar", "foo\uffffbar"]
ok.each do |body|
note_comment = note_comments(:t1)
fixtures :users, :notes, :note_comments
def test_status_valid
- ok = [ "open", "closed", "hidden" ]
- bad = [ "expropriated", "fubared" ]
+ ok = %w(open closed hidden)
+ bad = %w(expropriated fubared)
ok.each do |status|
note = notes(:open_note)
nonce2 = OauthNonce.remember(string, timestamp)
assert_equal false, nonce2, "Shouldn't be able to remember the same nonce twice."
end
-
end
tok.invalidate!
assert_equal false, tok.authorized?, "Token should now be invalid."
end
-
end
tag = OldNodeTag.new
tag.node_id = node_tags(:t1).node_id
tag.version = node_tags(:t1).version
- tag.k = key*i
+ tag.k = key * i
tag.v = "v"
assert tag.valid?
end
tag.node_id = node_tags(:t1).node_id
tag.version = node_tags(:t1).version
tag.k = "k"
- tag.v = val*i
+ tag.v = val * i
assert tag.valid?
end
end
def test_length_key_invalid
- ["k"*256].each do |i|
+ ["k" * 256].each do |i|
tag = OldNodeTag.new
tag.node_id = node_tags(:t1).node_id
tag.version = node_tags(:t1).version
end
def test_length_value_invalid
- ["k"*256].each do |i|
+ ["k" * 256].each do |i|
tag = OldNodeTag.new
tag.node_id = node_tags(:t1).node_id
tag.version = node_tags(:t1).version
tag.v = node_tags(:t1).v
assert tag.new_record?
assert !tag.valid?
- assert_raise(ActiveRecord::RecordInvalid) {tag.save!}
+ assert_raise(ActiveRecord::RecordInvalid) { tag.save! }
assert tag.new_record?
end
end
assert_equal dbnode.version, node.version
assert_equal dbnode.visible, node.visible
assert_equal dbnode.timestamp, node.timestamp
- #assert_equal node.tile, QuadTile.tile_for_point(nodes(nod).lat, nodes(nod).lon)
+ # assert_equal node.tile, QuadTile.tile_for_point(nodes(nod).lat, nodes(nod).lon)
assert node.valid?
end
assert_equal dbnode.version, node.version
assert_equal dbnode.visible, node.visible
assert_equal dbnode.timestamp, node.timestamp
- #assert_equal node.tile, QuadTile.tile_for_point(nodes(nod).lat, nodes(nod).lon)
+ # assert_equal node.tile, QuadTile.tile_for_point(nodes(nod).lat, nodes(nod).lon)
assert_equal false, node.valid?
end
tag = OldRelationTag.new
tag.relation_id = relation_tags(:t1).relation_id
tag.version = 1
- tag.k = key*i
+ tag.k = key * i
tag.v = "v"
assert tag.valid?
end
tag.relation_id = relation_tags(:t1).relation_id
tag.version = 1
tag.k = "k"
- tag.v = val*i
+ tag.v = val * i
assert tag.valid?
end
end
def test_length_key_invalid
- ["k"*256].each do |i|
+ ["k" * 256].each do |i|
tag = OldRelationTag.new
tag.relation_id = relation_tags(:t1).relation_id
tag.version = 1
end
def test_length_value_invalid
- ["k"*256].each do |i|
+ ["k" * 256].each do |i|
tag = OldRelationTag.new
tag.relation_id = relation_tags(:t1).relation_id
tag.version = 1
tag.v = relation_tags(:t1).v
assert tag.new_record?
assert !tag.valid?
- assert_raise(ActiveRecord::RecordInvalid) {tag.save!}
+ assert_raise(ActiveRecord::RecordInvalid) { tag.save! }
assert tag.new_record?
end
end
tag = OldWayTag.new
tag.way_id = way_tags(:t1).way_id
tag.version = 1
- tag.k = key*i
+ tag.k = key * i
tag.v = "v"
assert tag.valid?
end
tag.way_id = way_tags(:t1).way_id
tag.version = 1
tag.k = "k"
- tag.v = val*i
+ tag.v = val * i
assert tag.valid?
end
end
def test_length_key_invalid
- ["k"*256].each do |i|
+ ["k" * 256].each do |i|
tag = OldWayTag.new
tag.way_id = way_tags(:t1).way_id
tag.version = 1
end
def test_length_value_invalid
- ["k"*256].each do |i|
+ ["k" * 256].each do |i|
tag = OldWayTag.new
tag.way_id = way_tags(:t1).way_id
tag.version = 1
tag.v = way_tags(:t1).v
assert tag.new_record?
assert !tag.valid?
- assert_raise(ActiveRecord::RecordInvalid) {tag.save!}
+ assert_raise(ActiveRecord::RecordInvalid) { tag.save! }
assert tag.new_record?
end
end
way = ways(:way_with_versions_v3)
nodes = OldWay.find(way.id).get_nodes_undelete
assert_equal 2, nodes.size
- assert_equal [1.0, 1.0, 15, 4, {"testing" => "added in node version 3", "testing two" => "modified in node version 4"}, true], nodes[0]
- assert_equal [3.0, 3.0, 3, 1, {"test" => "yes"}, true], nodes[1]
+ assert_equal [1.0, 1.0, 15, 4, { "testing" => "added in node version 3", "testing two" => "modified in node version 4" }, true], nodes[0]
+ assert_equal [3.0, 3.0, 3, 1, { "test" => "yes" }, true], nodes[1]
way = ways(:way_with_redacted_versions_v2)
nodes = OldWay.find(way.id).get_nodes_undelete
assert_equal 2, nodes.size
- assert_equal [3.0, 3.0, 3, 1, {"test" => "yes"}, true], nodes[0]
- assert_equal [2.0, 2.0, 2, 1, {"testused" => "yes"}, false], nodes[1]
+ assert_equal [3.0, 3.0, 3, 1, { "test" => "yes" }, true], nodes[0]
+ assert_equal [2.0, 2.0, 2, 1, { "testused" => "yes" }, false], nodes[1]
end
end
end
assert_equal(true, n.redacted?, "Expected node to be redacted after redact! call.")
end
-
end
(0..255).each do |i|
tag = RelationTag.new
tag.relation_id = 1
- tag.k = key*i
+ tag.k = key * i
tag.v = "v"
assert tag.valid?
end
tag = RelationTag.new
tag.relation_id = 1
tag.k = "k"
- tag.v = val*i
+ tag.v = val * i
assert tag.valid?
end
end
def test_length_key_invalid
- ["k"*256].each do |i|
+ ["k" * 256].each do |i|
tag = RelationTag.new
tag.relation_id = 1
tag.k = i
end
def test_length_value_invalid
- ["v"*256].each do |i|
+ ["v" * 256].each do |i|
tag = RelationTag.new
tag.relation_id = 1
tag.k = "k"
tag.v = current_relation_tags(:t1).v
assert tag.new_record?
assert !tag.valid?
- assert_raise(ActiveRecord::RecordInvalid) {tag.save!}
+ assert_raise(ActiveRecord::RecordInvalid) { tag.save! }
assert tag.new_record?
end
def test_from_xml_no_id
noid = "<osm><relation version='12' changeset='23' /></osm>"
- assert_nothing_raised(OSM::APIBadXMLError) {
+ assert_nothing_raised(OSM::APIBadXMLError) do
Relation.from_xml(noid, true)
- }
- message = assert_raise(OSM::APIBadXMLError) {
+ end
+ message = assert_raise(OSM::APIBadXMLError) do
Relation.from_xml(noid, false)
- }
+ end
assert_match /ID is required when updating/, message.message
end
def test_from_xml_no_changeset_id
nocs = "<osm><relation id='123' version='12' /></osm>"
- message_create = assert_raise(OSM::APIBadXMLError) {
+ message_create = assert_raise(OSM::APIBadXMLError) do
Relation.from_xml(nocs, true)
- }
+ end
assert_match /Changeset id is missing/, message_create.message
- message_update = assert_raise(OSM::APIBadXMLError) {
+ message_update = assert_raise(OSM::APIBadXMLError) do
Relation.from_xml(nocs, false)
- }
+ end
assert_match /Changeset id is missing/, message_update.message
end
def test_from_xml_no_version
no_version = "<osm><relation id='123' changeset='23' /></osm>"
- assert_nothing_raised(OSM::APIBadXMLError) {
+ assert_nothing_raised(OSM::APIBadXMLError) do
Relation.from_xml(no_version, true)
- }
- message_update = assert_raise(OSM::APIBadXMLError) {
+ end
+ message_update = assert_raise(OSM::APIBadXMLError) do
Relation.from_xml(no_version, false)
- }
+ end
assert_match /Version is required when updating/, message_update.message
end
id_list = ["", "0", "00", "0.0", "a"]
id_list.each do |id|
zero_id = "<osm><relation id='#{id}' changeset='332' version='23' /></osm>"
- assert_nothing_raised(OSM::APIBadUserInput) {
+ assert_nothing_raised(OSM::APIBadUserInput) do
Relation.from_xml(zero_id, true)
- }
- message_update = assert_raise(OSM::APIBadUserInput) {
+ end
+ message_update = assert_raise(OSM::APIBadUserInput) do
Relation.from_xml(zero_id, false)
- }
+ end
assert_match /ID of relation cannot be zero when updating/, message_update.message
end
end
def test_from_xml_no_text
no_text = ""
- message_create = assert_raise(OSM::APIBadXMLError) {
+ message_create = assert_raise(OSM::APIBadXMLError) do
Relation.from_xml(no_text, true)
- }
+ end
assert_match /Must specify a string with one or more characters/, message_create.message
- message_update = assert_raise(OSM::APIBadXMLError) {
+ message_update = assert_raise(OSM::APIBadXMLError) do
Relation.from_xml(no_text, false)
- }
+ end
assert_match /Must specify a string with one or more characters/, message_update.message
end
def test_from_xml_no_k_v
nokv = "<osm><relation id='23' changeset='23' version='23'><tag /></relation></osm>"
- message_create = assert_raise(OSM::APIBadXMLError) {
+ message_create = assert_raise(OSM::APIBadXMLError) do
Relation.from_xml(nokv, true)
- }
+ end
assert_match /tag is missing key/, message_create.message
- message_update = assert_raise(OSM::APIBadXMLError) {
+ message_update = assert_raise(OSM::APIBadXMLError) do
Relation.from_xml(nokv, false)
- }
+ end
assert_match /tag is missing key/, message_update.message
end
def test_from_xml_no_v
no_v = "<osm><relation id='23' changeset='23' version='23'><tag k='key' /></relation></osm>"
- message_create = assert_raise(OSM::APIBadXMLError) {
+ message_create = assert_raise(OSM::APIBadXMLError) do
Relation.from_xml(no_v, true)
- }
+ end
assert_match /tag is missing value/, message_create.message
- message_update = assert_raise(OSM::APIBadXMLError) {
+ message_update = assert_raise(OSM::APIBadXMLError) do
Relation.from_xml(no_v, false)
- }
+ end
assert_match /tag is missing value/, message_update.message
end
def test_from_xml_duplicate_k
dupk = "<osm><relation id='23' changeset='23' version='23'><tag k='dup' v='test'/><tag k='dup' v='tester'/></relation></osm>"
- message_create = assert_raise(OSM::APIDuplicateTagsError) {
+ message_create = assert_raise(OSM::APIDuplicateTagsError) do
Relation.from_xml(dupk, true)
- }
+ end
assert_equal "Element relation/ has duplicate tags with key dup", message_create.message
- message_update = assert_raise(OSM::APIDuplicateTagsError) {
+ message_update = assert_raise(OSM::APIDuplicateTagsError) do
Relation.from_xml(dupk, false)
- }
+ end
assert_equal "Element relation/23 has duplicate tags with key dup", message_update.message
end
def test_containing_relation_members
relation = current_relations(:used_relation)
crm = Relation.find(relation.id).containing_relation_members.order(:relation_id)
-# assert_equal 1, crm.size
+ # assert_equal 1, crm.size
assert_equal 1, crm.first.relation_id
assert_equal "Relation", crm.first.member_type
assert_equal relation.id, crm.first.member_id
def test_validations
trace_valid({})
- trace_valid({:user_id => nil}, false)
- trace_valid({:name => 'a'*255})
- trace_valid({:name => 'a'*256}, false)
- trace_valid({:description => nil}, false)
- trace_valid({:description => 'a'*255})
- trace_valid({:description => 'a'*256}, false)
- trace_valid({:visibility => "private"})
- trace_valid({:visibility => "public"})
- trace_valid({:visibility => "trackable"})
- trace_valid({:visibility => "identifiable"})
- trace_valid({:visibility => "foo"}, false)
+ trace_valid({ :user_id => nil }, false)
+ trace_valid(:name => 'a' * 255)
+ trace_valid({ :name => 'a' * 256 }, false)
+ trace_valid({ :description => nil }, false)
+ trace_valid(:description => 'a' * 255)
+ trace_valid({ :description => 'a' * 256 }, false)
+ trace_valid(:visibility => "private")
+ trace_valid(:visibility => "public")
+ trace_valid(:visibility => "trackable")
+ trace_valid(:visibility => "identifiable")
+ trace_valid({ :visibility => "foo" }, false)
end
def test_tagstring
assert_equal ".gpx.gz", gpx_files(:identifiable_trace_file).extension_name
end
-private
+ private
def check_query(query, traces)
traces = traces.map { |t| gpx_files(t) }.sort
def test_tracepoint_count
assert_equal 4, Tracepoint.count
end
-
end
def test_validations
tracetag_valid({})
- tracetag_valid({:tag => nil}, false)
- tracetag_valid({:tag => ''}, false)
- tracetag_valid({:tag => 'a'})
- tracetag_valid({:tag => 'a'*255})
- tracetag_valid({:tag => 'a'*256}, false)
- tracetag_valid({:tag => 'a/b'}, false)
- tracetag_valid({:tag => 'a;b'}, false)
- tracetag_valid({:tag => 'a.b'}, false)
- tracetag_valid({:tag => 'a,b'}, false)
- tracetag_valid({:tag => 'a?b'}, false)
+ tracetag_valid({ :tag => nil }, false)
+ tracetag_valid({ :tag => '' }, false)
+ tracetag_valid(:tag => 'a')
+ tracetag_valid(:tag => 'a' * 255)
+ tracetag_valid({ :tag => 'a' * 256 }, false)
+ tracetag_valid({ :tag => 'a/b' }, false)
+ tracetag_valid({ :tag => 'a;b' }, false)
+ tracetag_valid({ :tag => 'a.b' }, false)
+ tracetag_valid({ :tag => 'a,b' }, false)
+ tracetag_valid({ :tag => 'a?b' }, false)
end
-private
+ private
def tracetag_valid(attrs, result = true)
entry = Tracetag.new(gpx_file_tags(:first_trace_1).attributes)
newUP.k = up.k
newUP.v = "some other value"
assert_not_equal newUP.v, up.v
- assert_raise (ActiveRecord::RecordNotUnique) {newUP.save}
+ assert_raise (ActiveRecord::RecordNotUnique) { newUP.save }
end
def test_check_valid_length
(1..255).each do |i|
up = UserPreference.new
up.user = users(:normal_user)
- up.k = key*i
- up.v = val*i
+ up.k = key * i
+ up.v = val * i
assert up.valid?
assert up.save!
resp = UserPreference.find(up.id)
- assert_equal key*i, resp.k, "User preference with #{i} #{key} chars (i.e. #{key.length*i} bytes) fails"
- assert_equal val*i, resp.v, "User preference with #{i} #{val} chars (i.e. #{val.length*i} bytes) fails"
+ assert_equal key * i, resp.k, "User preference with #{i} #{key} chars (i.e. #{key.length * i} bytes) fails"
+ assert_equal val * i, resp.v, "User preference with #{i} #{val} chars (i.e. #{val.length * i} bytes) fails"
end
end
def test_check_invalid_length
key = "k"
val = "v"
- [0,256].each do |i|
+ [0, 256].each do |i|
up = UserPreference.new
up.user = users(:normal_user)
- up.k = key*i
- up.v = val*i
+ up.k = key * i
+ up.v = val * i
assert_equal false, up.valid?
- assert_raise(ActiveRecord::RecordInvalid) {up.save!}
+ assert_raise(ActiveRecord::RecordInvalid) { up.save! }
end
end
-
end
end
def test_email_valid
- ok = %w{ a@s.com test@shaunmcdonald.me.uk hello_local@ping-d.ng
- test_local@openstreetmap.org test-local@example.com }
- bad = %w{ hi ht@ n@ @.com help@.me.uk help"hi.me.uk も対@応します
- 輕觸搖晃的遊戲@ah.com も対応します@s.name }
+ ok = %w(a@s.com test@shaunmcdonald.me.uk hello_local@ping-d.ng
+ test_local@openstreetmap.org test-local@example.com)
+ bad = %w(hi ht@ n@ @.com help@.me.uk help"hi.me.uk も対@応します
+ 輕觸搖晃的遊戲@ah.com も対応します@s.name)
ok.each do |name|
user = users(:normal_user)
# Due to sanitisation in the view some of these that you might not
# expact are allowed
# However, would they affect the xml planet dumps?
- ok = [ "Name", "'me", "he\"", "<hr>", "*ho", "\"help\"@",
- "vergrößern", "ルシステムにも対応します", "輕觸搖晃的遊戲" ]
+ ok = ["Name", "'me", "he\"", "<hr>", "*ho", "\"help\"@",
+ "vergrößern", "ルシステムにも対応します", "輕觸搖晃的遊戲"]
# These need to be 3 chars in length, otherwise the length test above
# should be used.
- bad = [ "<hr/>", "test@example.com", "s/f", "aa/", "aa;", "aa.",
- "aa,", "aa?", "/;.,?", "も対応します/", "#ping",
- "foo\x1fbar", "foo\x7fbar", "foo\ufffebar", "foo\uffffbar",
- "new", "terms", "save", "confirm", "confirm-email",
- "go_public", "reset-password", "forgot-password", "suspended" ]
+ bad = ["<hr/>", "test@example.com", "s/f", "aa/", "aa;", "aa.",
+ "aa,", "aa?", "/;.,?", "も対応します/", "#ping",
+ "foo\x1fbar", "foo\x7fbar", "foo\ufffebar", "foo\uffffbar",
+ "new", "terms", "save", "confirm", "confirm-email",
+ "go_public", "reset-password", "forgot-password", "suspended"]
ok.each do |display_name|
user = users(:normal_user)
user.display_name = display_name
assert_equal 1, Friend.count
norm = users(:normal_user)
sec = users(:public_user)
- #friend = Friend.new
- #friend.befriender = norm
- #friend.befriendee = sec
- #friend.save
+ # friend = Friend.new
+ # friend.befriender = norm
+ # friend.befriendee = sec
+ # friend.save
assert_equal [sec], norm.nearby
assert_equal 1, norm.nearby.size
assert_equal 1, Friend.count
assert !users(:public_user).is_friends_with?(users(:inactive_user))
assert !users(:inactive_user).is_friends_with?(users(:normal_user))
assert !users(:inactive_user).is_friends_with?(users(:public_user))
- #Friend.delete(friend)
- #assert_equal 0, Friend.count
+ # Friend.delete(friend)
+ # assert_equal 0, Friend.count
end
def test_user_preferred_editor
def test_languages
user = users(:normal_user)
- assert_equal [ "en" ], user.languages
- user.languages = [ "de", "fr", "en" ]
- assert_equal [ "de", "fr", "en" ], user.languages
- user.languages = [ "fr", "de", "sl" ]
+ assert_equal ["en"], user.languages
+ user.languages = %w(de fr en)
+ assert_equal %w(de fr en), user.languages
+ user.languages = %w(fr de sl)
assert_equal "de", user.preferred_language
- assert_equal "de", user.preferred_language_from(["en", "sl", "de", "es"])
+ assert_equal "de", user.preferred_language_from(%w(en sl de es))
end
def test_visible?
def test_user_token_count
assert_equal 0, UserToken.count
end
-
end
(0..255).each do |i|
tag = WayTag.new
tag.way_id = current_way_tags(:t1).way_id
- tag.k = key*i
+ tag.k = key * i
tag.v = current_way_tags(:t1).v
assert tag.valid?
end
tag = WayTag.new
tag.way_id = current_way_tags(:t1).way_id
tag.k = "k"
- tag.v = val*i
+ tag.v = val * i
assert tag.valid?
end
end
def test_length_key_invalid
- ["k"*256].each do |i|
+ ["k" * 256].each do |i|
tag = WayTag.new
tag.way_id = current_way_tags(:t1).way_id
tag.k = i
end
def test_length_value_invalid
- ["v"*256].each do |i|
+ ["v" * 256].each do |i|
tag = WayTag.new
tag.way_id = current_way_tags(:t1).way_id
tag.k = "k"
tag.v = current_way_tags(:t1).v
assert tag.new_record?
assert !tag.valid?
- assert_raise(ActiveRecord::RecordInvalid) {tag.save!}
+ assert_raise(ActiveRecord::RecordInvalid) { tag.save! }
assert tag.new_record?
end
end
def test_bbox
node = current_nodes(:used_node_1)
- [ :visible_way,
- :invisible_way,
- :used_way ].each do |way_symbol|
+ [:visible_way,
+ :invisible_way,
+ :used_way].each do |way_symbol|
way = current_ways(way_symbol)
assert_equal node.bbox.min_lon, way.bbox.min_lon, 'min_lon'
assert_equal node.bbox.min_lat, way.bbox.min_lat, 'min_lat'
way = Way.find(current_ways(:visible_way).id)
assert way.valid?
# it already has 1 node
- 1.upto((MAX_NUMBER_OF_WAY_NODES) / 2) {
+ 1.upto((MAX_NUMBER_OF_WAY_NODES) / 2) do
way.add_nd_num(current_nodes(:used_node_1).id)
way.add_nd_num(current_nodes(:used_node_2).id)
- }
+ end
way.save
- #print way.nds.size
+ # print way.nds.size
assert way.valid?
way.add_nd_num(current_nodes(:visible_node).id)
assert way.valid?
def test_from_xml_no_id
noid = "<osm><way version='12' changeset='23' /></osm>"
- assert_nothing_raised(OSM::APIBadXMLError) {
+ assert_nothing_raised(OSM::APIBadXMLError) do
Way.from_xml(noid, true)
- }
- message = assert_raise(OSM::APIBadXMLError) {
+ end
+ message = assert_raise(OSM::APIBadXMLError) do
Way.from_xml(noid, false)
- }
+ end
assert_match /ID is required when updating/, message.message
end
def test_from_xml_no_changeset_id
nocs = "<osm><way id='123' version='23' /></osm>"
- message_create = assert_raise(OSM::APIBadXMLError) {
+ message_create = assert_raise(OSM::APIBadXMLError) do
Way.from_xml(nocs, true)
- }
+ end
assert_match /Changeset id is missing/, message_create.message
- message_update = assert_raise(OSM::APIBadXMLError) {
+ message_update = assert_raise(OSM::APIBadXMLError) do
Way.from_xml(nocs, false)
- }
+ end
assert_match /Changeset id is missing/, message_update.message
end
def test_from_xml_no_version
no_version = "<osm><way id='123' changeset='23' /></osm>"
- assert_nothing_raised(OSM::APIBadXMLError) {
+ assert_nothing_raised(OSM::APIBadXMLError) do
Way.from_xml(no_version, true)
- }
- message_update = assert_raise(OSM::APIBadXMLError) {
+ end
+ message_update = assert_raise(OSM::APIBadXMLError) do
Way.from_xml(no_version, false)
- }
+ end
assert_match /Version is required when updating/, message_update.message
end
id_list = ["", "0", "00", "0.0", "a"]
id_list.each do |id|
zero_id = "<osm><way id='#{id}' changeset='33' version='23' /></osm>"
- assert_nothing_raised(OSM::APIBadUserInput) {
+ assert_nothing_raised(OSM::APIBadUserInput) do
Way.from_xml(zero_id, true)
- }
- message_update = assert_raise(OSM::APIBadUserInput) {
+ end
+ message_update = assert_raise(OSM::APIBadUserInput) do
Way.from_xml(zero_id, false)
- }
+ end
assert_match /ID of way cannot be zero when updating/, message_update.message
end
end
def test_from_xml_no_text
no_text = ""
- message_create = assert_raise(OSM::APIBadXMLError) {
+ message_create = assert_raise(OSM::APIBadXMLError) do
Way.from_xml(no_text, true)
- }
+ end
assert_match /Must specify a string with one or more characters/, message_create.message
- message_update = assert_raise(OSM::APIBadXMLError) {
+ message_update = assert_raise(OSM::APIBadXMLError) do
Way.from_xml(no_text, false)
- }
+ end
assert_match /Must specify a string with one or more characters/, message_update.message
end
def test_from_xml_no_k_v
nokv = "<osm><way id='23' changeset='23' version='23'><tag /></way></osm>"
- message_create = assert_raise(OSM::APIBadXMLError) {
+ message_create = assert_raise(OSM::APIBadXMLError) do
Way.from_xml(nokv, true)
- }
+ end
assert_match /tag is missing key/, message_create.message
- message_update = assert_raise(OSM::APIBadXMLError) {
+ message_update = assert_raise(OSM::APIBadXMLError) do
Way.from_xml(nokv, false)
- }
+ end
assert_match /tag is missing key/, message_update.message
end
def test_from_xml_no_v
no_v = "<osm><way id='23' changeset='23' version='23'><tag k='key' /></way></osm>"
- message_create = assert_raise(OSM::APIBadXMLError) {
+ message_create = assert_raise(OSM::APIBadXMLError) do
Way.from_xml(no_v, true)
- }
+ end
assert_match /tag is missing value/, message_create.message
- message_update = assert_raise(OSM::APIBadXMLError) {
+ message_update = assert_raise(OSM::APIBadXMLError) do
Way.from_xml(no_v, false)
- }
+ end
assert_match /tag is missing value/, message_update.message
end
def test_from_xml_duplicate_k
dupk = "<osm><way id='23' changeset='23' version='23'><tag k='dup' v='test' /><tag k='dup' v='tester' /></way></osm>"
- message_create = assert_raise(OSM::APIDuplicateTagsError) {
+ message_create = assert_raise(OSM::APIDuplicateTagsError) do
Way.from_xml(dupk, true)
- }
+ end
assert_equal "Element way/ has duplicate tags with key dup", message_create.message
- message_update = assert_raise(OSM::APIDuplicateTagsError) {
+ message_update = assert_raise(OSM::APIDuplicateTagsError) do
Way.from_xml(dupk, false)
- }
+ end
assert_equal "Element way/23 has duplicate tags with key dup", message_update.message
end
def test_containing_relation_members
way = current_ways(:used_way)
crm = Way.find(way.id).containing_relation_members.order(:relation_id)
-# assert_equal 1, crm.size
+ # assert_equal 1, crm.size
assert_equal 1, crm.first.relation_id
assert_equal "Way", crm.first.member_type
assert_equal way.id, crm.first.member_id
class ActiveSupport::TestCase
# Load standard fixtures needed to test API methods
def self.api_fixtures
- #print "setting up the api_fixtures"
+ # print "setting up the api_fixtures"
fixtures :users, :user_roles, :changesets, :changeset_tags
fixtures :current_nodes, :nodes
set_fixture_class :current_nodes => Node
set_fixture_class :nodes => OldNode
- fixtures :current_node_tags,:node_tags
+ fixtures :current_node_tags, :node_tags
set_fixture_class :current_node_tags => NodeTag
set_fixture_class :node_tags => OldNodeTag
# Not sure this is the best response we could give
def assert_inactive_user(msg = "an inactive user shouldn't be able to access the API")
assert_response :unauthorized, msg
- #assert_equal @response.headers['Error'], ""
+ # assert_equal @response.headers['Error'], ""
end
- def assert_no_missing_translations(msg="")
+ def assert_no_missing_translations(msg = "")
assert_select "span[class=translation_missing]", false, "Missing translation #{msg}"
end
# Set things up for OpenID testing
def openid_setup
- begin
- # Test if the ROTS (Ruby OpenID Test Server) is already running
- rots_response = Net::HTTP.get_response(URI.parse("http://localhost:1123/"))
- rescue
- # It isn't, so start a new instance.
- rots = IO.popen("#{Rails.root}/vendor/gems/rots-0.2.1/bin/rots --silent")
-
- # Wait for up to 30 seconds for the server to start and respond before continuing
- for i in (1 .. 30)
- begin
- sleep 1
- rots_response = Net::HTTP.get_response(URI.parse("http://localhost:1123/"))
- # If the rescue block doesn't fire, ROTS is up and running and we can continue
- break
- rescue
- # If the connection failed, do nothing and repeat the loop
- end
+ rots_response = Net::HTTP.get_response(URI.parse("http://localhost:1123/"))
+ rescue
+ # It isn't, so start a new instance.
+ rots = IO.popen("#{Rails.root}/vendor/gems/rots-0.2.1/bin/rots --silent")
+
+ # Wait for up to 30 seconds for the server to start and respond before continuing
+ for i in (1..30)
+ begin
+ sleep 1
+ rots_response = Net::HTTP.get_response(URI.parse("http://localhost:1123/"))
+ # If the rescue block doesn't fire, ROTS is up and running and we can continue
+ break
+ rescue
+ # If the connection failed, do nothing and repeat the loop
end
+ end
- # Arrange to kill the process when we exit - note that we need
- # to kill it really har due to a bug in ROTS
- Kernel.at_exit do
- Process.kill("KILL", rots.pid)
- end
+ # Arrange to kill the process when we exit - note that we need
+ # to kill it really har due to a bug in ROTS
+ Kernel.at_exit do
+ Process.kill("KILL", rots.pid)
end
end
openid_response_uri = URI(openid_response['Location'])
openid_response_qs = Rack::Utils.parse_query(openid_response_uri.query)
- return openid_response_qs
+ openid_response_qs
end
-
# Add more helper methods to be used by all tests here...
end