From ef7f3d800cbdd49b692df10d312e5fd880e2e938 Mon Sep 17 00:00:00 2001 From: Tom Hughes Date: Mon, 16 Feb 2015 19:02:59 +0000 Subject: [PATCH] Fix most auto-correctable rubocop issues --- .rubocop.yml | 3 + .rubocop_todo.yml | 399 +----------------- app/controllers/amf_controller.rb | 365 ++++++++-------- app/controllers/api_controller.rb | 37 +- app/controllers/application_controller.rb | 117 ++--- app/controllers/browse_controller.rb | 10 +- app/controllers/changeset_controller.rb | 67 ++- app/controllers/diary_entry_controller.rb | 26 +- app/controllers/export_controller.rb | 7 +- app/controllers/geocoder_controller.rb | 159 ++++--- app/controllers/message_controller.rb | 26 +- app/controllers/node_controller.rb | 16 +- app/controllers/notes_controller.rb | 74 ++-- app/controllers/oauth_clients_controller.rb | 10 +- app/controllers/oauth_controller.rb | 4 +- app/controllers/old_controller.rb | 20 +- app/controllers/old_node_controller.rb | 1 - app/controllers/old_relation_controller.rb | 1 - app/controllers/old_way_controller.rb | 1 - app/controllers/redactions_controller.rb | 6 +- app/controllers/relation_controller.rb | 28 +- app/controllers/search_controller.rb | 22 +- app/controllers/site_controller.rb | 16 +- app/controllers/swf_controller.rb | 359 ++++++++-------- app/controllers/trace_controller.rb | 62 ++- app/controllers/user_blocks_controller.rb | 20 +- app/controllers/user_controller.rb | 70 +-- app/controllers/user_preference_controller.rb | 12 +- app/controllers/user_roles_controller.rb | 5 +- app/controllers/way_controller.rb | 12 +- app/helpers/application_helper.rb | 12 +- app/helpers/browse_helper.rb | 35 +- app/helpers/geocoder_helper.rb | 8 +- app/helpers/note_helper.rb | 13 +- app/helpers/user_helper.rb | 2 +- app/helpers/user_roles_helper.rb | 4 +- app/models/access_token.rb | 2 +- app/models/acl.rb | 6 +- app/models/changeset.rb | 80 ++-- app/models/changeset_comment.rb | 2 +- app/models/client_application.rb | 28 +- app/models/diary_comment.rb | 2 +- app/models/diary_entry.rb | 10 +- app/models/language.rb | 2 +- app/models/message.rb | 4 +- app/models/node.rb | 99 +++-- app/models/note.rb | 14 +- app/models/note_comment.rb | 2 +- app/models/notifier.rb | 6 +- app/models/oauth2_token.rb | 4 +- app/models/oauth2_verifier.rb | 6 +- app/models/oauth_token.rb | 8 +- app/models/old_node.rb | 38 +- app/models/old_relation.rb | 44 +- app/models/old_way.rb | 50 +-- app/models/relation.rb | 152 ++++--- app/models/request_token.rb | 12 +- app/models/trace.rb | 108 +++-- app/models/tracepoint.rb | 8 +- app/models/user.rb | 110 ++--- app/models/user_block.rb | 12 +- app/models/user_preference.rb | 7 +- app/models/user_role.rb | 2 +- app/models/user_token.rb | 6 +- app/models/way.rb | 130 +++--- config/application.rb | 12 +- config/initializers/abstract_adapter.rb | 3 +- config/initializers/field_error.rb | 4 +- config/initializers/i18n.rb | 4 +- config/initializers/libxml.rb | 2 +- config/initializers/memory_limits.rb | 12 +- config/initializers/paperclip.rb | 2 +- config/initializers/piwik.rb | 2 +- config/initializers/potlatch.rb | 2 +- config/initializers/r2.rb | 2 +- config/initializers/router.rb | 2 +- config/initializers/sanitize.rb | 4 +- config/initializers/streaming.rb | 2 +- config/initializers/tempfile.rb | 2 +- config/preinitializer.rb | 4 +- config/routes.rb | 2 +- db/migrate/001_create_osm_db.rb | 17 +- db/migrate/002_cleanup_osm_db.rb | 6 +- db/migrate/004_user_enhancements.rb | 4 +- db/migrate/005_tile_tracepoints.rb | 2 +- db/migrate/006_tile_nodes.rb | 12 +- db/migrate/007_add_relations.rb | 14 +- db/migrate/008_remove_segments.rb | 23 +- db/migrate/010_diary_comments.rb | 3 +- db/migrate/013_add_email_valid.rb | 2 +- .../020_populate_node_tags_and_remove.rb | 22 +- db/migrate/021_move_to_innodb.rb | 40 +- db/migrate/022_key_constraints.rb | 2 +- db/migrate/023_add_changesets.rb | 15 +- db/migrate/028_add_more_changeset_indexes.rb | 2 +- db/migrate/030_add_foreign_keys.rb | 2 +- db/migrate/034_create_languages.rb | 2 +- db/migrate/038_add_message_sender_index.rb | 4 +- .../039_add_more_controls_to_gpx_files.rb | 2 +- db/migrate/040_create_oauth_tables.rb | 2 - db/migrate/041_add_fine_o_auth_permissions.rb | 2 +- db/migrate/044_create_user_roles.rb | 2 +- db/migrate/051_add_status_to_user.rb | 2 +- db/migrate/053_add_map_bug_tables.rb | 2 +- db/migrate/057_add_map_bug_comment_event.rb | 2 +- ...120208122334_merge_acl_address_and_mask.rb | 2 +- db/migrate/20120214210114_add_text_format.rb | 2 +- lib/bounding_box.rb | 29 +- lib/classic_pagination/pagination.rb | 61 ++- lib/classic_pagination/pagination_helper.rb | 7 +- lib/consistency_validations.rb | 30 +- lib/country.rb | 4 +- lib/daemons/gpx_import.rb | 10 +- lib/daemons/gpx_import_ctl | 8 +- lib/diff_reader.rb | 36 +- lib/editors.rb | 4 +- lib/geo_record.rb | 14 +- lib/gpx.rb | 20 +- lib/id.rb | 2 +- lib/migrate.rb | 2 +- lib/nominatim.rb | 6 +- lib/not_redactable.rb | 4 +- lib/osm.rb | 37 +- lib/output_compression/output_compression.rb | 2 +- lib/password_hash.rb | 10 +- lib/potlatch.rb | 201 +++++---- lib/quad_tile.rb | 18 +- lib/quova.rb | 6 +- lib/redactable.rb | 4 +- lib/rich_text.rb | 30 +- lib/short_link.rb | 14 +- lib/tasks/add_version_to_nodes.rake | 14 +- lib/utf8.rb | 4 +- lib/validators.rb | 2 - script/daemons | 2 +- script/deliver-message | 2 +- script/locale/po2yaml | 10 +- script/locale/yaml2po | 30 +- script/statistics | 8 +- script/update-spam-blocks | 24 +- test/controllers/amf_controller_test.rb | 130 +++--- test/controllers/api_controller_test.rb | 68 +-- test/controllers/browse_controller_test.rb | 8 +- test/controllers/changeset_controller_test.rb | 275 ++++++------ .../diary_entry_controller_test.rb | 112 ++--- .../controllers/directions_controller_test.rb | 2 - test/controllers/export_controller_test.rb | 6 +- test/controllers/geocoder_controller_test.rb | 177 ++++---- test/controllers/message_controller_test.rb | 20 +- test/controllers/node_controller_test.rb | 83 ++-- test/controllers/notes_controller_test.rb | 182 ++++---- .../oauth_clients_controller_test.rb | 32 +- test/controllers/old_node_controller_test.rb | 19 +- .../old_relation_controller_test.rb | 2 +- test/controllers/old_way_controller_test.rb | 5 +- test/controllers/relation_controller_test.rb | 148 +++---- test/controllers/site_controller_test.rb | 14 +- test/controllers/trace_controller_test.rb | 92 ++-- .../user_blocks_controller_test.rb | 26 +- test/controllers/user_controller_test.rb | 66 +-- .../controllers/user_roles_controller_test.rb | 4 - test/controllers/way_controller_test.rb | 77 ++-- test/helpers/asset_helper_test.rb | 2 +- test/helpers/browse_helper_test.rb | 18 +- test/integration/client_application_test.rb | 13 +- test/integration/oauth_test.rb | 74 ++-- test/integration/short_links_test.rb | 4 +- test/integration/user_blocks_test.rb | 6 +- .../user_changeset_comments_test.rb | 2 +- test/integration/user_creation_test.rb | 50 +-- test/integration/user_diaries_test.rb | 8 +- test/integration/user_login_test.rb | 62 +-- test/integration/user_roles_test.rb | 6 +- test/integration/user_terms_seen_test.rb | 10 +- test/lib/bounding_box_test.rb | 95 ++--- test/lib/i18n_test.rb | 22 +- test/lib/rich_text_test.rb | 2 +- test/lib/short_link_test.rb | 8 +- test/models/changeset_tag_test.rb | 10 +- test/models/changeset_test.rb | 48 +-- test/models/diary_entry_test.rb | 26 +- test/models/friend_test.rb | 1 - test/models/message_test.rb | 10 +- test/models/node_tag_test.rb | 12 +- test/models/node_test.rb | 112 ++--- test/models/note_comment_test.rb | 12 +- test/models/note_test.rb | 4 +- test/models/oauth_nonce_test.rb | 1 - test/models/oauth_token_test.rb | 1 - test/models/old_node_tag_test.rb | 10 +- test/models/old_node_test.rb | 4 +- test/models/old_relation_tag_test.rb | 10 +- test/models/old_way_tag_test.rb | 10 +- test/models/old_way_test.rb | 8 +- test/models/redaction_test.rb | 1 - test/models/relation_tag_test.rb | 10 +- test/models/relation_test.rb | 66 +-- test/models/trace_test.rb | 24 +- test/models/tracepoint_test.rb | 1 - test/models/tracetag_test.rb | 22 +- test/models/user_preference_test.rb | 19 +- test/models/user_test.rb | 44 +- test/models/user_token_test.rb | 1 - test/models/way_tag_test.rb | 10 +- test/models/way_test.rb | 78 ++-- test/test_helper.rb | 52 ++- 206 files changed, 2939 insertions(+), 3487 deletions(-) diff --git a/.rubocop.yml b/.rubocop.yml index cc32da4b9..8187b2696 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1 +1,4 @@ inherit_from: .rubocop_todo.yml + +Style/BracesAroundHashParameters: + EnforcedStyle: context_dependent diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 0c09cb1b7..75f088e1a 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -1,5 +1,5 @@ # 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 @@ -18,21 +18,11 @@ Lint/AmbiguousRegexpLiteral: 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 @@ -62,26 +52,6 @@ Lint/RescueException: 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 @@ -111,10 +81,10 @@ Metrics/ClassLength: 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. @@ -130,59 +100,14 @@ Metrics/ParameterLists: 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: @@ -193,118 +118,36 @@ 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: @@ -331,79 +174,25 @@ Style/GuardClause: 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 @@ -413,17 +202,6 @@ Style/NestedTernaryOperator: 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: @@ -437,18 +215,6 @@ Style/OneLineConditional: 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: @@ -459,32 +225,11 @@ 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 @@ -493,112 +238,16 @@ Style/RegexpLiteral: 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. @@ -615,25 +264,7 @@ Style/StringLiteralsInInterpolation: 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 @@ -647,23 +278,7 @@ Style/UnlessElse: 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 diff --git a/app/controllers/amf_controller.rb b/app/controllers/amf_controller.rb index 19b7d5de8..75dc16458 100644 --- a/app/controllers/amf_controller.rb +++ b/app/controllers/amf_controller.rb @@ -47,21 +47,21 @@ class AmfController < ApplicationController 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 @@ -75,22 +75,22 @@ class AmfController < ApplicationController 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 @@ -102,7 +102,7 @@ class AmfController < ApplicationController 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] @@ -111,15 +111,15 @@ class AmfController < ApplicationController 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 @@ -130,14 +130,14 @@ class AmfController < ApplicationController # 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 @@ -145,12 +145,12 @@ class AmfController < ApplicationController 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! @@ -158,12 +158,12 @@ class AmfController < ApplicationController 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 @@ -171,9 +171,9 @@ class AmfController < ApplicationController 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 @@ -181,7 +181,7 @@ class AmfController < ApplicationController # 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? @@ -200,12 +200,12 @@ class AmfController < ApplicationController 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) @@ -213,14 +213,14 @@ class AmfController < ApplicationController 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 @@ -247,8 +247,8 @@ class AmfController < ApplicationController # 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 @@ -258,17 +258,17 @@ class AmfController < ApplicationController 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 @@ -276,9 +276,9 @@ class AmfController < ApplicationController 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] @@ -289,8 +289,8 @@ class AmfController < ApplicationController # 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 @@ -301,9 +301,9 @@ class AmfController < ApplicationController 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 @@ -311,8 +311,8 @@ class AmfController < ApplicationController # 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) @@ -324,10 +324,10 @@ class AmfController < ApplicationController 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 @@ -356,7 +356,7 @@ class AmfController < ApplicationController # 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 @@ -368,7 +368,7 @@ class AmfController < ApplicationController 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 @@ -381,9 +381,9 @@ class AmfController < ApplicationController 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 @@ -399,70 +399,65 @@ class AmfController < ApplicationController # 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 0 then + if searchterm.to_i > 0 query = query.where(:id => searchterm.to_i) else query = query.where("MATCH(name) AGAINST (?)", searchterm).limit(21) @@ -470,7 +465,7 @@ class AmfController < ApplicationController gpxs = query.collect do |gpx| [gpx.id, gpx.name, gpx.description] end - [0,'',gpxs] + [0, '', gpxs] end end @@ -484,10 +479,10 @@ class AmfController < ApplicationController # 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 @@ -497,14 +492,14 @@ class AmfController < ApplicationController 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 @@ -520,13 +515,13 @@ class AmfController < ApplicationController # 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 @@ -581,7 +576,7 @@ class AmfController < ApplicationController 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 @@ -608,26 +603,25 @@ class AmfController < ApplicationController # 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| @@ -636,8 +630,8 @@ class AmfController < ApplicationController 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 @@ -647,7 +641,7 @@ class AmfController < ApplicationController 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') @@ -659,8 +653,8 @@ class AmfController < ApplicationController 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 @@ -668,9 +662,9 @@ class AmfController < ApplicationController # -- 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 @@ -678,18 +672,18 @@ class AmfController < ApplicationController 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 @@ -702,7 +696,6 @@ class AmfController < ApplicationController # and we don't want to delete it end end - end # transaction [0, '', originalway, way.id, renumberednodes, way.version, nodeversions, deletednodes] @@ -719,13 +712,13 @@ class AmfController < ApplicationController # 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 @@ -733,11 +726,11 @@ class AmfController < ApplicationController 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 @@ -753,14 +746,13 @@ class AmfController < ApplicationController 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 @@ -776,8 +768,8 @@ class AmfController < ApplicationController # # 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 @@ -804,18 +796,17 @@ class AmfController < ApplicationController # 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) @@ -827,7 +818,7 @@ class AmfController < ApplicationController # -- 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 @@ -835,19 +826,17 @@ class AmfController < ApplicationController 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 @@ -857,12 +846,12 @@ class AmfController < ApplicationController # 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 @@ -876,14 +865,14 @@ class AmfController < ApplicationController 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" @@ -891,14 +880,14 @@ class AmfController < ApplicationController 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 @@ -907,12 +896,12 @@ class AmfController < ApplicationController 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 @@ -921,19 +910,19 @@ class AmfController < ApplicationController 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 @@ -941,7 +930,7 @@ class AmfController < ApplicationController 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 @@ -950,12 +939,12 @@ class AmfController < ApplicationController 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} @@ -964,20 +953,20 @@ class AmfController < ApplicationController 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 diff --git a/app/controllers/api_controller.rb b/app/controllers/api_controller.rb index 36bb0bff3..1b9a1ad69 100644 --- a/app/controllers/api_controller.rb +++ b/app/controllers/api_controller.rb @@ -1,5 +1,4 @@ class ApiController < ApplicationController - skip_before_filter :verify_authenticity_token before_filter :check_api_readable, :except => [:capabilities] before_filter :setup_user_auth, :only => [:permissions] @@ -9,12 +8,12 @@ class ApiController < ApplicationController # 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 @@ -127,7 +126,7 @@ class ApiController < ApplicationController 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 @@ -146,19 +145,19 @@ class ApiController < ApplicationController # 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 @@ -179,7 +178,7 @@ class ApiController < ApplicationController 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) @@ -195,7 +194,7 @@ class ApiController < ApplicationController # 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. @@ -213,7 +212,7 @@ class ApiController < ApplicationController 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 @@ -222,11 +221,11 @@ class ApiController < ApplicationController 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' @@ -264,11 +263,11 @@ class ApiController < ApplicationController 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 diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index c335dcaf4..e3f0391d1 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -9,29 +9,29 @@ class ApplicationController < ActionController::Base 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 @@ -47,7 +47,7 @@ class ApplicationController < ActionController::Base 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 ## @@ -87,26 +87,32 @@ class ApplicationController < ActionController::Base 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 @@ -131,7 +137,7 @@ class ApplicationController < ActionController::Base # 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? @@ -154,14 +160,14 @@ class ApplicationController < ActionController::Base # 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 @@ -182,7 +188,7 @@ class ApplicationController < ActionController::Base # 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 @@ -191,7 +197,7 @@ class ApplicationController < ActionController::Base 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 @@ -201,8 +207,8 @@ class ApplicationController < ActionController::Base 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 @@ -244,7 +250,7 @@ class ApplicationController < ActionController::Base status = :readonly end end - return status + status end def gpx_status @@ -252,7 +258,7 @@ class ApplicationController < ActionController::Base if status == :online status = :offline if STATUS == :gpx_offline end - return status + status end def require_public_data @@ -271,7 +277,7 @@ class ApplicationController < ActionController::Base # 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" @@ -304,15 +310,15 @@ class ApplicationController < ActionController::Base 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 @@ -326,25 +332,23 @@ class ApplicationController < ActionController::Base 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 ## @@ -352,7 +356,7 @@ class ApplicationController < ActionController::Base # 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 ## @@ -374,7 +378,7 @@ class ApplicationController < ActionController::Base 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 @@ -432,14 +436,14 @@ class ApplicationController < ActionController::Base 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 @@ -448,22 +452,22 @@ class ApplicationController < ActionController::Base 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 @@ -473,11 +477,10 @@ private # 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 diff --git a/app/controllers/browse_controller.rb b/app/controllers/browse_controller.rb index d3a474c14..3dfcd18e6 100644 --- a/app/controllers/browse_controller.rb +++ b/app/controllers/browse_controller.rb @@ -3,7 +3,7 @@ class BrowseController < ApplicationController 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 @@ -58,14 +58,14 @@ class BrowseController < ApplicationController 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 diff --git a/app/controllers/changeset_controller.rb b/app/controllers/changeset_controller.rb index eaa87df7b..3f693a996 100644 --- a/app/controllers/changeset_controller.rb +++ b/app/controllers/changeset_controller.rb @@ -78,8 +78,8 @@ class ChangesetController < ApplicationController 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? @@ -257,8 +257,8 @@ class ChangesetController < ApplicationController ## # 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 @@ -275,14 +275,14 @@ class ChangesetController < ApplicationController 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") @@ -315,8 +315,8 @@ class ChangesetController < ApplicationController # 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 @@ -324,14 +324,12 @@ class ChangesetController < ApplicationController # 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| @@ -351,15 +349,15 @@ class ChangesetController < ApplicationController # 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 @@ -372,15 +370,15 @@ class ChangesetController < ApplicationController # 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) @@ -393,7 +391,7 @@ class ChangesetController < ApplicationController # 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 @@ -412,7 +410,7 @@ class ChangesetController < ApplicationController # 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 @@ -450,7 +448,8 @@ class ChangesetController < ApplicationController end end -private + private + #------------------------------------------------------------ # utility functions below. #------------------------------------------------------------ @@ -474,21 +473,21 @@ private ## # 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. @@ -497,7 +496,7 @@ private # 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 @@ -514,7 +513,7 @@ private 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) @@ -566,9 +565,9 @@ private 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 @@ -577,17 +576,17 @@ private # 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 diff --git a/app/controllers/diary_entry_controller.rb b/app/controllers/diary_entry_controller.rb index a611c19e9..5129963f8 100644 --- a/app/controllers/diary_entry_controller.rb +++ b/app/controllers/diary_entry_controller.rb @@ -38,12 +38,12 @@ class DiaryEntryController < ApplicationController 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 @@ -85,19 +85,19 @@ class DiaryEntryController < ApplicationController @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 @@ -131,7 +131,7 @@ class DiaryEntryController < ApplicationController 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]) @@ -180,7 +180,9 @@ class DiaryEntryController < ApplicationController :per_page => 20) @page = (params[:page] || 1).to_i end -private + + private + ## # return permitted diary entry parameters def entry_params @@ -206,17 +208,17 @@ private ## # 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 diff --git a/app/controllers/export_controller.rb b/app/controllers/export_controller.rb index 00eba741f..6a8348fb5 100644 --- a/app/controllers/export_controller.rb +++ b/app/controllers/export_controller.rb @@ -1,21 +1,20 @@ 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] diff --git a/app/controllers/geocoder_controller.rb b/app/controllers/geocoder_controller.rb index 5a3cbebdf..25042c474 100644 --- a/app/controllers/geocoder_controller.rb +++ b/app/controllers/geocoder_controller.rb @@ -38,16 +38,16 @@ class GeocoderController < ApplicationController 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 @@ -58,7 +58,7 @@ class GeocoderController < ApplicationController 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)}") @@ -66,15 +66,15 @@ class GeocoderController < ApplicationController # 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 @@ -83,7 +83,7 @@ class GeocoderController < ApplicationController 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)}") @@ -94,35 +94,35 @@ class GeocoderController < ApplicationController 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 @@ -154,12 +154,10 @@ class GeocoderController < ApplicationController 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| @@ -168,13 +166,13 @@ class GeocoderController < ApplicationController 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 @@ -182,17 +180,17 @@ class GeocoderController < ApplicationController 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 @@ -203,7 +201,7 @@ class GeocoderController < ApplicationController 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}") @@ -214,15 +212,15 @@ class GeocoderController < ApplicationController 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 @@ -233,7 +231,7 @@ class GeocoderController < ApplicationController 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(',')}") @@ -246,15 +244,15 @@ class GeocoderController < ApplicationController 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 @@ -267,7 +265,7 @@ class GeocoderController < ApplicationController 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}") @@ -276,45 +274,45 @@ class GeocoderController < ApplicationController 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) @@ -324,11 +322,11 @@ private 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 @@ -353,7 +351,7 @@ private 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 @@ -366,31 +364,30 @@ private 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 diff --git a/app/controllers/message_controller.rb b/app/controllers/message_controller.rb index c7acc90d8..3cc80c190 100644 --- a/app/controllers/message_controller.rb +++ b/app/controllers/message_controller.rb @@ -38,13 +38,13 @@ class MessageController < ApplicationController 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 @@ -55,7 +55,7 @@ class MessageController < ApplicationController 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 @@ -64,7 +64,7 @@ class MessageController < ApplicationController @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 @@ -72,14 +72,14 @@ class MessageController < ApplicationController 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 @@ -88,7 +88,7 @@ class MessageController < ApplicationController # 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 @@ -105,12 +105,12 @@ class MessageController < ApplicationController 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 @@ -119,7 +119,7 @@ class MessageController < ApplicationController @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] @@ -129,10 +129,12 @@ class MessageController < ApplicationController 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 diff --git a/app/controllers/node_controller.rb b/app/controllers/node_controller.rb index 597aa4a44..cd5b893e3 100644 --- a/app/controllers/node_controller.rb +++ b/app/controllers/node_controller.rb @@ -41,8 +41,8 @@ class NodeController < ApplicationController 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" @@ -55,8 +55,8 @@ class NodeController < ApplicationController 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" @@ -64,14 +64,14 @@ class NodeController < ApplicationController # 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 diff --git a/app/controllers/notes_controller.rb b/app/controllers/notes_controller.rb index e4782449b..5fdda44f4 100644 --- a/app/controllers/notes_controller.rb +++ b/app/controllers/notes_controller.rb @@ -1,5 +1,4 @@ class NotesController < ApplicationController - layout 'site', :only => [:mine] before_filter :check_api_readable @@ -21,10 +20,10 @@ class NotesController < ApplicationController 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 @@ -54,12 +53,12 @@ class NotesController < ApplicationController # 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") @@ -70,7 +69,7 @@ class NotesController < ApplicationController 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! @@ -90,11 +89,11 @@ class NotesController < ApplicationController # 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 @@ -102,9 +101,9 @@ class NotesController < ApplicationController # 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 @@ -122,7 +121,7 @@ class NotesController < ApplicationController # 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 @@ -130,9 +129,9 @@ class NotesController < ApplicationController # 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 @@ -152,7 +151,7 @@ class NotesController < ApplicationController # 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 @@ -160,9 +159,9 @@ class NotesController < ApplicationController # 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 @@ -207,12 +206,12 @@ class NotesController < ApplicationController # 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| @@ -227,7 +226,7 @@ class NotesController < ApplicationController # 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 @@ -235,8 +234,8 @@ class NotesController < ApplicationController # 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 @@ -257,7 +256,7 @@ class NotesController < ApplicationController # 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) @@ -295,7 +294,8 @@ class NotesController < ApplicationController end end -private + private + #------------------------------------------------------------ # utility functions below. #------------------------------------------------------------ @@ -315,10 +315,10 @@ private # 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 @@ -343,7 +343,7 @@ private notes = notes.where("status = 'open'") end - return notes + notes end ## @@ -359,8 +359,8 @@ private 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 diff --git a/app/controllers/oauth_clients_controller.rb b/app/controllers/oauth_clients_controller.rb index 320dab1b5..48074ddd4 100644 --- a/app/controllers/oauth_clients_controller.rb +++ b/app/controllers/oauth_clients_controller.rb @@ -17,7 +17,7 @@ class OauthClientsController < ApplicationController 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" @@ -41,7 +41,7 @@ class OauthClientsController < ApplicationController 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" @@ -54,13 +54,15 @@ class OauthClientsController < ApplicationController 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 diff --git a/app/controllers/oauth_controller.rb b/app/controllers/oauth_controller.rb index c7251f0a7..4f094b981 100644 --- a/app/controllers/oauth_controller.rb +++ b/app/controllers/oauth_controller.rb @@ -35,11 +35,11 @@ class OauthController < ApplicationController 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 diff --git a/app/controllers/old_controller.rb b/app/controllers/old_controller.rb index 82669f504..002da675c 100644 --- a/app/controllers/old_controller.rb +++ b/app/controllers/old_controller.rb @@ -5,22 +5,22 @@ class OldController < ApplicationController 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 @@ -38,7 +38,7 @@ class OldController < ApplicationController end def version - if @old_element.redacted? and not show_redactions? + if @old_element.redacted? && !show_redactions? render :text => "", :status => :forbidden else @@ -72,6 +72,6 @@ class OldController < ApplicationController private def show_redactions? - @user and @user.moderator? and params[:show_redactions] == "true" + @user && @user.moderator? && params[:show_redactions] == "true" end end diff --git a/app/controllers/old_node_controller.rb b/app/controllers/old_node_controller.rb index 75be576d0..a32e299fe 100644 --- a/app/controllers/old_node_controller.rb +++ b/app/controllers/old_node_controller.rb @@ -1,5 +1,4 @@ class OldNodeController < OldController - private def lookup_old_element diff --git a/app/controllers/old_relation_controller.rb b/app/controllers/old_relation_controller.rb index abf37452f..78eca324c 100644 --- a/app/controllers/old_relation_controller.rb +++ b/app/controllers/old_relation_controller.rb @@ -1,5 +1,4 @@ class OldRelationController < OldController - private def lookup_old_element diff --git a/app/controllers/old_way_controller.rb b/app/controllers/old_way_controller.rb index 64fe5b6a7..1daab997a 100644 --- a/app/controllers/old_way_controller.rb +++ b/app/controllers/old_way_controller.rb @@ -1,5 +1,4 @@ class OldWayController < OldController - private def lookup_old_element diff --git a/app/controllers/redactions_controller.rb b/app/controllers/redactions_controller.rb index 6dbe53937..b40c83e0d 100644 --- a/app/controllers/redactions_controller.rb +++ b/app/controllers/redactions_controller.rb @@ -52,9 +52,9 @@ class RedactionsController < ApplicationController 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 diff --git a/app/controllers/relation_controller.rb b/app/controllers/relation_controller.rb index 454e0ef58..f77f722f6 100644 --- a/app/controllers/relation_controller.rb +++ b/app/controllers/relation_controller.rb @@ -17,12 +17,12 @@ class RelationController < ApplicationController # 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 @@ -41,7 +41,7 @@ class RelationController < ApplicationController 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 @@ -52,7 +52,7 @@ class RelationController < ApplicationController 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 @@ -78,7 +78,7 @@ class RelationController < ApplicationController 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. @@ -88,9 +88,9 @@ class RelationController < ApplicationController # 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) @@ -130,14 +130,14 @@ class RelationController < ApplicationController 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 @@ -162,7 +162,7 @@ class RelationController < ApplicationController 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 diff --git a/app/controllers/search_controller.rb b/app/controllers/search_controller.rb index dd7c2febe..7cd6f4ca7 100644 --- a/app/controllers/search_controller.rb +++ b/app/controllers/search_controller.rb @@ -6,23 +6,25 @@ class SearchController < ApplicationController 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' @@ -49,7 +51,7 @@ class SearchController < ApplicationController 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 @@ -59,7 +61,7 @@ class SearchController < ApplicationController 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 @@ -69,11 +71,11 @@ class SearchController < ApplicationController 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 = {} diff --git a/app/controllers/site_controller.rb b/app/controllers/site_controller.rb index e76ee97f6..a133e7b27 100644 --- a/app/controllers/site_controller.rb +++ b/app/controllers/site_controller.rb @@ -10,34 +10,34 @@ class SiteController < ApplicationController 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] @@ -48,7 +48,7 @@ class SiteController < ApplicationController new_params[:anchor] = "map=#{zoom}/#{lat}/#{lon}" - if params.has_key? :layers + if params.key? :layers new_params[:anchor] += "&layers=#{params[:layers]}" end diff --git a/app/controllers/swf_controller.rb b/app/controllers/swf_controller.rb index 02e43a87d..541185d03 100644 --- a/app/controllers/swf_controller.rb +++ b/app/controllers/swf_controller.rb @@ -1,233 +1,216 @@ 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 diff --git a/app/controllers/trace_controller.rb b/app/controllers/trace_controller.rb index e1553cbb0..251c92a68 100644 --- a/app/controllers/trace_controller.rb +++ b/app/controllers/trace_controller.rb @@ -21,7 +21,7 @@ class TraceController < ApplicationController 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 @@ -32,7 +32,7 @@ class TraceController < ApplicationController # 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 @@ -47,15 +47,15 @@ class TraceController < ApplicationController # 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 @@ -73,7 +73,7 @@ class TraceController < ApplicationController @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| @@ -94,8 +94,8 @@ class TraceController < ApplicationController 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' @@ -129,12 +129,12 @@ class TraceController < ApplicationController 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 @@ -148,7 +148,7 @@ class TraceController < ApplicationController 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 @@ -168,9 +168,9 @@ class TraceController < ApplicationController 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 @@ -191,9 +191,9 @@ class TraceController < ApplicationController 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 @@ -209,7 +209,7 @@ class TraceController < ApplicationController @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] @@ -225,7 +225,7 @@ class TraceController < ApplicationController 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 @@ -242,7 +242,7 @@ class TraceController < ApplicationController 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 @@ -258,7 +258,7 @@ class TraceController < ApplicationController 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 @@ -271,8 +271,8 @@ class TraceController < ApplicationController 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 @@ -302,8 +302,8 @@ class TraceController < ApplicationController 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') @@ -341,7 +341,7 @@ class TraceController < ApplicationController end end -private + private def do_create(file, tags, description, visibility) # Sanitise the user's filename @@ -400,7 +400,6 @@ private else @user.preferences.create(:k => "gps.trace.visibility", :v => visibility) end - end def offline_warning @@ -422,5 +421,4 @@ private "public" end end - end diff --git a/app/controllers/user_blocks_controller.rb b/app/controllers/user_blocks_controller.rb index f530eec91..1b2ff8965 100644 --- a/app/controllers/user_blocks_controller.rb +++ b/app/controllers/user_blocks_controller.rb @@ -19,7 +19,7 @@ class UserBlocksController < ApplicationController 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 @@ -39,7 +39,7 @@ class UserBlocksController < ApplicationController :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] ) @@ -60,9 +60,9 @@ class UserBlocksController < ApplicationController 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) @@ -79,7 +79,7 @@ class UserBlocksController < ApplicationController 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 @@ -90,7 +90,7 @@ class UserBlocksController < ApplicationController 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 @@ -100,12 +100,13 @@ class UserBlocksController < ApplicationController 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 @@ -126,12 +127,11 @@ class UserBlocksController < ApplicationController 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 diff --git a/app/controllers/user_controller.rb b/app/controllers/user_controller.rb index ea50113e5..a8bbdee8a 100644 --- a/app/controllers/user_controller.rb +++ b/app/controllers/user_controller.rb @@ -28,10 +28,10 @@ class UserController < ApplicationController 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 @@ -57,7 +57,7 @@ class UserController < ApplicationController 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 @@ -81,7 +81,7 @@ class UserController < ApplicationController @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) @@ -92,9 +92,9 @@ class UserController < ApplicationController 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 @@ -119,9 +119,9 @@ class UserController < ApplicationController @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 @@ -152,7 +152,7 @@ class UserController < ApplicationController 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? @@ -218,7 +218,7 @@ class UserController < ApplicationController 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 @@ -275,7 +275,7 @@ class UserController < ApplicationController end def login - if params[:username] or using_open_id? + if params[:username] || using_open_id? session[:referer] ||= params[:referer] if using_open_id? @@ -333,7 +333,7 @@ class UserController < ApplicationController 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 @@ -366,7 +366,7 @@ class UserController < ApplicationController 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 @@ -398,7 +398,7 @@ class UserController < ApplicationController 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 @@ -406,8 +406,8 @@ class UserController < ApplicationController 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] @@ -486,14 +486,14 @@ class UserController < ApplicationController # 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] @@ -504,7 +504,7 @@ class UserController < ApplicationController end end -private + private ## # handle password authentication @@ -525,7 +525,7 @@ private 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"] @@ -553,8 +553,8 @@ private 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 @@ -585,8 +585,8 @@ private # 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 @@ -616,7 +616,7 @@ private 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 @@ -631,8 +631,8 @@ private # 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 ## @@ -649,7 +649,7 @@ private # - 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 @@ -687,7 +687,7 @@ private 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 @@ -725,7 +725,7 @@ private 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 @@ -752,7 +752,7 @@ private # 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] @@ -760,7 +760,7 @@ private 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 @@ -817,6 +817,6 @@ private render :action => 'blocked' end - not blocked + !blocked end end diff --git a/app/controllers/user_preference_controller.rb b/app/controllers/user_preference_controller.rb index 7d6fc8e23..03cb8f191 100644 --- a/app/controllers/user_preference_controller.rb +++ b/app/controllers/user_preference_controller.rb @@ -33,7 +33,7 @@ class UserPreferenceController < ApplicationController # 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 @@ -46,7 +46,7 @@ class UserPreferenceController < ApplicationController 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 @@ -54,13 +54,9 @@ class UserPreferenceController < ApplicationController 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 diff --git a/app/controllers/user_roles_controller.rb b/app/controllers/user_roles_controller.rb index 2c83971e7..4316c5e94 100644 --- a/app/controllers/user_roles_controller.rb +++ b/app/controllers/user_roles_controller.rb @@ -15,17 +15,18 @@ class UserRolesController < ApplicationController 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 diff --git a/app/controllers/way_controller.rb b/app/controllers/way_controller.rb index 3291ce8b7..0c83b5b92 100644 --- a/app/controllers/way_controller.rb +++ b/app/controllers/way_controller.rb @@ -39,7 +39,7 @@ class WayController < ApplicationController 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 @@ -52,7 +52,7 @@ class WayController < ApplicationController 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 @@ -84,14 +84,14 @@ class WayController < ApplicationController 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 diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 5266bf633..b4a0ad192 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -10,11 +10,11 @@ module ApplicationHelper 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 @@ -25,10 +25,10 @@ module ApplicationHelper 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) @@ -58,7 +58,7 @@ module ApplicationHelper 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 diff --git a/app/helpers/browse_helper.rb b/app/helpers/browse_helper.rb index f4b332f70..45240e082 100644 --- a/app/helpers/browse_helper.rb +++ b/app/helpers/browse_helper.rb @@ -1,5 +1,5 @@ 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 @@ -15,14 +15,14 @@ module BrowseHelper 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 @@ -30,7 +30,7 @@ module BrowseHelper end def link_class(type, object) - classes = [ type ] + classes = [type] if object.redacted? classes << "deleted" @@ -46,7 +46,7 @@ module BrowseHelper 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 @@ -84,15 +84,12 @@ module BrowseHelper 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) @@ -110,7 +107,7 @@ private url = "http://wiki.openstreetmap.org/wiki/#{page}?uselang=#{locale}" end - return url + url end def wikipedia_link(key, value) @@ -136,7 +133,7 @@ private 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 @@ -145,23 +142,23 @@ private 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*$/ @@ -169,6 +166,6 @@ private # "+1 (234) 567-8901 " -> "+1(234)567-8901" valueNoWhitespace = value.gsub(/\s+/, '') - return "tel:#{valueNoWhitespace}" + "tel:#{valueNoWhitespace}" end end diff --git a/app/helpers/geocoder_helper.rb b/app/helpers/geocoder_helper.rb index 04f437a7c..f0663108e 100644 --- a/app/helpers/geocoder_helper.rb +++ b/app/helpers/geocoder_helper.rb @@ -2,21 +2,21 @@ module GeocoderHelper 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 diff --git a/app/helpers/note_helper.rb b/app/helpers/note_helper.rb index e0eef269b..baf5a2721 100644 --- a/app/helpers/note_helper.rb +++ b/app/helpers/note_helper.rb @@ -2,14 +2,14 @@ module NoteHelper 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 @@ -18,8 +18,7 @@ module NoteHelper 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 diff --git a/app/helpers/user_helper.rb b/app/helpers/user_helper.rb index ba37a1334..b5bf30645 100644 --- a/app/helpers/user_helper.rb +++ b/app/helpers/user_helper.rb @@ -62,7 +62,7 @@ module UserHelper # 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 diff --git a/app/helpers/user_roles_helper.rb b/app/helpers/user_roles_helper.rb index 37fbf8634..adc5b22e0 100644 --- a/app/helpers/user_roles_helper.rb +++ b/app/helpers/user_roles_helper.rb @@ -1,10 +1,10 @@ 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}") diff --git a/app/models/access_token.rb b/app/models/access_token.rb index 6e48c996d..2bf226784 100644 --- a/app/models/access_token.rb +++ b/app/models/access_token.rb @@ -8,7 +8,7 @@ class AccessToken < OauthToken before_create :set_authorized_at -protected + protected def set_authorized_at self.authorized_at = Time.now diff --git a/app/models/acl.rb b/app/models/acl.rb index e2f163ea5..0c8996828 100644 --- a/app/models/acl.rb +++ b/app/models/acl.rb @@ -8,14 +8,14 @@ class Acl < ActiveRecord::Base 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 diff --git a/app/models/changeset.rb b/app/models/changeset.rb index 926e82ab6..2001c70be 100644 --- a/app/models/changeset.rb +++ b/app/models/changeset.rb @@ -46,7 +46,7 @@ class Changeset < ActiveRecord::Base # 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 @@ -55,21 +55,19 @@ class Changeset < ActiveRecord::Base 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 @@ -81,12 +79,12 @@ class Changeset < ActiveRecord::Base 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 ## @@ -122,29 +120,27 @@ class Changeset < ActiveRecord::Base 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 @@ -156,11 +152,11 @@ class Changeset < ActiveRecord::Base 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! @@ -185,46 +181,46 @@ class Changeset < ActiveRecord::Base 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? @@ -241,7 +237,7 @@ class Changeset < ActiveRecord::Base # they are just structures for tagging. to get the osmChange of a # changeset, see the download method of the controller. - return el1 + el1 end ## @@ -250,13 +246,13 @@ class Changeset < ActiveRecord::Base # 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 diff --git a/app/models/changeset_comment.rb b/app/models/changeset_comment.rb index 1f037d667..02f68a2fa 100644 --- a/app/models/changeset_comment.rb +++ b/app/models/changeset_comment.rb @@ -8,7 +8,7 @@ class ChangesetComment < ActiveRecord::Base 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 diff --git a/app/models/client_application.rb b/app/models/client_application.rb index fd382629a..6195dfc2e 100644 --- a/app/models/client_application.rb +++ b/app/models/client_application.rb @@ -10,8 +10,8 @@ class ClientApplication < ActiveRecord::Base 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 @@ -27,14 +27,12 @@ class ClientApplication < ActiveRecord::Base 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 @@ -49,8 +47,8 @@ class ClientApplication < ActiveRecord::Base @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 @@ -76,7 +74,7 @@ class ClientApplication < ActiveRecord::Base 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 @@ -86,7 +84,7 @@ protected :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 diff --git a/app/models/diary_comment.rb b/app/models/diary_comment.rb index 5ace3d158..b38240db0 100644 --- a/app/models/diary_comment.rb +++ b/app/models/diary_comment.rb @@ -20,7 +20,7 @@ class DiaryComment < ActiveRecord::Base md5.hexdigest end -private + private def spam_check user.spam_check diff --git a/app/models/diary_entry.rb b/app/models/diary_entry.rb index c0fbac546..a66eb599d 100644 --- a/app/models/diary_entry.rb +++ b/app/models/diary_entry.rb @@ -3,17 +3,17 @@ class DiaryEntry < ActiveRecord::Base 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 @@ -22,7 +22,7 @@ class DiaryEntry < ActiveRecord::Base RichText.new(read_attribute(:body_format), read_attribute(:body)) end -private + private def spam_check user.spam_check diff --git a/app/models/language.rb b/app/models/language.rb index fdcb7bacb..8ccb00a5d 100644 --- a/app/models/language.rb +++ b/app/models/language.rb @@ -5,7 +5,7 @@ class Language < ActiveRecord::Base 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 diff --git a/app/models/message.rb b/app/models/message.rb index b05d005b0..8ca1dc5bc 100644 --- a/app/models/message.rb +++ b/app/models/message.rb @@ -6,7 +6,7 @@ class Message < ActiveRecord::Base 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) @@ -16,7 +16,7 @@ class Message < ActiveRecord::Base 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 diff --git a/app/models/node.rb b/app/models/node.rb index 755dc82ce..7d2219d75 100644 --- a/app/models/node.rb +++ b/app/models/node.rb @@ -18,15 +18,15 @@ class Node < ActiveRecord::Base 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 @@ -41,42 +41,40 @@ class Node < ActiveRecord::Base 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 @@ -85,16 +83,16 @@ class Node < ActiveRecord::Base 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 ## @@ -106,8 +104,8 @@ class Node < ActiveRecord::Base # 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 @@ -117,10 +115,10 @@ class Node < ActiveRecord::Base 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 = {} @@ -143,7 +141,7 @@ class Node < ActiveRecord::Base 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 @@ -152,7 +150,7 @@ class Node < ActiveRecord::Base self.visible = true # update changeset bbox with *new* position - changeset.update_bbox!(bbox); + changeset.update_bbox!(bbox) save_with_history! end @@ -171,44 +169,42 @@ class Node < ActiveRecord::Base 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 @@ -223,7 +219,7 @@ class Node < ActiveRecord::Base ## # 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 @@ -238,10 +234,10 @@ class Node < ActiveRecord::Base # 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! @@ -259,5 +255,4 @@ class Node < ActiveRecord::Base changeset.save! end end - end diff --git a/app/models/note.rb b/app/models/note.rb index 27357e58a..f70e4f3bf 100644 --- a/app/models/note.rb +++ b/app/models/note.rb @@ -8,7 +8,7 @@ class Note < ActiveRecord::Base 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'") } @@ -25,14 +25,14 @@ class Note < ActiveRecord::Base 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 @@ -42,20 +42,20 @@ class Note < ActiveRecord::Base # 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 diff --git a/app/models/note_comment.rb b/app/models/note_comment.rb index dd91a95b4..192064864 100644 --- a/app/models/note_comment.rb +++ b/app/models/note_comment.rb @@ -8,7 +8,7 @@ class NoteComment < ActiveRecord::Base 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 diff --git a/app/models/notifier.rb b/app/models/notifier.rb index b1a94a77d..be7b8d145 100644 --- a/app/models/notifier.rb +++ b/app/models/notifier.rb @@ -166,7 +166,7 @@ class Notifier < ActionMailer::Base end end -private + private def with_recipient_locale(recipient) old_locale = I18n.locale @@ -181,8 +181,8 @@ private 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 diff --git a/app/models/oauth2_token.rb b/app/models/oauth2_token.rb index 9c28d886e..6dd421ab1 100644 --- a/app/models/oauth2_token.rb +++ b/app/models/oauth2_token.rb @@ -1,8 +1,8 @@ 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 diff --git a/app/models/oauth2_verifier.rb b/app/models/oauth2_verifier.rb index 94856d0d8..4dcce5588 100644 --- a/app/models/oauth2_verifier.rb +++ b/app/models/oauth2_verifier.rb @@ -2,9 +2,9 @@ class Oauth2Verifier < OauthToken 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 @@ -27,7 +27,7 @@ class Oauth2Verifier < OauthToken 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 diff --git a/app/models/oauth_token.rb b/app/models/oauth_token.rb index bd3d57496..f2dd31df0 100644 --- a/app/models/oauth_token.rb +++ b/app/models/oauth_token.rb @@ -18,17 +18,17 @@ class OauthToken < ActiveRecord::Base 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 diff --git a/app/models/old_node.rb b/app/models/old_node.rb index b3ed96cd0..00f46dba6 100644 --- a/app/models/old_node.rb +++ b/app/models/old_node.rb @@ -11,7 +11,7 @@ class OldNode < ActiveRecord::Base 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 @@ -36,69 +36,67 @@ class OldNode < ActiveRecord::Base 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 diff --git a/app/models/old_relation.rb b/app/models/old_relation.rb index 86c4784c4..8e0727743 100644 --- a/app/models/old_relation.rb +++ b/app/models/old_relation.rb @@ -27,24 +27,24 @@ class OldRelation < ActiveRecord::Base 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] @@ -53,36 +53,32 @@ class OldRelation < ActiveRecord::Base 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 @@ -90,29 +86,29 @@ class OldRelation < ActiveRecord::Base 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 diff --git a/app/models/old_way.rb b/app/models/old_way.rb index 167ed303a..c088ee129 100644 --- a/app/models/old_way.rb +++ b/app/models/old_way.rb @@ -27,25 +27,25 @@ class OldWay < ActiveRecord::Base 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 @@ -53,36 +53,32 @@ class OldWay < ActiveRecord::Base 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 @@ -93,21 +89,21 @@ class OldWay < ActiveRecord::Base # (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 @@ -116,22 +112,22 @@ class OldWay < ActiveRecord::Base # 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 diff --git a/app/models/relation.rb b/app/models/relation.rb index 464766802..c59ae47d1 100644 --- a/app/models/relation.rb +++ b/app/models/relation.rb @@ -18,9 +18,9 @@ class Relation < ActiveRecord::Base 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 @@ -31,36 +31,34 @@ class Relation < ActiveRecord::Base 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 @@ -69,12 +67,12 @@ class Relation < ActiveRecord::Base 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 @@ -82,47 +80,47 @@ class Relation < ActiveRecord::Base # 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 @@ -134,29 +132,25 @@ class Relation < ActiveRecord::Base 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 ||= [] @@ -164,11 +158,11 @@ class Relation < ActiveRecord::Base 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 @@ -184,8 +178,8 @@ class Relation < ActiveRecord::Base 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 @@ -195,8 +189,8 @@ class Relation < ActiveRecord::Base 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 = {} @@ -210,8 +204,8 @@ class Relation < ActiveRecord::Base 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 @@ -225,7 +219,7 @@ class Relation < ActiveRecord::Base 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 @@ -240,14 +234,15 @@ class Relation < ActiveRecord::Base # 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 @@ -256,19 +251,19 @@ class Relation < ActiveRecord::Base 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 ## @@ -276,11 +271,11 @@ class Relation < ActiveRecord::Base # 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] @@ -302,13 +297,13 @@ class Relation < ActiveRecord::Base 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 @@ -322,11 +317,11 @@ class Relation < ActiveRecord::Base 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! @@ -335,9 +330,9 @@ class Relation < ActiveRecord::Base # 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? @@ -353,10 +348,10 @@ class Relation < ActiveRecord::Base # 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] @@ -379,10 +374,10 @@ class Relation < ActiveRecord::Base # 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. @@ -390,7 +385,7 @@ class Relation < ActiveRecord::Base 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 @@ -403,5 +398,4 @@ class Relation < ActiveRecord::Base changeset.save! end end - end diff --git a/app/models/request_token.rb b/app/models/request_token.rb index 1ac502bc7..0d55375ff 100644 --- a/app/models/request_token.rb +++ b/app/models/request_token.rb @@ -1,13 +1,12 @@ 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! @@ -17,9 +16,9 @@ class RequestToken < OauthToken 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! @@ -40,7 +39,6 @@ class RequestToken < OauthToken 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 diff --git a/app/models/trace.rb b/app/models/trace.rb index bf3e4ef93..d8cc6048a 100644 --- a/app/models/trace.rb +++ b/app/models/trace.rb @@ -7,16 +7,16 @@ class Trace < ActiveRecord::Base 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 @@ -26,19 +26,19 @@ class Trace < ActiveRecord::Base 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 @@ -58,13 +58,13 @@ class Trace < ActiveRecord::Base 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 @@ -105,9 +105,9 @@ class Trace < ActiveRecord::Base 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" @@ -115,7 +115,7 @@ class Trace < ActiveRecord::Base mimetype = "application/gpx+xml" end - return mimetype + mimetype end def extension_name @@ -125,9 +125,9 @@ class Trace < ActiveRecord::Base 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" @@ -141,67 +141,65 @@ class Trace < ActiveRecord::Base 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 @@ -210,14 +208,14 @@ class Trace < ActiveRecord::Base 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 @@ -228,12 +226,12 @@ class Trace < ActiveRecord::Base 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}") @@ -252,13 +250,13 @@ class Trace < ActiveRecord::Base 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 @@ -267,8 +265,8 @@ class Trace < ActiveRecord::Base # 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| @@ -310,6 +308,6 @@ class Trace < ActiveRecord::Base logger.info "done trace #{id}" - return gpx + gpx end end diff --git a/app/models/tracepoint.rb b/app/models/tracepoint.rb index c4ad8e123..879702822 100644 --- a/app/models/tracepoint.rb +++ b/app/models/tracepoint.rb @@ -13,9 +13,9 @@ class Tracepoint < ActiveRecord::Base 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 diff --git a/app/models/user.rb b/app/models/user.rb index 7ace4bca4..12afbb24b 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -7,7 +7,7 @@ class User < ActiveRecord::Base 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" @@ -26,27 +26,27 @@ class User < ActiveRecord::Base 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 @@ -59,7 +59,7 @@ class User < ActiveRecord::Base 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? @@ -70,7 +70,7 @@ class User < ActiveRecord::Base 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 @@ -83,36 +83,36 @@ class User < ActiveRecord::Base 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 @@ -132,39 +132,39 @@ class User < ActiveRecord::Base 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 ## @@ -189,13 +189,13 @@ class User < ActiveRecord::Base # 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 @@ -204,31 +204,31 @@ class User < ActiveRecord::Base 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 @@ -236,10 +236,10 @@ class User < ActiveRecord::Base ## # 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) diff --git a/app/models/user_block.rb b/app/models/user_block.rb index d8fa95cb2..6ebdeee0b 100644 --- a/app/models/user_block.rb +++ b/app/models/user_block.rb @@ -10,7 +10,7 @@ class UserBlock < ActiveRecord::Base ## # 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 ## @@ -23,7 +23,7 @@ class UserBlock < ActiveRecord::Base # 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 ## @@ -31,20 +31,20 @@ class UserBlock < ActiveRecord::Base # 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 diff --git a/app/models/user_preference.rb b/app/models/user_preference.rb index 7faec977e..969a368e3 100644 --- a/app/models/user_preference.rb +++ b/app/models/user_preference.rb @@ -9,10 +9,9 @@ class UserPreference < ActiveRecord::Base # Turn this Node in to an XML Node without the 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 diff --git a/app/models/user_role.rb b/app/models/user_role.rb index fb783281e..c4d703530 100644 --- a/app/models/user_role.rb +++ b/app/models/user_role.rb @@ -1,7 +1,7 @@ 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 diff --git a/app/models/user_token.rb b/app/models/user_token.rb index 735fd8485..faa540e67 100644 --- a/app/models/user_token.rb +++ b/app/models/user_token.rb @@ -7,10 +7,10 @@ class UserToken < ActiveRecord::Base 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 diff --git a/app/models/way.rb b/app/models/way.rb index c105fa089..96422a8f6 100644 --- a/app/models/way.rb +++ b/app/models/way.rb @@ -20,9 +20,9 @@ class Way < ActiveRecord::Base 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 @@ -31,34 +31,32 @@ class Way < ActiveRecord::Base 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 @@ -67,12 +65,12 @@ class Way < ActiveRecord::Base 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 @@ -80,7 +78,7 @@ class Way < ActiveRecord::Base 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 @@ -88,27 +86,27 @@ class Way < ActiveRecord::Base # 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] @@ -116,52 +114,48 @@ class Way < ActiveRecord::Base 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 @@ -170,8 +164,8 @@ class Way < ActiveRecord::Base # 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 @@ -179,8 +173,8 @@ class Way < ActiveRecord::Base 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 @@ -195,7 +189,7 @@ class Way < ActiveRecord::Base 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 @@ -203,30 +197,30 @@ class Way < ActiveRecord::Base 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 @@ -236,7 +230,7 @@ class Way < ActiveRecord::Base 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 @@ -250,7 +244,7 @@ class Way < ActiveRecord::Base # Temporary method to match interface to nodes def tags_as_hash - return self.tags + tags end ## @@ -258,10 +252,10 @@ class Way < ActiveRecord::Base # 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 @@ -278,7 +272,7 @@ class Way < ActiveRecord::Base # 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 @@ -287,21 +281,21 @@ class Way < ActiveRecord::Base 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 @@ -313,7 +307,7 @@ class Way < ActiveRecord::Base # 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. diff --git a/config/application.rb b/config/application.rb index 6a96b9dd6..652721e21 100644 --- a/config/application.rb +++ b/config/application.rb @@ -3,13 +3,13 @@ require File.expand_path('../boot', __FILE__) 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 diff --git a/config/initializers/abstract_adapter.rb b/config/initializers/abstract_adapter.rb index 7288488a6..5613e0d00 100644 --- a/config/initializers/abstract_adapter.rb +++ b/config/initializers/abstract_adapter.rb @@ -2,7 +2,8 @@ if defined?(ActiveRecord::ConnectionAdaptors::AbstractAdapter) module ActiveRecord module ConnectionAdapters class AbstractAdapter - protected + protected + alias_method :old_log, :log def log(sql, name) diff --git a/config/initializers/field_error.rb b/config/initializers/field_error.rb index 41f2c2d52..6ddacda96 100644 --- a/config/initializers/field_error.rb +++ b/config/initializers/field_error.rb @@ -1,8 +1,8 @@ -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 diff --git a/config/initializers/i18n.rb b/config/initializers/i18n.rb index 2562b67a0..1ee7716e6 100644 --- a/config/initializers/i18n.rb +++ b/config/initializers/i18n.rb @@ -4,7 +4,7 @@ module I18n 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 @@ -15,7 +15,7 @@ module I18n 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) diff --git a/config/initializers/libxml.rb b/config/initializers/libxml.rb index 07f79660f..e0e659f12 100644 --- a/config/initializers/libxml.rb +++ b/config/initializers/libxml.rb @@ -1,5 +1,5 @@ # 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 diff --git a/config/initializers/memory_limits.rb b/config/initializers/memory_limits.rb index 1b79df7f4..199bda5c6 100644 --- a/config/initializers/memory_limits.rb +++ b/config/initializers/memory_limits.rb @@ -1,11 +1,11 @@ # 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) @@ -24,7 +24,9 @@ if defined?(SOFT_MEMORY_LIMIT) and defined?(PhusionPassenger) # 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 @@ -33,7 +35,7 @@ if defined?(SOFT_MEMORY_LIMIT) and defined?(PhusionPassenger) end # Return resident size in megabytes - return fields[1].to_i / 256 + fields[1].to_i / 256 end end diff --git a/config/initializers/paperclip.rb b/config/initializers/paperclip.rb index 592c9e187..75f6d2371 100644 --- a/config/initializers/paperclip.rb +++ b/config/initializers/paperclip.rb @@ -14,7 +14,7 @@ module Paperclip 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 diff --git a/config/initializers/piwik.rb b/config/initializers/piwik.rb index 1f054f7d1..2de98ce06 100644 --- a/config/initializers/piwik.rb +++ b/config/initializers/piwik.rb @@ -1,5 +1,5 @@ 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 diff --git a/config/initializers/potlatch.rb b/config/initializers/potlatch.rb index b98d60e1a..223083b7e 100644 --- a/config/initializers/potlatch.rb +++ b/config/initializers/potlatch.rb @@ -1,5 +1,5 @@ # 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 diff --git a/config/initializers/r2.rb b/config/initializers/r2.rb index 254ce01fc..114041202 100644 --- a/config/initializers/r2.rb +++ b/config/initializers/r2.rb @@ -13,7 +13,7 @@ class R2Template < Tilt::Template @output = R2.r2(data) end - def evaluate(scope, locals, &block) + def evaluate(_scope, _locals, &_block) @output end end diff --git a/config/initializers/router.rb b/config/initializers/router.rb index a1e6bbf38..2987e424a 100644 --- a/config/initializers/router.rb +++ b/config/initializers/router.rb @@ -6,7 +6,7 @@ module ActionDispatch 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 diff --git a/config/initializers/sanitize.rb b/config/initializers/sanitize.rb index eb3039a13..7ae94feef 100644 --- a/config/initializers/sanitize.rb +++ b/config/initializers/sanitize.rb @@ -1,5 +1,5 @@ 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) diff --git a/config/initializers/streaming.rb b/config/initializers/streaming.rb index db61e6b24..3db2a55f9 100644 --- a/config/initializers/streaming.rb +++ b/config/initializers/streaming.rb @@ -4,7 +4,7 @@ module ActionController 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] diff --git a/config/initializers/tempfile.rb b/config/initializers/tempfile.rb index 11416b086..43b5a5443 100644 --- a/config/initializers/tempfile.rb +++ b/config/initializers/tempfile.rb @@ -2,6 +2,6 @@ # does a half assed job of making TempFile act as a File class Tempfile def file - return @tmpfile + @tmpfile end end diff --git a/config/preinitializer.rb b/config/preinitializer.rb index ec05a6070..818146c21 100644 --- a/config/preinitializer.rb +++ b/config/preinitializer.rb @@ -8,13 +8,13 @@ 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 diff --git a/config/routes.rb b/config/routes.rb index 009930547..dc24e3000 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -86,7 +86,7 @@ OpenStreetMap::Application.routes.draw do # 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" } diff --git a/db/migrate/001_create_osm_db.rb b/db/migrate/001_create_osm_db.rb index b16e9939f..34cf27b50 100644 --- a/db/migrate/001_create_osm_db.rb +++ b/db/migrate/001_create_osm_db.rb @@ -13,7 +13,7 @@ class CreateOsmDb < ActiveRecord::Migration 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| @@ -26,7 +26,7 @@ class CreateOsmDb < ActiveRecord::Migration 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" @@ -82,7 +82,7 @@ class CreateOsmDb < ActiveRecord::Migration 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" @@ -109,7 +109,7 @@ class CreateOsmDb < ActiveRecord::Migration 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 @@ -148,7 +148,7 @@ class CreateOsmDb < ActiveRecord::Migration 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 @@ -193,7 +193,7 @@ class CreateOsmDb < ActiveRecord::Migration 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 @@ -202,7 +202,7 @@ class CreateOsmDb < ActiveRecord::Migration 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 @@ -212,11 +212,10 @@ class CreateOsmDb < ActiveRecord::Migration 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 diff --git a/db/migrate/002_cleanup_osm_db.rb b/db/migrate/002_cleanup_osm_db.rb index 346c7cf4a..2f6af1c17 100644 --- a/db/migrate/002_cleanup_osm_db.rb +++ b/db/migrate/002_cleanup_osm_db.rb @@ -21,7 +21,7 @@ class CleanupOsmDb < ActiveRecord::Migration 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 @@ -40,7 +40,7 @@ class CleanupOsmDb < ActiveRecord::Migration 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 @@ -204,7 +204,7 @@ class CleanupOsmDb < ActiveRecord::Migration 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 diff --git a/db/migrate/004_user_enhancements.rb b/db/migrate/004_user_enhancements.rb index 8b352be3e..92f996200 100644 --- a/db/migrate/004_user_enhancements.rb +++ b/db/migrate/004_user_enhancements.rb @@ -12,7 +12,7 @@ class UserEnhancements < ActiveRecord::Migration 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 @@ -35,7 +35,7 @@ class UserEnhancements < ActiveRecord::Migration 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 diff --git a/db/migrate/005_tile_tracepoints.rb b/db/migrate/005_tile_tracepoints.rb index fea6d4137..f260f234a 100644 --- a/db/migrate/005_tile_tracepoints.rb +++ b/db/migrate/005_tile_tracepoints.rb @@ -20,7 +20,7 @@ class TileTracepoints < ActiveRecord::Migration 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 diff --git a/db/migrate/006_tile_nodes.rb b/db/migrate/006_tile_nodes.rb index f8a18671e..016ba040b 100644 --- a/db/migrate/006_tile_nodes.rb +++ b/db/migrate/006_tile_nodes.rb @@ -19,9 +19,7 @@ class TileNodes < ActiveRecord::Migration FROM #{from_table} END_SQL - model.all.each do |n| - n.save! - end + model.all.each(&:save!) end end @@ -59,8 +57,8 @@ class TileNodes < ActiveRecord::Migration 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| @@ -98,7 +96,7 @@ class TileNodes < ActiveRecord::Migration 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" @@ -118,7 +116,7 @@ class TileNodes < ActiveRecord::Migration 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" diff --git a/db/migrate/007_add_relations.rb b/db/migrate/007_add_relations.rb index 4a0f74c52..064fd05c9 100644 --- a/db/migrate/007_add_relations.rb +++ b/db/migrate/007_add_relations.rb @@ -3,7 +3,7 @@ require 'migrate' 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: @@ -16,8 +16,8 @@ class AddRelations < ActiveRecord::Migration 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| @@ -44,8 +44,8 @@ class AddRelations < ActiveRecord::Migration 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 @@ -54,7 +54,7 @@ class AddRelations < ActiveRecord::Migration 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 @@ -64,7 +64,7 @@ class AddRelations < ActiveRecord::Migration 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 diff --git a/db/migrate/008_remove_segments.rb b/db/migrate/008_remove_segments.rb index a72859ae8..2820f82f8 100644 --- a/db/migrate/008_remove_segments.rb +++ b/db/migrate/008_remove_segments.rb @@ -5,25 +5,24 @@ class RemoveSegments < ActiveRecord::Migration 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 @@ -82,6 +81,6 @@ class RemoveSegments < ActiveRecord::Migration end def self.down - raise ActiveRecord::IrreversibleMigration + fail ActiveRecord::IrreversibleMigration end end diff --git a/db/migrate/010_diary_comments.rb b/db/migrate/010_diary_comments.rb index ad2edffa4..2473bcb3b 100644 --- a/db/migrate/010_diary_comments.rb +++ b/db/migrate/010_diary_comments.rb @@ -11,8 +11,7 @@ class DiaryComments < ActiveRecord::Migration 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 diff --git a/db/migrate/013_add_email_valid.rb b/db/migrate/013_add_email_valid.rb index a01809701..8552c2733 100644 --- a/db/migrate/013_add_email_valid.rb +++ b/db/migrate/013_add_email_valid.rb @@ -1,7 +1,7 @@ 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 diff --git a/db/migrate/020_populate_node_tags_and_remove.rb b/db/migrate/020_populate_node_tags_and_remove.rb index b5932bbe8..8315cb143 100644 --- a/db/migrate/020_populate_node_tags_and_remove.rb +++ b/db/migrate/020_populate_node_tags_and_remove.rb @@ -5,21 +5,21 @@ class PopulateNodeTagsAndRemove < ActiveRecord::Migration 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 @@ -46,7 +46,7 @@ class PopulateNodeTagsAndRemove < ActiveRecord::Migration 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 @@ -55,8 +55,8 @@ class PopulateNodeTagsAndRemove < ActiveRecord::Migration 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 diff --git a/db/migrate/021_move_to_innodb.rb b/db/migrate/021_move_to_innodb.rb index aeb84028e..72a4607d9 100644 --- a/db/migrate/021_move_to_innodb.rb +++ b/db/migrate/021_move_to_innodb.rb @@ -1,43 +1,41 @@ 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 diff --git a/db/migrate/022_key_constraints.rb b/db/migrate/022_key_constraints.rb index e854ba78e..79706bc4a 100644 --- a/db/migrate/022_key_constraints.rb +++ b/db/migrate/022_key_constraints.rb @@ -47,6 +47,6 @@ class KeyConstraints < ActiveRecord::Migration end def self.down - raise ActiveRecord::IrreversibleMigration + fail ActiveRecord::IrreversibleMigration end end diff --git a/db/migrate/023_add_changesets.rb b/db/migrate/023_add_changesets.rb index aac921ad8..b54494759 100644 --- a/db/migrate/023_add_changesets.rb +++ b/db/migrate/023_add_changesets.rb @@ -1,8 +1,7 @@ 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| @@ -32,17 +31,17 @@ class AddChangesets < ActiveRecord::Migration 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 diff --git a/db/migrate/028_add_more_changeset_indexes.rb b/db/migrate/028_add_more_changeset_indexes.rb index ea2dc0290..b7b1be955 100644 --- a/db/migrate/028_add_more_changeset_indexes.rb +++ b/db/migrate/028_add_more_changeset_indexes.rb @@ -4,7 +4,7 @@ class AddMoreChangesetIndexes < ActiveRecord::Migration 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 diff --git a/db/migrate/030_add_foreign_keys.rb b/db/migrate/030_add_foreign_keys.rb index 1b99f664d..2a68d422f 100644 --- a/db/migrate/030_add_foreign_keys.rb +++ b/db/migrate/030_add_foreign_keys.rb @@ -9,6 +9,6 @@ class AddForeignKeys < ActiveRecord::Migration end def self.down - raise ActiveRecord::IrreversibleMigration + fail ActiveRecord::IrreversibleMigration end end diff --git a/db/migrate/034_create_languages.rb b/db/migrate/034_create_languages.rb index a9d683151..8f5244f22 100644 --- a/db/migrate/034_create_languages.rb +++ b/db/migrate/034_create_languages.rb @@ -13,6 +13,6 @@ class CreateLanguages < ActiveRecord::Migration 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 diff --git a/db/migrate/038_add_message_sender_index.rb b/db/migrate/038_add_message_sender_index.rb index 0fb84bf94..723ef7814 100644 --- a/db/migrate/038_add_message_sender_index.rb +++ b/db/migrate/038_add_message_sender_index.rb @@ -1,9 +1,9 @@ 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 diff --git a/db/migrate/039_add_more_controls_to_gpx_files.rb b/db/migrate/039_add_more_controls_to_gpx_files.rb index aa2050e78..5382324b3 100644 --- a/db/migrate/039_add_more_controls_to_gpx_files.rb +++ b/db/migrate/039_add_more_controls_to_gpx_files.rb @@ -2,7 +2,7 @@ require 'migrate' 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" diff --git a/db/migrate/040_create_oauth_tables.rb b/db/migrate/040_create_oauth_tables.rb index d1095f834..4b3725365 100644 --- a/db/migrate/040_create_oauth_tables.rb +++ b/db/migrate/040_create_oauth_tables.rb @@ -32,7 +32,6 @@ class CreateOauthTables < ActiveRecord::Migration t.timestamps end add_index :oauth_nonces, [:nonce, :timestamp], :unique => true - end def self.down @@ -40,5 +39,4 @@ class CreateOauthTables < ActiveRecord::Migration drop_table :oauth_tokens drop_table :oauth_nonces end - end diff --git a/db/migrate/041_add_fine_o_auth_permissions.rb b/db/migrate/041_add_fine_o_auth_permissions.rb index ad4c7a8a4..dcb77a2b6 100644 --- a/db/migrate/041_add_fine_o_auth_permissions.rb +++ b/db/migrate/041_add_fine_o_auth_permissions.rb @@ -1,6 +1,6 @@ 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| diff --git a/db/migrate/044_create_user_roles.rb b/db/migrate/044_create_user_roles.rb index 26b2adf6f..bd7ac41af 100644 --- a/db/migrate/044_create_user_roles.rb +++ b/db/migrate/044_create_user_roles.rb @@ -2,7 +2,7 @@ require 'migrate' 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 diff --git a/db/migrate/051_add_status_to_user.rb b/db/migrate/051_add_status_to_user.rb index e79246f48..dc8d58138 100644 --- a/db/migrate/051_add_status_to_user.rb +++ b/db/migrate/051_add_status_to_user.rb @@ -2,7 +2,7 @@ require 'migrate' 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" diff --git a/db/migrate/053_add_map_bug_tables.rb b/db/migrate/053_add_map_bug_tables.rb index c5a4a4801..54c23fd1d 100644 --- a/db/migrate/053_add_map_bug_tables.rb +++ b/db/migrate/053_add_map_bug_tables.rb @@ -2,7 +2,7 @@ require 'migrate' 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 diff --git a/db/migrate/057_add_map_bug_comment_event.rb b/db/migrate/057_add_map_bug_comment_event.rb index f28aee7d8..98e64599e 100644 --- a/db/migrate/057_add_map_bug_comment_event.rb +++ b/db/migrate/057_add_map_bug_comment_event.rb @@ -2,7 +2,7 @@ require 'migrate' 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 diff --git a/db/migrate/20120208122334_merge_acl_address_and_mask.rb b/db/migrate/20120208122334_merge_acl_address_and_mask.rb index 791bf659a..9153da1e5 100644 --- a/db/migrate/20120208122334_merge_acl_address_and_mask.rb +++ b/db/migrate/20120208122334_merge_acl_address_and_mask.rb @@ -19,7 +19,7 @@ class MergeAclAddressAndMask < ActiveRecord::Migration while netmask != "0.0.0.0" netmask = netmask << 1 - prefix = prefix + 1 + prefix += 1 end acl.address = "#{address.mask(prefix)}/#{prefix}" diff --git a/db/migrate/20120214210114_add_text_format.rb b/db/migrate/20120214210114_add_text_format.rb index 5b4455f58..0b0ca5004 100644 --- a/db/migrate/20120214210114_add_text_format.rb +++ b/db/migrate/20120214210114_add_text_format.rb @@ -2,7 +2,7 @@ require 'migrate' 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" diff --git a/lib/bounding_box.rb b/lib/bounding_box.rb index 38b994d26..282a6a840 100644 --- a/lib/bounding_box.rb +++ b/lib/bounding_box.rb @@ -1,13 +1,15 @@ 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? @@ -24,21 +26,21 @@ public 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) @@ -64,15 +66,15 @@ public 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 @@ -81,7 +83,7 @@ public 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 @@ -98,7 +100,7 @@ public end def complete? - not to_a.include?(nil) + !to_a.include?(nil) end def centre_lon @@ -118,7 +120,7 @@ public 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) @@ -127,7 +129,7 @@ public 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, @@ -163,9 +165,10 @@ public 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 diff --git a/lib/classic_pagination/pagination.rb b/lib/classic_pagination/pagination.rb index 5db1be02b..7a7177984 100644 --- a/lib/classic_pagination/pagination.rb +++ b/lib/classic_pagination/pagination.rb @@ -59,7 +59,7 @@ module ActionController 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 = { @@ -87,14 +87,14 @@ module ActionController 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) @@ -128,7 +128,7 @@ module ActionController # # :group:: :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 @@ -143,11 +143,11 @@ module ActionController # of: # :actions:: 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 @@ -162,10 +162,10 @@ module ActionController 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 @@ -207,14 +207,14 @@ module ActionController :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 @@ -228,8 +228,8 @@ module ActionController # 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 @@ -246,7 +246,7 @@ module ActionController # 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 @@ -257,31 +257,31 @@ module ActionController 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 @@ -291,9 +291,9 @@ module ActionController 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 @@ -310,14 +310,14 @@ module ActionController @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 @@ -326,7 +326,7 @@ module ActionController # 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 @@ -369,7 +369,7 @@ module ActionController # 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 @@ -387,7 +387,7 @@ module ActionController 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 @@ -408,11 +408,10 @@ module ActionController # 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 diff --git a/lib/classic_pagination/pagination_helper.rb b/lib/classic_pagination/pagination_helper.rb index 01260f9e0..cb7ef9dfe 100644 --- a/lib/classic_pagination/pagination_helper.rb +++ b/lib/classic_pagination/pagination_helper.rb @@ -56,7 +56,7 @@ module ActionView # pagination_links(@person_pages, :params => { :viewer => "flash" }) # # => 1 2 3 ... # # 10 - 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 @@ -105,7 +105,7 @@ module ActionView 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 << ' ' @@ -120,7 +120,7 @@ module ActionView 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 @@ -129,7 +129,6 @@ module ActionView html end - end # PaginationHelper end # Helpers end # ActionView diff --git a/lib/consistency_validations.rb b/lib/consistency_validations.rb index bcb7a26b7..a385ae1be 100644 --- a/lib/consistency_validations.rb +++ b/lib/consistency_validations.rb @@ -6,27 +6,27 @@ module ConsistencyValidations # 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 @@ -37,11 +37,11 @@ module ConsistencyValidations # 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 diff --git a/lib/country.rb b/lib/country.rb index ea52efd77..41e36ccec 100644 --- a/lib/country.rb +++ b/lib/country.rb @@ -13,14 +13,14 @@ class Country 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| diff --git a/lib/daemons/gpx_import.rb b/lib/daemons/gpx_import.rb index 1a87bf6b8..c257c1bfc 100755 --- a/lib/daemons/gpx_import.rb +++ b/lib/daemons/gpx_import.rb @@ -1,7 +1,7 @@ #!/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" @@ -9,7 +9,7 @@ terminated = false 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| @@ -28,7 +28,7 @@ while(true) do 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 @@ -47,7 +47,7 @@ while(true) do 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") diff --git a/lib/daemons/gpx_import_ctl b/lib/daemons/gpx_import_ctl index 32c5f34ab..fd06863fa 100755 --- a/lib/daemons/gpx_import_ctl +++ b/lib/daemons/gpx_import_ctl @@ -6,15 +6,15 @@ require 'erb' 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 diff --git a/lib/diff_reader.rb b/lib/diff_reader.rb index 40b43c5cd..89e34550f 100644 --- a/lib/diff_reader.rb +++ b/lib/diff_reader.rb @@ -32,11 +32,9 @@ class DiffReader 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 ## @@ -52,7 +50,7 @@ class DiffReader # 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 @@ -85,9 +83,9 @@ class DiffReader # 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, @@ -111,9 +109,9 @@ class DiffReader # 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 @@ -125,20 +123,19 @@ class DiffReader # 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 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. @@ -149,12 +146,12 @@ class DiffReader # 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. @@ -213,7 +210,7 @@ class DiffReader # 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 @@ -254,12 +251,11 @@ class DiffReader 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 diff --git a/lib/editors.rb b/lib/editors.rb index 84f2a9468..1c5427b94 100644 --- a/lib/editors.rb +++ b/lib/editors.rb @@ -1,4 +1,4 @@ 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 diff --git a/lib/geo_record.rb b/lib/geo_record.rb index 7c65e3af2..61185a314 100644 --- a/lib/geo_record.rb +++ b/lib/geo_record.rb @@ -12,9 +12,9 @@ module GeoRecord # 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 @@ -31,17 +31,17 @@ module GeoRecord # 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 diff --git a/lib/gpx.rb b/lib/gpx.rb index 2041ce7c0..0a7a88c10 100644 --- a/lib/gpx.rb +++ b/lib/gpx.rb @@ -28,13 +28,13 @@ module GPX 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 @@ -100,7 +100,7 @@ module GPX 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 @@ -117,7 +117,7 @@ module GPX il.delay = 50 il.format = 'GIF' - return il.to_blob + il.to_blob end def icon(min_lat, min_lon, max_lat, max_lon) @@ -152,17 +152,17 @@ module GPX 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 diff --git a/lib/id.rb b/lib/id.rb index 15b7f8367..732194422 100644 --- a/lib/id.rb +++ b/lib/id.rb @@ -1,3 +1,3 @@ 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 diff --git a/lib/migrate.rb b/lib/migrate.rb index 681eba5b6..9008b0a9f 100644 --- a/lib/migrate.rb +++ b/lib/migrate.rb @@ -20,7 +20,7 @@ module ActiveRecord 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 diff --git a/lib/nominatim.rb b/lib/nominatim.rb index 33a0c3e26..10eac78e5 100644 --- a/lib/nominatim.rb +++ b/lib/nominatim.rb @@ -2,8 +2,8 @@ module Nominatim 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}" @@ -16,7 +16,7 @@ module Nominatim 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)}" diff --git a/lib/not_redactable.rb b/lib/not_redactable.rb index d7c952463..75ff33176 100644 --- a/lib/not_redactable.rb +++ b/lib/not_redactable.rb @@ -5,7 +5,7 @@ module NotRedactable false end - def redact!(r) - raise OSM::APICannotRedactError.new + def redact!(_r) + fail OSM::APICannotRedactError.new end end diff --git a/lib/osm.rb b/lib/osm.rb index c59ab7e26..1d0896417 100644 --- a/lib/osm.rb +++ b/lib/osm.rb @@ -1,6 +1,5 @@ # The OSM module provides support functions for OSM. module OSM - require 'time' require 'rexml/parsers/sax2parser' require 'rexml/text' @@ -203,7 +202,7 @@ module OSM # 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 @@ -397,7 +396,7 @@ module OSM 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) @@ -418,7 +417,7 @@ module OSM @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) @@ -428,14 +427,14 @@ module OSM 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 @@ -452,15 +451,15 @@ module OSM 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 @@ -470,7 +469,7 @@ module OSM 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 @@ -490,7 +489,7 @@ module OSM root['attribution'] = ATTRIBUTION_URL root['license'] = LICENSE_URL doc.root = root - return doc + doc end end @@ -498,7 +497,7 @@ module OSM 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| @@ -518,11 +517,11 @@ module OSM 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 @@ -541,7 +540,7 @@ module OSM 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 @@ -549,13 +548,13 @@ module OSM 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 diff --git a/lib/output_compression/output_compression.rb b/lib/output_compression/output_compression.rb index e3db8fb78..2c5dd6ca5 100644 --- a/lib/output_compression/output_compression.rb +++ b/lib/output_compression/output_compression.rb @@ -49,7 +49,7 @@ module CompressionSystem 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)/ diff --git a/lib/password_hash.rb b/lib/password_hash.rb index 5adfc7a34..fe618ba7a 100644 --- a/lib/password_hash.rb +++ b/lib/password_hash.rb @@ -12,7 +12,7 @@ module PasswordHash 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) @@ -26,7 +26,7 @@ module PasswordHash candidate = Digest::MD5.hexdigest(salt + candidate) end - return hash == candidate + hash == candidate end def self.upgrade?(hash, salt) @@ -42,14 +42,14 @@ module PasswordHash 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 diff --git a/lib/potlatch.rb b/lib/potlatch.rb index bd2c905fe..29cc93430 100644 --- a/lib/potlatch.rb +++ b/lib/potlatch.rb @@ -2,50 +2,48 @@ require 'stringio' # 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 @@ -54,62 +52,62 @@ module Potlatch # 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 @@ -121,13 +119,12 @@ module Potlatch 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) @@ -145,12 +142,12 @@ module Potlatch @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 @@ -169,7 +166,6 @@ module Potlatch # The Potlatch class is a helper for Potlatch class Potlatch - # ----- getpresets # in: none # does: reads tag preset menus, colours, and autocomplete config files @@ -180,85 +176,84 @@ module Potlatch 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 diff --git a/lib/quad_tile.rb b/lib/quad_tile.rb index 258fb9fd5..8aee1b74a 100644 --- a/lib/quad_tile.rb +++ b/lib/quad_tile.rb @@ -6,7 +6,7 @@ module QuadTile 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) @@ -22,7 +22,7 @@ module QuadTile end end - return tiles + tiles end def self.tile_for_xy(x, y) @@ -30,14 +30,14 @@ module QuadTile 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) @@ -61,10 +61,10 @@ module QuadTile 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 @@ -74,7 +74,7 @@ module QuadTile 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 diff --git a/lib/quova.rb b/lib/quova.rb index 70e5b4601..9a4fb3bf8 100644 --- a/lib/quova.rb +++ b/lib/quova.rb @@ -6,7 +6,7 @@ require 'soap/wsdlDriver' # Monkey patch WSDL parser to stop it moaning module WSDL class Parser - def warn(msg) + def warn(_msg) end end end @@ -16,7 +16,7 @@ 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 @@ -47,7 +47,7 @@ module Quova # 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 diff --git a/lib/redactable.rb b/lib/redactable.rb index b7f7046be..c46b32737 100644 --- a/lib/redactable.rb +++ b/lib/redactable.rb @@ -8,12 +8,12 @@ module Redactable 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 diff --git a/lib/rich_text.rb b/lib/rich_text.rb index 4cd254720..503ecedbd 100644 --- a/lib/rich_text.rb +++ b/lib/rich_text.rb @@ -1,9 +1,9 @@ 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 @@ -37,10 +37,10 @@ module RichText 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) @@ -61,10 +61,10 @@ module RichText end def to_text - self.to_s + to_s end - private + private def sanitize(text) Sanitize.clean(text, Sanitize::Config::OSM).html_safe @@ -77,22 +77,18 @@ module RichText 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) "#{alt_text}" end @@ -112,7 +108,7 @@ module RichText end def to_text - self.to_s + to_s end end end diff --git a/lib/short_link.rb b/lib/short_link.rb index b09e65f43..0d8f21cad 100644 --- a/lib/short_link.rb +++ b/lib/short_link.rb @@ -5,11 +5,10 @@ # 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 @@ -23,7 +22,7 @@ module ShortLink # 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 @@ -31,8 +30,8 @@ module ShortLink 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 @@ -55,7 +54,7 @@ module ShortLink 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 @@ -64,7 +63,7 @@ module ShortLink # of 3 zoom levels). ((z + 8) % 3).times { str << "-" } - return str + str end private @@ -80,5 +79,4 @@ module ShortLink end c end - end diff --git a/lib/tasks/add_version_to_nodes.rake b/lib/tasks/add_version_to_nodes.rake index 22762ef2e..c0fac49b7 100644 --- a/lib/tasks/add_version_to_nodes.rake +++ b/lib/tasks/add_version_to_nodes.rake @@ -10,12 +10,12 @@ namespace 'db' do 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| @@ -30,8 +30,8 @@ namespace 'db' do 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 diff --git a/lib/utf8.rb b/lib/utf8.rb index c6e1918af..e669d8aae 100644 --- a/lib/utf8.rb +++ b/lib/utf8.rb @@ -2,10 +2,10 @@ module UTF8 ## # 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' diff --git a/lib/validators.rb b/lib/validators.rb index 94dbdb7f3..6338e9ce9 100644 --- a/lib/validators.rb +++ b/lib/validators.rb @@ -1,7 +1,6 @@ module ActiveRecord module Validations module ClassMethods - # error message when invalid UTF-8 is detected @@invalid_utf8_message = " is invalid UTF-8" @@ -14,7 +13,6 @@ module ActiveRecord record.errors.add(attr, @@invalid_utf8_message) unless UTF8.valid? value end end - end end end diff --git a/script/daemons b/script/daemons index 69c7ec948..4eb2fcf6a 100755 --- a/script/daemons +++ b/script/daemons @@ -1,2 +1,2 @@ #!/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}` } diff --git a/script/deliver-message b/script/deliver-message index e713b2cfc..e6a5ebbd7 100755 --- a/script/deliver-message +++ b/script/deliver-message @@ -18,7 +18,7 @@ else 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 diff --git a/script/locale/po2yaml b/script/locale/po2yaml index e181bf3d5..ea78ce2c6 100755 --- a/script/locale/po2yaml +++ b/script/locale/po2yaml @@ -11,7 +11,7 @@ def add_translation(hash, keys, value) 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) @@ -23,7 +23,7 @@ def po2hash(f) trs = {} path = [] msgstr = '' - f.each_line { |line| + f.each_line do |line| line.strip! if line[0..8] == 'msgctxt "' path = line[9..-2].split(':') @@ -31,12 +31,12 @@ def po2hash(f) 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 @@ -45,6 +45,6 @@ pofile = File.open(filename, "r") langcode = File.basename(filename, '.po') -tr = {langcode => po2hash(pofile)} +tr = { langcode => po2hash(pofile) } print tr.to_yaml diff --git a/script/locale/yaml2po b/script/locale/yaml2po index ff5a77b26..22d3e78db 100755 --- a/script/locale/yaml2po +++ b/script/locale/yaml2po @@ -13,29 +13,29 @@ require "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 @@ -46,17 +46,17 @@ end 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 diff --git a/script/statistics b/script/statistics index f20e70031..47a368a81 100755 --- a/script/statistics +++ b/script/statistics @@ -11,11 +11,11 @@ puts "OpenStreetMap Statistics" puts "" puts "" puts "" -puts "

OpenStreetMap stats report run at #{start_time.to_s}

" +puts "

OpenStreetMap stats report run at #{start_time}

" 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 @@ -83,10 +83,10 @@ begin puts "" end rescue Exception => e - puts "

Exception: #{e.to_s}
#{e.backtrace.join('
')}

" + puts "

Exception: #{e}
#{e.backtrace.join('
')}

" end -puts "

Report took #{(Time.new - start_time).to_s} seconds to run

" +puts "

Report took #{(Time.new - start_time)} seconds to run

" puts "" puts "" diff --git a/script/update-spam-blocks b/script/update-spam-blocks index c21b17cff..89bccf1c9 100755 --- a/script/update-spam-blocks +++ b/script/update-spam-blocks @@ -5,24 +5,24 @@ require 'generator' 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 @@ -30,9 +30,9 @@ addresses.each do |address,count| 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] diff --git a/test/controllers/amf_controller_test.rb b/test/controllers/amf_controller_test.rb index ef50cfe74..20002f7cc 100644 --- a/test/controllers/amf_controller_test.rb +++ b/test/controllers/amf_controller_test.rb @@ -46,7 +46,7 @@ class AmfControllerTest < ActionController::TestCase 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 @@ -113,15 +113,15 @@ class AmfControllerTest < ActionController::TestCase 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 @@ -164,16 +164,16 @@ class AmfControllerTest < ActionController::TestCase # 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 @@ -184,7 +184,7 @@ class AmfControllerTest < ActionController::TestCase # # 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 @@ -195,7 +195,7 @@ class AmfControllerTest < ActionController::TestCase # # 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 @@ -203,10 +203,10 @@ class AmfControllerTest < ActionController::TestCase 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 @@ -220,13 +220,13 @@ class AmfControllerTest < ActionController::TestCase # 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 @@ -257,7 +257,7 @@ class AmfControllerTest < ActionController::TestCase 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 @@ -270,7 +270,7 @@ class AmfControllerTest < ActionController::TestCase 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 @@ -385,15 +385,15 @@ class AmfControllerTest < ActionController::TestCase # 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 @@ -424,12 +424,12 @@ class AmfControllerTest < ActionController::TestCase 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 @@ -439,7 +439,7 @@ class AmfControllerTest < ActionController::TestCase 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 @@ -448,8 +448,8 @@ class AmfControllerTest < ActionController::TestCase # 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) @@ -487,8 +487,8 @@ class AmfControllerTest < ActionController::TestCase # 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) @@ -530,12 +530,12 @@ class AmfControllerTest < ActionController::TestCase # 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] @@ -565,8 +565,8 @@ class AmfControllerTest < ActionController::TestCase # 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) @@ -585,26 +585,22 @@ class AmfControllerTest < ActionController::TestCase 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 @@ -623,19 +619,19 @@ class AmfControllerTest < ActionController::TestCase # 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") @@ -653,21 +649,21 @@ class AmfControllerTest < ActionController::TestCase 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 @@ -694,14 +690,14 @@ class AmfControllerTest < ActionController::TestCase # 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 diff --git a/test/controllers/api_controller_test.rb b/test/controllers/api_controller_test.rb index 0ae06be5e..75e77f776 100644 --- a/test/controllers/api_controller_test.rb +++ b/test/controllers/api_controller_test.rb @@ -6,14 +6,14 @@ class ApiControllerTest < ActionController::TestCase 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 @@ -55,10 +55,10 @@ class ApiControllerTest < ActionController::TestCase 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 @@ -95,10 +95,10 @@ class ApiControllerTest < ActionController::TestCase 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 @@ -111,10 +111,10 @@ class ApiControllerTest < ActionController::TestCase 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 @@ -133,10 +133,10 @@ class ApiControllerTest < ActionController::TestCase 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 @@ -155,7 +155,7 @@ class ApiControllerTest < ActionController::TestCase 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" @@ -176,7 +176,7 @@ class ApiControllerTest < ActionController::TestCase 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}" @@ -186,7 +186,7 @@ class ApiControllerTest < ActionController::TestCase 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}" @@ -196,7 +196,7 @@ class ApiControllerTest < ActionController::TestCase 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}" @@ -206,7 +206,7 @@ class ApiControllerTest < ActionController::TestCase 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}" @@ -215,7 +215,7 @@ class ApiControllerTest < ActionController::TestCase 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 @@ -224,7 +224,7 @@ class ApiControllerTest < ActionController::TestCase # 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: @@ -234,7 +234,7 @@ class ApiControllerTest < ActionController::TestCase 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 @@ -246,7 +246,7 @@ class ApiControllerTest < ActionController::TestCase 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 @@ -267,7 +267,7 @@ class ApiControllerTest < ActionController::TestCase 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}" diff --git a/test/controllers/browse_controller_test.rb b/test/controllers/browse_controller_test.rb index 2ab9106f1..50bd253fc 100644 --- a/test/controllers/browse_controller_test.rb +++ b/test/controllers/browse_controller_test.rb @@ -135,7 +135,7 @@ class BrowseControllerTest < ActionController::TestCase 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 @@ -147,15 +147,15 @@ private 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" diff --git a/test/controllers/changeset_controller_test.rb b/test/controllers/changeset_controller_test.rb index b3d6d7eb2..07b06e675 100644 --- a/test/controllers/changeset_controller_test.rb +++ b/test/controllers/changeset_controller_test.rb @@ -62,7 +62,7 @@ class ChangesetControllerTest < ActionController::TestCase ) 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 }, @@ -90,7 +90,7 @@ class ChangesetControllerTest < ActionController::TestCase ) assert_routing( { :path => "/history/comments/feed", :method => :get }, - { :controller => "changeset", :action => "comments_feed", :format =>"rss" } + { :controller => "changeset", :action => "comments_feed", :format => "rss" } ) end @@ -107,7 +107,6 @@ class ChangesetControllerTest < ActionController::TestCase put :create assert_require_public_data - basic_authorization users(:public_user).email, "test" # Create the first user's changeset content "" + @@ -124,7 +123,7 @@ class ChangesetControllerTest < ActionController::TestCase # 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})" @@ -216,13 +215,11 @@ class ChangesetControllerTest < ActionController::TestCase 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" @@ -318,9 +315,7 @@ EOF 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" @@ -350,9 +345,7 @@ EOF 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" @@ -382,7 +375,7 @@ EOF 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" @@ -422,7 +415,7 @@ EOF 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 @@ -469,7 +462,7 @@ EOF # 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 @@ -479,7 +472,7 @@ EOF 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 @@ -507,7 +500,7 @@ EOF 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 @@ -573,7 +566,7 @@ EOF 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) @@ -601,7 +594,7 @@ EOF 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 @@ -628,7 +621,7 @@ EOF 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 @@ -671,7 +664,7 @@ EOF - + @@ -681,8 +674,7 @@ EOF 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 ## @@ -719,7 +711,7 @@ EOF 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 @@ -734,7 +726,7 @@ EOF # 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 @@ -781,7 +773,7 @@ EOF 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)) @@ -816,7 +808,7 @@ EOF 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 @@ -844,7 +836,7 @@ EOF 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 ## @@ -865,7 +857,7 @@ EOF 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 ## @@ -881,10 +873,10 @@ EOF
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 ## @@ -912,7 +904,7 @@ EOF 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 @@ -950,7 +942,7 @@ EOF 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 @@ -978,7 +970,7 @@ EOF 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 ## @@ -1008,7 +1000,7 @@ EOF 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 @@ -1032,7 +1024,7 @@ EOF 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 @@ -1063,7 +1055,7 @@ EOF 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 @@ -1087,7 +1079,7 @@ EOF 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 @@ -1120,14 +1112,14 @@ EOF 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 ## @@ -1159,14 +1151,14 @@ EOF 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 ## @@ -1174,10 +1166,10 @@ EOF def test_upload_empty_invalid basic_authorization users(:public_user).email, "test" - [ "", - "", - "", - "" + ["", + "", + "", + "" ].each do |diff| # upload it content diff @@ -1204,13 +1196,12 @@ EOF 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 ## @@ -1227,8 +1218,6 @@ EOF put :create assert_response :forbidden - - ## Now try with the public user basic_authorization(users(:public_user).email, "test") @@ -1260,7 +1249,7 @@ EOF 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 @@ -1319,7 +1308,7 @@ OSMFILE 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 @@ -1372,7 +1361,7 @@ EOF 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 @@ -1391,7 +1380,7 @@ EOF 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 @@ -1476,10 +1465,10 @@ EOF # 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 @@ -1495,8 +1484,8 @@ EOF 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 "" @@ -1510,9 +1499,8 @@ EOF # Try to use a hopefully missing changeset content "" - 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 ## @@ -1520,7 +1508,7 @@ EOF 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" @@ -1542,11 +1530,11 @@ EOF 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 @@ -1558,27 +1546,27 @@ EOF 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" @@ -1586,7 +1574,7 @@ EOF 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" @@ -1596,29 +1584,29 @@ EOF # 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 @@ -1650,7 +1638,6 @@ EOF 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 @@ -1734,7 +1721,7 @@ EOF 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 @@ -1763,25 +1750,25 @@ EOF ## # 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 @@ -1789,25 +1776,25 @@ EOF ## # 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 @@ -1816,7 +1803,7 @@ EOF # 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 @@ -1825,7 +1812,7 @@ EOF ## # 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 @@ -1835,13 +1822,13 @@ EOF 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 @@ -1850,7 +1837,7 @@ EOF # 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 @@ -1860,7 +1847,7 @@ EOF ## # 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 @@ -1886,7 +1873,7 @@ EOF 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 @@ -1895,32 +1882,32 @@ EOF # 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 @@ -1932,7 +1919,7 @@ EOF 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 @@ -1943,7 +1930,7 @@ EOF # 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 @@ -1951,21 +1938,21 @@ EOF # 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 @@ -1977,7 +1964,7 @@ EOF 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 @@ -1988,7 +1975,7 @@ EOF # 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 @@ -1996,21 +1983,21 @@ EOF # 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 @@ -2021,7 +2008,7 @@ EOF # 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 @@ -2029,14 +2016,14 @@ EOF # 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 @@ -2048,7 +2035,7 @@ EOF 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 @@ -2059,7 +2046,7 @@ EOF # 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 @@ -2067,14 +2054,14 @@ EOF # 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 @@ -2086,7 +2073,7 @@ EOF 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 @@ -2094,7 +2081,7 @@ EOF ## # 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 @@ -2103,7 +2090,7 @@ EOF 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 @@ -2157,6 +2144,6 @@ EOF # 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 diff --git a/test/controllers/diary_entry_controller_test.rb b/test/controllers/diary_entry_controller_test.rb index 464f5fbfe..1260fa468 100644 --- a/test/controllers/diary_entry_controller_test.rb +++ b/test/controllers/diary_entry_controller_test.rb @@ -91,11 +91,11 @@ class DiaryEntryControllerTest < ActionController::TestCase 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 @@ -123,7 +123,7 @@ class DiaryEntryControllerTest < ActionController::TestCase 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 @@ -131,7 +131,7 @@ class DiaryEntryControllerTest < ActionController::TestCase # 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 @@ -157,15 +157,15 @@ class DiaryEntryControllerTest < ActionController::TestCase 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 @@ -179,12 +179,12 @@ class DiaryEntryControllerTest < ActionController::TestCase 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 @@ -205,7 +205,7 @@ class DiaryEntryControllerTest < ActionController::TestCase 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 @@ -218,7 +218,7 @@ class DiaryEntryControllerTest < ActionController::TestCase 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 @@ -245,10 +245,10 @@ class DiaryEntryControllerTest < ActionController::TestCase 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 @@ -269,7 +269,7 @@ class DiaryEntryControllerTest < ActionController::TestCase 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 @@ -278,13 +278,13 @@ class DiaryEntryControllerTest < ActionController::TestCase # 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 @@ -308,20 +308,20 @@ class DiaryEntryControllerTest < ActionController::TestCase # Check that you can get the expected response and template for all available languages # Should test that there are no 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 @@ -333,64 +333,64 @@ class DiaryEntryControllerTest < ActionController::TestCase 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 @@ -403,18 +403,18 @@ class DiaryEntryControllerTest < ActionController::TestCase 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 @@ -422,18 +422,18 @@ class DiaryEntryControllerTest < ActionController::TestCase 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 diff --git a/test/controllers/directions_controller_test.rb b/test/controllers/directions_controller_test.rb index f24c9d205..e80d796bd 100644 --- a/test/controllers/directions_controller_test.rb +++ b/test/controllers/directions_controller_test.rb @@ -1,7 +1,6 @@ require 'test_helper' class DirectionsControllerTest < ActionController::TestCase - ## # test all routes which lead to this controller def test_routes @@ -17,5 +16,4 @@ class DirectionsControllerTest < ActionController::TestCase get :search assert_response :success end - end diff --git a/test/controllers/export_controller_test.rb b/test/controllers/export_controller_test.rb index 64ba70b19..ab93f74bc 100644 --- a/test/controllers/export_controller_test.rb +++ b/test/controllers/export_controller_test.rb @@ -1,7 +1,6 @@ require 'test_helper' class ExportControllerTest < ActionController::TestCase - ## # test all routes which lead to this controller def test_routes @@ -18,7 +17,7 @@ class ExportControllerTest < ActionController::TestCase ### # 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 @@ -26,7 +25,7 @@ class ExportControllerTest < ActionController::TestCase ### # 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 @@ -38,5 +37,4 @@ class ExportControllerTest < ActionController::TestCase assert_response :success assert_template "export/embed" end - end diff --git a/test/controllers/geocoder_controller_test.rb b/test/controllers/geocoder_controller_test.rb index 94cf7cf46..3ac4c090e 100644 --- a/test/controllers/geocoder_controller_test.rb +++ b/test/controllers/geocoder_controller_test.rb @@ -12,8 +12,8 @@ class GeocoderControllerTest < ActionController::TestCase { :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 }, @@ -49,10 +49,10 @@ class GeocoderControllerTest < ActionController::TestCase # 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 @@ -62,10 +62,10 @@ class GeocoderControllerTest < ActionController::TestCase # 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 @@ -75,10 +75,10 @@ class GeocoderControllerTest < ActionController::TestCase # 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 @@ -88,10 +88,10 @@ class GeocoderControllerTest < ActionController::TestCase # 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 @@ -101,10 +101,10 @@ class GeocoderControllerTest < ActionController::TestCase # 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 @@ -114,13 +114,13 @@ class GeocoderControllerTest < ActionController::TestCase # 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 @@ -130,13 +130,13 @@ class GeocoderControllerTest < ActionController::TestCase # 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 @@ -146,13 +146,13 @@ class GeocoderControllerTest < ActionController::TestCase # 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 @@ -162,13 +162,13 @@ class GeocoderControllerTest < ActionController::TestCase # 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 @@ -178,12 +178,12 @@ class GeocoderControllerTest < ActionController::TestCase # 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 @@ -193,12 +193,12 @@ class GeocoderControllerTest < ActionController::TestCase # 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 @@ -208,12 +208,12 @@ class GeocoderControllerTest < ActionController::TestCase # 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 @@ -223,12 +223,12 @@ class GeocoderControllerTest < ActionController::TestCase # 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 @@ -238,12 +238,12 @@ class GeocoderControllerTest < ActionController::TestCase # 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 @@ -252,21 +252,21 @@ class GeocoderControllerTest < ActionController::TestCase # 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 ## @@ -275,13 +275,14 @@ class GeocoderControllerTest < ActionController::TestCase 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] @@ -290,7 +291,7 @@ private 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] diff --git a/test/controllers/message_controller_test.rb b/test/controllers/message_controller_test.rb index ad604174d..2de1875ac 100644 --- a/test/controllers/message_controller_test.rb +++ b/test/controllers/message_controller_test.rb @@ -69,8 +69,8 @@ class MessageControllerTest < ActionController::TestCase 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 @@ -88,8 +88,8 @@ class MessageControllerTest < ActionController::TestCase 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 @@ -107,14 +107,14 @@ class MessageControllerTest < ActionController::TestCase 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 @@ -145,8 +145,8 @@ class MessageControllerTest < ActionController::TestCase 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/ @@ -384,7 +384,7 @@ class MessageControllerTest < ActionController::TestCase 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") diff --git a/test/controllers/node_controller_test.rb b/test/controllers/node_controller_test.rb index 771842b57..8fb6d8e16 100644 --- a/test/controllers/node_controller_test.rb +++ b/test/controllers/node_controller_test.rb @@ -33,8 +33,8 @@ class NodeControllerTest < ActionController::TestCase ## 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 @@ -45,14 +45,12 @@ class NodeControllerTest < ActionController::TestCase # 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 @@ -63,14 +61,12 @@ class NodeControllerTest < ActionController::TestCase # 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 @@ -139,11 +135,10 @@ class NodeControllerTest < ActionController::TestCase assert_equal "Cannot parse valid node from xml string . lon not a number", @response.body # test that the upload is rejected when we have a tag which is too long - content("") + content("") 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 @@ -167,9 +162,8 @@ class NodeControllerTest < ActionController::TestCase 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, @@ -178,7 +172,7 @@ class NodeControllerTest < ActionController::TestCase 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") @@ -201,18 +195,16 @@ class NodeControllerTest < ActionController::TestCase 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, @@ -221,7 +213,7 @@ class NodeControllerTest < ActionController::TestCase 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 @@ -229,13 +221,13 @@ class NodeControllerTest < ActionController::TestCase 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, :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) @@ -245,7 +237,7 @@ class NodeControllerTest < ActionController::TestCase # 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) @@ -261,14 +253,14 @@ class NodeControllerTest < ActionController::TestCase 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 @@ -283,8 +275,6 @@ class NodeControllerTest < ActionController::TestCase put :update, :id => current_nodes(:visible_node).id assert_response :unauthorized - - ## Second test with the private user # setup auth @@ -310,19 +300,19 @@ class NodeControllerTest < ActionController::TestCase 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" @@ -346,7 +336,7 @@ class NodeControllerTest < ActionController::TestCase # 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" @@ -362,19 +352,19 @@ class NodeControllerTest < ActionController::TestCase 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" @@ -383,34 +373,34 @@ class NodeControllerTest < ActionController::TestCase # 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 "" 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 @@ -465,7 +455,7 @@ class NodeControllerTest < ActionController::TestCase 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 @@ -483,7 +473,6 @@ class NodeControllerTest < ActionController::TestCase 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 @@ -530,7 +519,7 @@ class NodeControllerTest < ActionController::TestCase # 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 ## diff --git a/test/controllers/notes_controller_test.rb b/test/controllers/notes_controller_test.rb index fcb1ca9b8..25c6d096b 100644 --- a/test/controllers/notes_controller_test.rb +++ b/test/controllers/notes_controller_test.rb @@ -124,7 +124,7 @@ class NotesControllerTest < ActionController::TestCase 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 @@ -140,7 +140,7 @@ class NotesControllerTest < ActionController::TestCase 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 @@ -158,56 +158,56 @@ class NotesControllerTest < ActionController::TestCase 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 @@ -215,7 +215,7 @@ class NotesControllerTest < ActionController::TestCase 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) @@ -228,7 +228,7 @@ class NotesControllerTest < ActionController::TestCase 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 @@ -243,43 +243,43 @@ class NotesControllerTest < ActionController::TestCase 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 @@ -291,7 +291,7 @@ class NotesControllerTest < ActionController::TestCase 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 @@ -313,23 +313,23 @@ class NotesControllerTest < ActionController::TestCase 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 @@ -341,7 +341,7 @@ class NotesControllerTest < ActionController::TestCase 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 @@ -355,23 +355,23 @@ class NotesControllerTest < ActionController::TestCase 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 @@ -388,7 +388,7 @@ class NotesControllerTest < ActionController::TestCase 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 @@ -397,14 +397,14 @@ class NotesControllerTest < ActionController::TestCase 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) @@ -420,7 +420,7 @@ class NotesControllerTest < ActionController::TestCase 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 @@ -436,7 +436,7 @@ class NotesControllerTest < ActionController::TestCase 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 @@ -448,25 +448,25 @@ class NotesControllerTest < ActionController::TestCase 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 @@ -478,30 +478,30 @@ class NotesControllerTest < ActionController::TestCase 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 @@ -510,7 +510,7 @@ class NotesControllerTest < ActionController::TestCase 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) @@ -518,14 +518,14 @@ class NotesControllerTest < ActionController::TestCase 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 @@ -534,7 +534,7 @@ class NotesControllerTest < ActionController::TestCase 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 @@ -543,7 +543,7 @@ class NotesControllerTest < ActionController::TestCase 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) @@ -551,14 +551,14 @@ class NotesControllerTest < ActionController::TestCase 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 @@ -567,25 +567,25 @@ class NotesControllerTest < ActionController::TestCase 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) @@ -593,7 +593,7 @@ class NotesControllerTest < ActionController::TestCase 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) @@ -601,7 +601,7 @@ class NotesControllerTest < ActionController::TestCase 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) @@ -611,40 +611,40 @@ class NotesControllerTest < ActionController::TestCase 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) @@ -652,7 +652,7 @@ class NotesControllerTest < ActionController::TestCase 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 @@ -661,7 +661,7 @@ class NotesControllerTest < ActionController::TestCase 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 @@ -670,14 +670,14 @@ class NotesControllerTest < ActionController::TestCase 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) @@ -685,7 +685,7 @@ class NotesControllerTest < ActionController::TestCase 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 @@ -694,7 +694,7 @@ class NotesControllerTest < ActionController::TestCase 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 @@ -706,15 +706,15 @@ class NotesControllerTest < ActionController::TestCase 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 @@ -723,7 +723,7 @@ class NotesControllerTest < ActionController::TestCase 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 @@ -734,27 +734,27 @@ class NotesControllerTest < ActionController::TestCase 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 diff --git a/test/controllers/oauth_clients_controller_test.rb b/test/controllers/oauth_clients_controller_test.rb index 5b2c5b6e4..f32c6cf97 100644 --- a/test/controllers/oauth_clients_controller_test.rb +++ b/test/controllers/oauth_clients_controller_test.rb @@ -39,7 +39,7 @@ class OauthClientsControllerTest < ActionController::TestCase 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)) @@ -52,7 +52,7 @@ class OauthClientsControllerTest < ActionController::TestCase 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)) @@ -74,7 +74,7 @@ class OauthClientsControllerTest < ActionController::TestCase 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 @@ -82,11 +82,9 @@ class OauthClientsControllerTest < ActionController::TestCase 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" @@ -98,9 +96,7 @@ class OauthClientsControllerTest < ActionController::TestCase :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) @@ -110,7 +106,7 @@ class OauthClientsControllerTest < ActionController::TestCase 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)) @@ -127,7 +123,7 @@ class OauthClientsControllerTest < ActionController::TestCase 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)) @@ -153,7 +149,7 @@ class OauthClientsControllerTest < ActionController::TestCase 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 } @@ -167,9 +163,7 @@ class OauthClientsControllerTest < ActionController::TestCase :name => "New Name", :url => nil } - }, { - :user => user - } + }, { :user => user } assert_response :success assert_template "edit" @@ -180,9 +174,7 @@ class OauthClientsControllerTest < ActionController::TestCase :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 @@ -192,7 +184,7 @@ class OauthClientsControllerTest < ActionController::TestCase 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 diff --git a/test/controllers/old_node_controller_test.rb b/test/controllers/old_node_controller_test.rb index 74c540cb6..6e90773fa 100644 --- a/test/controllers/old_node_controller_test.rb +++ b/test/controllers/old_node_controller_test.rb @@ -44,7 +44,7 @@ class OldNodeControllerTest < ActionController::TestCase # 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 @@ -74,7 +74,7 @@ class OldNodeControllerTest < ActionController::TestCase 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 @@ -83,7 +83,6 @@ class OldNodeControllerTest < ActionController::TestCase # 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 @@ -95,7 +94,7 @@ class OldNodeControllerTest < ActionController::TestCase # 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 @@ -125,7 +124,7 @@ class OldNodeControllerTest < ActionController::TestCase 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 @@ -137,7 +136,7 @@ class OldNodeControllerTest < ActionController::TestCase 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) @@ -147,7 +146,7 @@ class OldNodeControllerTest < ActionController::TestCase 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) @@ -311,11 +310,11 @@ class OldNodeControllerTest < ActionController::TestCase # 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 ## @@ -323,6 +322,6 @@ class OldNodeControllerTest < ActionController::TestCase # 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 diff --git a/test/controllers/old_relation_controller_test.rb b/test/controllers/old_relation_controller_test.rb index 85f21a5f7..669e4431e 100644 --- a/test/controllers/old_relation_controller_test.rb +++ b/test/controllers/old_relation_controller_test.rb @@ -43,7 +43,7 @@ class OldRelationControllerTest < ActionController::TestCase 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 diff --git a/test/controllers/old_way_controller_test.rb b/test/controllers/old_way_controller_test.rb index 1fa0657fa..efaa029bd 100644 --- a/test/controllers/old_way_controller_test.rb +++ b/test/controllers/old_way_controller_test.rb @@ -69,7 +69,7 @@ class OldWayControllerTest < ActionController::TestCase 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 @@ -87,7 +87,7 @@ class OldWayControllerTest < ActionController::TestCase 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 @@ -221,5 +221,4 @@ class OldWayControllerTest < ActionController::TestCase # now redact it post :redact, :id => way.way_id, :version => way.version, :redaction => redaction.id end - end diff --git a/test/controllers/relation_controller_test.rb b/test/controllers/relation_controller_test.rb index 10ee25c81..2650d706c 100644 --- a/test/controllers/relation_controller_test.rb +++ b/test/controllers/relation_controller_test.rb @@ -70,19 +70,19 @@ class RelationControllerTest < ActionController::TestCase 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) @@ -109,7 +109,7 @@ class RelationControllerTest < ActionController::TestCase assert_response :success # FIXME check whether this contains the stuff we want! if $VERBOSE - print @response.body + print @response.body end end @@ -155,7 +155,7 @@ class RelationControllerTest < ActionController::TestCase 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 @@ -167,19 +167,18 @@ class RelationControllerTest < ActionController::TestCase 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 "" + - ""+ - "" + "" + "
" 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 @@ -192,9 +191,7 @@ class RelationControllerTest < ActionController::TestCase 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" @@ -207,28 +204,27 @@ class RelationControllerTest < ActionController::TestCase 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 @@ -239,56 +235,54 @@ class RelationControllerTest < ActionController::TestCase 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 "" + - ""+ - "" + "" + "" 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 @@ -305,27 +299,26 @@ class RelationControllerTest < ActionController::TestCase 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 # ------------------------------------ @@ -408,7 +401,7 @@ class RelationControllerTest < ActionController::TestCase 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 @@ -423,8 +416,8 @@ class RelationControllerTest < ActionController::TestCase # create some xml that should return an error content "" + - "" + - "" + "" + + "" put :create # expect failure assert_response :bad_request @@ -432,7 +425,6 @@ class RelationControllerTest < ActionController::TestCase assert_match(/The type is not allowed only, /, @response.body) end - # ------------------------------------- # Test deleting relations. # ------------------------------------- @@ -442,7 +434,6 @@ class RelationControllerTest < ActionController::TestCase 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") @@ -462,7 +453,7 @@ class RelationControllerTest < ActionController::TestCase 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 @@ -491,10 +482,8 @@ class RelationControllerTest < ActionController::TestCase 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 @@ -513,7 +502,7 @@ class RelationControllerTest < ActionController::TestCase 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 @@ -521,7 +510,7 @@ class RelationControllerTest < ActionController::TestCase 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) @@ -533,7 +522,7 @@ class RelationControllerTest < ActionController::TestCase 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... @@ -544,7 +533,7 @@ class RelationControllerTest < ActionController::TestCase # 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) @@ -561,7 +550,7 @@ class RelationControllerTest < ActionController::TestCase 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 @@ -574,7 +563,7 @@ class RelationControllerTest < ActionController::TestCase 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 @@ -603,7 +592,7 @@ class RelationControllerTest < ActionController::TestCase 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 @@ -634,12 +623,12 @@ class RelationControllerTest < ActionController::TestCase # 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) @@ -723,14 +712,14 @@ OSM 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 @@ -757,7 +746,7 @@ 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 @@ -781,11 +770,11 @@ OSM # 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) @@ -830,7 +819,7 @@ OSM # 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. @@ -840,7 +829,6 @@ OSM 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") @@ -903,7 +891,7 @@ OSM yield new_rel - return version + version end ## @@ -936,13 +924,13 @@ OSM 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 @@ -959,8 +947,8 @@ OSM 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 @@ -974,7 +962,7 @@ OSM # 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 ## diff --git a/test/controllers/site_controller_test.rb b/test/controllers/site_controller_test.rb index 07587bc4d..3fd41c662 100644 --- a/test/controllers/site_controller_test.rb +++ b/test/controllers/site_controller_test.rb @@ -155,7 +155,7 @@ class SiteControllerTest < ActionController::TestCase # 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 @@ -167,7 +167,7 @@ class SiteControllerTest < ActionController::TestCase 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 @@ -176,7 +176,7 @@ class SiteControllerTest < ActionController::TestCase 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 @@ -185,7 +185,7 @@ class SiteControllerTest < ActionController::TestCase 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 @@ -194,7 +194,7 @@ class SiteControllerTest < ActionController::TestCase 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 @@ -276,7 +276,7 @@ class SiteControllerTest < ActionController::TestCase 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 @@ -336,7 +336,7 @@ class SiteControllerTest < ActionController::TestCase # 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 diff --git a/test/controllers/trace_controller_test.rb b/test/controllers/trace_controller_test.rb index 408ae0cd1..4f5c4b3be 100644 --- a/test/controllers/trace_controller_test.rb +++ b/test/controllers/trace_controller_test.rb @@ -176,11 +176,11 @@ class TraceControllerTest < ActionController::TestCase 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 @@ -195,15 +195,15 @@ class TraceControllerTest < ActionController::TestCase 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 @@ -225,49 +225,49 @@ class TraceControllerTest < ActionController::TestCase # 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 @@ -275,84 +275,84 @@ class TraceControllerTest < ActionController::TestCase # 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 @@ -362,23 +362,23 @@ class TraceControllerTest < ActionController::TestCase 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) @@ -390,23 +390,23 @@ class TraceControllerTest < ActionController::TestCase # 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) @@ -494,7 +494,7 @@ class TraceControllerTest < ActionController::TestCase 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") @@ -536,7 +536,7 @@ class TraceControllerTest < ActionController::TestCase assert_response :not_found end -private + private def check_trace_feed(traces) assert_response :success @@ -549,12 +549,12 @@ private 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 @@ -569,7 +569,7 @@ private 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}")) diff --git a/test/controllers/user_blocks_controller_test.rb b/test/controllers/user_blocks_controller_test.rb index 717f1167a..db8e2564d 100644 --- a/test/controllers/user_blocks_controller_test.rb +++ b/test/controllers/user_blocks_controller_test.rb @@ -210,8 +210,8 @@ class UserBlocksControllerTest < ActionController::TestCase # 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] @@ -219,9 +219,9 @@ class UserBlocksControllerTest < ActionController::TestCase # 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) @@ -268,9 +268,9 @@ class UserBlocksControllerTest < ActionController::TestCase # 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] @@ -281,8 +281,8 @@ class UserBlocksControllerTest < ActionController::TestCase # 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] @@ -290,9 +290,9 @@ class UserBlocksControllerTest < ActionController::TestCase # 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] diff --git a/test/controllers/user_controller_test.rb b/test/controllers/user_controller_test.rb index 93b7f76d6..a0f0fcd3a 100644 --- a/test/controllers/user_controller_test.rb +++ b/test/controllers/user_controller_test.rb @@ -224,7 +224,7 @@ class UserControllerTest < ActionController::TestCase 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 @@ -246,7 +246,7 @@ class UserControllerTest < ActionController::TestCase 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 @@ -261,7 +261,7 @@ class UserControllerTest < ActionController::TestCase 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 @@ -276,7 +276,7 @@ class UserControllerTest < ActionController::TestCase 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 @@ -291,7 +291,7 @@ class UserControllerTest < ActionController::TestCase 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 @@ -305,9 +305,9 @@ class UserControllerTest < ActionController::TestCase 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), @@ -467,7 +467,7 @@ class UserControllerTest < ActionController::TestCase # 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" @@ -561,11 +561,11 @@ class UserControllerTest < ActionController::TestCase # 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 @@ -579,7 +579,7 @@ class UserControllerTest < ActionController::TestCase 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 @@ -593,7 +593,7 @@ class UserControllerTest < ActionController::TestCase 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 @@ -610,7 +610,7 @@ class UserControllerTest < ActionController::TestCase 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 @@ -627,7 +627,7 @@ class UserControllerTest < ActionController::TestCase 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 @@ -743,16 +743,16 @@ class UserControllerTest < ActionController::TestCase 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 @@ -762,7 +762,7 @@ class UserControllerTest < ActionController::TestCase 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 @@ -773,7 +773,7 @@ class UserControllerTest < ActionController::TestCase # 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] @@ -785,7 +785,7 @@ class UserControllerTest < ActionController::TestCase # 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] @@ -801,16 +801,16 @@ class UserControllerTest < ActionController::TestCase 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 @@ -820,7 +820,7 @@ class UserControllerTest < ActionController::TestCase 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 @@ -830,13 +830,13 @@ class UserControllerTest < ActionController::TestCase 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 @@ -844,17 +844,17 @@ class UserControllerTest < ActionController::TestCase 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 @@ -862,17 +862,17 @@ class UserControllerTest < ActionController::TestCase 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 diff --git a/test/controllers/user_roles_controller_test.rb b/test/controllers/user_roles_controller_test.rb index 1d005824d..81a8ac1a4 100644 --- a/test/controllers/user_roles_controller_test.rb +++ b/test/controllers/user_roles_controller_test.rb @@ -35,7 +35,6 @@ class UserRolesControllerTest < ActionController::TestCase 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 @@ -63,7 +62,6 @@ class UserRolesControllerTest < ActionController::TestCase 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 @@ -93,7 +91,6 @@ class UserRolesControllerTest < ActionController::TestCase 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 @@ -121,7 +118,6 @@ class UserRolesControllerTest < ActionController::TestCase 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 diff --git a/test/controllers/way_controller_test.rb b/test/controllers/way_controller_test.rb index 58984923c..3ae7aa36e 100644 --- a/test/controllers/way_controller_test.rb +++ b/test/controllers/way_controller_test.rb @@ -126,7 +126,7 @@ class WayControllerTest < ActionController::TestCase 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 @@ -145,25 +145,25 @@ class WayControllerTest < ActionController::TestCase 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 # ------------------------------------- @@ -185,7 +185,7 @@ class WayControllerTest < ActionController::TestCase 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 "" + @@ -193,7 +193,7 @@ class WayControllerTest < ActionController::TestCase 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 "" + @@ -201,8 +201,7 @@ class WayControllerTest < ActionController::TestCase 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" @@ -218,7 +217,7 @@ class WayControllerTest < ActionController::TestCase 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 @@ -227,7 +226,7 @@ class WayControllerTest < ActionController::TestCase 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 @@ -236,17 +235,17 @@ class WayControllerTest < ActionController::TestCase 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 "" + "" + - "" + + "" + "" 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 # ------------------------------------- @@ -259,7 +258,7 @@ class WayControllerTest < ActionController::TestCase 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 @@ -277,7 +276,7 @@ class WayControllerTest < ActionController::TestCase 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 @@ -289,7 +288,7 @@ class WayControllerTest < ActionController::TestCase # 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 @@ -301,16 +300,15 @@ class WayControllerTest < ActionController::TestCase 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 @@ -328,7 +326,7 @@ class WayControllerTest < ActionController::TestCase 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 @@ -341,7 +339,7 @@ class WayControllerTest < ActionController::TestCase # 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 @@ -352,7 +350,7 @@ class WayControllerTest < ActionController::TestCase 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 @@ -384,7 +382,7 @@ class WayControllerTest < ActionController::TestCase 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 @@ -403,7 +401,7 @@ class WayControllerTest < ActionController::TestCase 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 @@ -429,7 +427,7 @@ class WayControllerTest < ActionController::TestCase 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 @@ -450,9 +448,8 @@ class WayControllerTest < ActionController::TestCase 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 ## @@ -468,13 +465,13 @@ class WayControllerTest < ActionController::TestCase way_str = "" way_str << "" way_str << "" - way_str << ""; + way_str << "" # 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 @@ -484,13 +481,13 @@ class WayControllerTest < ActionController::TestCase way_str = "" way_str << "" way_str << "" - way_str << ""; + way_str << "" # 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 @@ -506,12 +503,12 @@ class WayControllerTest < ActionController::TestCase 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| @@ -531,6 +528,6 @@ class WayControllerTest < ActionController::TestCase # 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 diff --git a/test/helpers/asset_helper_test.rb b/test/helpers/asset_helper_test.rb index 20e450ed5..70debcd73 100644 --- a/test/helpers/asset_helper_test.rb +++ b/test/helpers/asset_helper_test.rb @@ -2,6 +2,6 @@ require 'test_helper' class AssetHelperTest < ActionView::TestCase def test_assets - assert assets("iD").kind_of?(Hash) + assert assets("iD").is_a?(Hash) end end diff --git a/test/helpers/browse_helper_test.rb b/test/helpers/browse_helper_test.rb index 5d5c038c2..2e949988f 100644 --- a/test/helpers/browse_helper_test.rb +++ b/test/helpers/browse_helper_test.rb @@ -95,21 +95,21 @@ class BrowseHelperTest < ActionView::TestCase 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 diff --git a/test/integration/client_application_test.rb b/test/integration/client_application_test.rb index a2361d618..9aa1bc56a 100644 --- a/test/integration/client_application_test.rb +++ b/test/integration/client_application_test.rb @@ -12,7 +12,7 @@ class ClientApplicationTest < ActionDispatch::IntegrationTest 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 @@ -41,7 +41,7 @@ class ClientApplicationTest < ActionDispatch::IntegrationTest 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| @@ -50,11 +50,10 @@ class ClientApplicationTest < ActionDispatch::IntegrationTest 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 diff --git a/test/integration/oauth_test.rb b/test/integration/oauth_test.rb index da8738b42..610c7f4e1 100644 --- a/test/integration/oauth_test.rb +++ b/test/integration/oauth_test.rb @@ -9,7 +9,7 @@ class OAuthTest < ActionDispatch::IntegrationTest 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 @@ -22,15 +22,15 @@ class OAuthTest < ActionDispatch::IntegrationTest 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 @@ -43,7 +43,7 @@ class OAuthTest < ActionDispatch::IntegrationTest 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 @@ -66,16 +66,16 @@ class OAuthTest < ActionDispatch::IntegrationTest 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 @@ -88,7 +88,7 @@ class OAuthTest < ActionDispatch::IntegrationTest 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 @@ -106,7 +106,7 @@ class OAuthTest < ActionDispatch::IntegrationTest 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 @@ -119,15 +119,15 @@ class OAuthTest < ActionDispatch::IntegrationTest 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 @@ -140,7 +140,7 @@ class OAuthTest < ActionDispatch::IntegrationTest 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 @@ -158,11 +158,11 @@ class OAuthTest < ActionDispatch::IntegrationTest 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 @@ -172,8 +172,8 @@ class OAuthTest < ActionDispatch::IntegrationTest 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}" @@ -181,13 +181,13 @@ class OAuthTest < ActionDispatch::IntegrationTest 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 @@ -198,7 +198,7 @@ class OAuthTest < ActionDispatch::IntegrationTest 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 @@ -212,8 +212,8 @@ class OAuthTest < ActionDispatch::IntegrationTest 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 @@ -223,8 +223,8 @@ class OAuthTest < ActionDispatch::IntegrationTest 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}" @@ -232,13 +232,13 @@ class OAuthTest < ActionDispatch::IntegrationTest 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 @@ -249,7 +249,7 @@ class OAuthTest < ActionDispatch::IntegrationTest 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 @@ -267,11 +267,11 @@ class OAuthTest < ActionDispatch::IntegrationTest 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 @@ -281,8 +281,8 @@ class OAuthTest < ActionDispatch::IntegrationTest 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("

The verification code is ([A-Za-z0-9]+).

") @@ -292,13 +292,13 @@ class OAuthTest < ActionDispatch::IntegrationTest 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 @@ -309,7 +309,7 @@ class OAuthTest < ActionDispatch::IntegrationTest 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 @@ -323,7 +323,7 @@ class OAuthTest < ActionDispatch::IntegrationTest assert_response :unauthorized end -private + private def signed_get(uri, options) uri = URI.parse(uri) diff --git a/test/integration/short_links_test.rb b/test/integration/short_links_test.rb index d1a6937cb..31c6cc111 100644 --- a/test/integration/short_links_test.rb +++ b/test/integration/short_links_test.rb @@ -6,13 +6,13 @@ class ShortLinksTest < ActionDispatch::IntegrationTest # 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 diff --git a/test/integration/user_blocks_test.rb b/test/integration/user_blocks_test.rb index db81117c3..1b2515cc7 100644 --- a/test/integration/user_blocks_test.rb +++ b/test/integration/user_blocks_test.rb @@ -4,7 +4,7 @@ class UserBlocksTest < ActionDispatch::IntegrationTest 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 @@ -43,12 +43,12 @@ class UserBlocksTest < ActionDispatch::IntegrationTest # 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 diff --git a/test/integration/user_changeset_comments_test.rb b/test/integration/user_changeset_comments_test.rb index 629929a1c..eb79d7183 100644 --- a/test/integration/user_changeset_comments_test.rb +++ b/test/integration/user_changeset_comments_test.rb @@ -26,7 +26,7 @@ class UserChangesetCommentsTest < ActionDispatch::IntegrationTest 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}" diff --git a/test/integration/user_creation_test.rb b/test/integration/user_creation_test.rb index 0efe2e1a7..e45ff5b2d 100644 --- a/test/integration/user_creation_test.rb +++ b/test/integration/user_creation_test.rb @@ -9,7 +9,7 @@ class UserCreationTest < ActionDispatch::IntegrationTest 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 @@ -18,12 +18,12 @@ class UserCreationTest < ActionDispatch::IntegrationTest 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 @@ -37,12 +37,12 @@ class UserCreationTest < ActionDispatch::IntegrationTest 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 @@ -54,14 +54,14 @@ class UserCreationTest < ActionDispatch::IntegrationTest 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" @@ -69,7 +69,7 @@ class UserCreationTest < ActionDispatch::IntegrationTest 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 @@ -106,10 +106,10 @@ class UserCreationTest < ActionDispatch::IntegrationTest 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 @@ -131,11 +131,11 @@ class UserCreationTest < ActionDispatch::IntegrationTest 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 @@ -149,13 +149,13 @@ class UserCreationTest < ActionDispatch::IntegrationTest 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 @@ -172,10 +172,10 @@ class UserCreationTest < ActionDispatch::IntegrationTest 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 @@ -196,13 +196,13 @@ class UserCreationTest < ActionDispatch::IntegrationTest 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 @@ -224,11 +224,11 @@ class UserCreationTest < ActionDispatch::IntegrationTest 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 diff --git a/test/integration/user_diaries_test.rb b/test/integration/user_diaries_test.rb index c724e6a00..f76df33ad 100644 --- a/test/integration/user_diaries_test.rb +++ b/test/integration/user_diaries_test.rb @@ -11,9 +11,9 @@ class UserDiariesTest < ActionDispatch::IntegrationTest 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 @@ -28,8 +28,8 @@ class UserDiariesTest < ActionDispatch::IntegrationTest 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 diff --git a/test/integration/user_login_test.rb b/test/integration/user_login_test.rb index ec91c1adc..10c0f63b8 100644 --- a/test/integration/user_login_test.rb +++ b/test/integration/user_login_test.rb @@ -16,13 +16,13 @@ class UserLoginTest < ActionDispatch::IntegrationTest 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 @@ -39,13 +39,13 @@ class UserLoginTest < ActionDispatch::IntegrationTest 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 @@ -62,13 +62,13 @@ class UserLoginTest < ActionDispatch::IntegrationTest 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 @@ -85,13 +85,13 @@ class UserLoginTest < ActionDispatch::IntegrationTest 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 @@ -108,13 +108,13 @@ class UserLoginTest < ActionDispatch::IntegrationTest 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 @@ -131,13 +131,13 @@ class UserLoginTest < ActionDispatch::IntegrationTest 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 @@ -154,13 +154,13 @@ class UserLoginTest < ActionDispatch::IntegrationTest 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 @@ -177,13 +177,13 @@ class UserLoginTest < ActionDispatch::IntegrationTest 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 @@ -200,13 +200,13 @@ class UserLoginTest < ActionDispatch::IntegrationTest 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 @@ -223,13 +223,13 @@ class UserLoginTest < ActionDispatch::IntegrationTest 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 @@ -246,13 +246,13 @@ class UserLoginTest < ActionDispatch::IntegrationTest 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 @@ -269,13 +269,13 @@ class UserLoginTest < ActionDispatch::IntegrationTest 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 @@ -289,7 +289,7 @@ class UserLoginTest < ActionDispatch::IntegrationTest 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) @@ -308,7 +308,7 @@ class UserLoginTest < ActionDispatch::IntegrationTest 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) @@ -327,8 +327,8 @@ class UserLoginTest < ActionDispatch::IntegrationTest 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 @@ -342,8 +342,8 @@ class UserLoginTest < ActionDispatch::IntegrationTest 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 @@ -357,7 +357,7 @@ class UserLoginTest < ActionDispatch::IntegrationTest 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) diff --git a/test/integration/user_roles_test.rb b/test/integration/user_roles_test.rb index 08031b4de..cbd0dbe80 100644 --- a/test/integration/user_roles_test.rb +++ b/test/integration/user_roles_test.rb @@ -16,7 +16,7 @@ class UserRolesTest < ActionDispatch::IntegrationTest check_fail(:revoke, :administrator_user, :moderator) end -private + private def check_fail(action, user, role) get '/login' @@ -24,7 +24,7 @@ private 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 @@ -41,7 +41,7 @@ private 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 diff --git a/test/integration/user_terms_seen_test.rb b/test/integration/user_terms_seen_test.rb index 554649396..d438a6c0c 100644 --- a/test/integration/user_terms_seen_test.rb +++ b/test/integration/user_terms_seen_test.rb @@ -27,7 +27,7 @@ class UserTermsSeenTest < ActionDispatch::IntegrationTest 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 => "/" @@ -35,7 +35,7 @@ class UserTermsSeenTest < ActionDispatch::IntegrationTest 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! @@ -53,7 +53,7 @@ class UserTermsSeenTest < ActionDispatch::IntegrationTest 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 => "/" @@ -67,10 +67,10 @@ class UserTermsSeenTest < ActionDispatch::IntegrationTest 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) diff --git a/test/lib/bounding_box_test.rb b/test/lib/bounding_box_test.rb index a5e4a39e0..eff48655c 100644 --- a/test/lib/bounding_box_test.rb +++ b/test/lib/bounding_box_test.rb @@ -10,39 +10,39 @@ class BoundingBoxTest < ActiveSupport::TestCase @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 @@ -56,8 +56,8 @@ class BoundingBoxTest < ActiveSupport::TestCase 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 @@ -65,14 +65,14 @@ class BoundingBoxTest < ActiveSupport::TestCase 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 @@ -81,7 +81,7 @@ class BoundingBoxTest < ActiveSupport::TestCase @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 @@ -90,27 +90,27 @@ class BoundingBoxTest < ActiveSupport::TestCase 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 @@ -120,7 +120,7 @@ class BoundingBoxTest < ActiveSupport::TestCase 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 @@ -130,7 +130,7 @@ class BoundingBoxTest < ActiveSupport::TestCase 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 @@ -140,7 +140,7 @@ class BoundingBoxTest < ActiveSupport::TestCase 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 @@ -152,13 +152,13 @@ class BoundingBoxTest < ActiveSupport::TestCase 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 @@ -167,7 +167,7 @@ class BoundingBoxTest < ActiveSupport::TestCase 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 @@ -176,36 +176,36 @@ class BoundingBoxTest < ActiveSupport::TestCase 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 @@ -292,7 +292,7 @@ class BoundingBoxTest < ActiveSupport::TestCase 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 @@ -300,8 +300,9 @@ class BoundingBoxTest < ActiveSupport::TestCase 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) diff --git a/test/lib/i18n_test.rb b/test/lib/i18n_test.rb index ea67e084e..700966928 100644 --- a/test/lib/i18n_test.rb +++ b/test/lib/i18n_test.rb @@ -13,7 +13,7 @@ class I18nTest < ActiveSupport::TestCase 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 @@ -31,8 +31,8 @@ class I18nTest < ActiveSupport::TestCase 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 @@ -49,31 +49,33 @@ class I18nTest < ActiveSupport::TestCase 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 diff --git a/test/lib/rich_text_test.rb b/test/lib/rich_text_test.rb index 14e6f2196..813dc3d35 100644 --- a/test/lib/rich_text_test.rb +++ b/test/lib/rich_text_test.rb @@ -156,7 +156,7 @@ class RichTextTest < ActiveSupport::TestCase end end -private + private def assert_html(richtext, &block) html = richtext.to_html diff --git a/test/lib/short_link_test.rb b/test/lib/short_link_test.rb index 401d133c3..9b198ffc7 100644 --- a/test/lib/short_link_test.rb +++ b/test/lib/short_link_test.rb @@ -5,9 +5,9 @@ class ShortLinkTest < ActiveSupport::TestCase # 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| @@ -18,7 +18,7 @@ class ShortLinkTest < ActiveSupport::TestCase # 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 @@ -35,7 +35,7 @@ class ShortLinkTest < ActiveSupport::TestCase 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 diff --git a/test/models/changeset_tag_test.rb b/test/models/changeset_tag_test.rb index 296183a45..75bbba0ba 100644 --- a/test/models/changeset_tag_test.rb +++ b/test/models/changeset_tag_test.rb @@ -12,7 +12,7 @@ class ChangesetTagTest < ActiveSupport::TestCase (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 @@ -24,13 +24,13 @@ class ChangesetTagTest < ActiveSupport::TestCase 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 @@ -41,7 +41,7 @@ class ChangesetTagTest < ActiveSupport::TestCase 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" @@ -64,7 +64,7 @@ class ChangesetTagTest < ActiveSupport::TestCase 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 diff --git a/test/models/changeset_test.rb b/test/models/changeset_test.rb index 715a90b92..f1ed1134e 100644 --- a/test/models/changeset_test.rb +++ b/test/models/changeset_test.rb @@ -9,72 +9,72 @@ class ChangesetTest < ActiveSupport::TestCase 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 = "" - 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 = "" - 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 = "" - 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 = "" - 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 = "" - 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 diff --git a/test/models/diary_entry_test.rb b/test/models/diary_entry_test.rb index 12fd69512..ad863a7de 100644 --- a/test/models/diary_entry_test.rb +++ b/test/models/diary_entry_test.rb @@ -10,18 +10,18 @@ class DiaryEntryTest < ActiveSupport::TestCase 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 @@ -41,7 +41,7 @@ class DiaryEntryTest < ActiveSupport::TestCase 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) diff --git a/test/models/friend_test.rb b/test/models/friend_test.rb index 9b0d34d41..240e3f148 100644 --- a/test/models/friend_test.rb +++ b/test/models/friend_test.rb @@ -7,5 +7,4 @@ class FriendTest < ActiveSupport::TestCase def test_friend_count assert_equal 1, Friend.count end - end diff --git a/test/models/message_test.rb b/test/models/message_test.rb index 622942737..05f3d9034 100644 --- a/test/models/message_test.rb +++ b/test/models/message_test.rb @@ -5,7 +5,7 @@ class MessageTest < ActiveSupport::TestCase 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. @@ -38,7 +38,7 @@ class MessageTest < ActiveSupport::TestCase 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 @@ -184,18 +184,18 @@ class MessageTest < ActiveSupport::TestCase 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 diff --git a/test/models/node_tag_test.rb b/test/models/node_tag_test.rb index 87f657ddc..49e91844a 100644 --- a/test/models/node_tag_test.rb +++ b/test/models/node_tag_test.rb @@ -12,7 +12,7 @@ class NodeTagTest < ActiveSupport::TestCase 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 @@ -22,7 +22,7 @@ class NodeTagTest < ActiveSupport::TestCase (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 @@ -34,13 +34,13 @@ class NodeTagTest < ActiveSupport::TestCase 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 @@ -51,7 +51,7 @@ class NodeTagTest < ActiveSupport::TestCase 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" @@ -74,7 +74,7 @@ class NodeTagTest < ActiveSupport::TestCase 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 diff --git a/test/models/node_test.rb b/test/models/node_test.rb index 9a38dd947..247707214 100644 --- a/test/models/node_test.rb +++ b/test/models/node_test.rb @@ -55,7 +55,7 @@ class NodeTest < ActiveSupport::TestCase 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 @@ -71,7 +71,7 @@ class NodeTest < ActiveSupport::TestCase 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 @@ -115,7 +115,7 @@ class NodeTest < ActiveSupport::TestCase 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) @@ -124,7 +124,7 @@ class NodeTest < ActiveSupport::TestCase 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 @@ -133,7 +133,7 @@ class NodeTest < ActiveSupport::TestCase 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 @@ -152,7 +152,7 @@ class NodeTest < ActiveSupport::TestCase 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 @@ -161,7 +161,7 @@ class NodeTest < ActiveSupport::TestCase 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 @@ -171,72 +171,72 @@ class NodeTest < ActiveSupport::TestCase version = 1 noid = "" # 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 = "" - 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 = "" - 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 = "" - 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 = "" - 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 = "" - 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 @@ -244,73 +244,73 @@ class NodeTest < ActiveSupport::TestCase id_list = ["", "0", "00", "0.0", "a"] id_list.each do |id| zero_id = "" - 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 = "" - 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 = "" - 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 = "" - 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 = "" - 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 @@ -335,7 +335,7 @@ class NodeTest < ActiveSupport::TestCase 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 diff --git a/test/models/note_comment_test.rb b/test/models/note_comment_test.rb index 75707d79b..9f10a62de 100644 --- a/test/models/note_comment_test.rb +++ b/test/models/note_comment_test.rb @@ -5,8 +5,8 @@ class NoteCommentTest < ActiveSupport::TestCase 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) @@ -22,10 +22,10 @@ class NoteCommentTest < ActiveSupport::TestCase 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) diff --git a/test/models/note_test.rb b/test/models/note_test.rb index 39efc7fe5..1c67a3aa0 100644 --- a/test/models/note_test.rb +++ b/test/models/note_test.rb @@ -5,8 +5,8 @@ class NoteTest < ActiveSupport::TestCase 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) diff --git a/test/models/oauth_nonce_test.rb b/test/models/oauth_nonce_test.rb index 04b8dad23..703774ec8 100644 --- a/test/models/oauth_nonce_test.rb +++ b/test/models/oauth_nonce_test.rb @@ -16,5 +16,4 @@ class OauthNonceTest < ActiveSupport::TestCase nonce2 = OauthNonce.remember(string, timestamp) assert_equal false, nonce2, "Shouldn't be able to remember the same nonce twice." end - end diff --git a/test/models/oauth_token_test.rb b/test/models/oauth_token_test.rb index da2e449f1..80056d2ea 100644 --- a/test/models/oauth_token_test.rb +++ b/test/models/oauth_token_test.rb @@ -22,5 +22,4 @@ class OauthTokenTest < ActiveSupport::TestCase tok.invalidate! assert_equal false, tok.authorized?, "Token should now be invalid." end - end diff --git a/test/models/old_node_tag_test.rb b/test/models/old_node_tag_test.rb index f3923d743..1e9ee19f7 100644 --- a/test/models/old_node_tag_test.rb +++ b/test/models/old_node_tag_test.rb @@ -13,7 +13,7 @@ class OldNodeTagTest < ActiveSupport::TestCase 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 @@ -26,13 +26,13 @@ class OldNodeTagTest < ActiveSupport::TestCase 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 @@ -44,7 +44,7 @@ class OldNodeTagTest < ActiveSupport::TestCase 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 @@ -69,7 +69,7 @@ class OldNodeTagTest < ActiveSupport::TestCase 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 diff --git a/test/models/old_node_test.rb b/test/models/old_node_test.rb index 9adac9f81..83b9863fc 100644 --- a/test/models/old_node_test.rb +++ b/test/models/old_node_test.rb @@ -55,7 +55,7 @@ class OldNodeTest < ActiveSupport::TestCase 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 @@ -71,7 +71,7 @@ class OldNodeTest < ActiveSupport::TestCase 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 diff --git a/test/models/old_relation_tag_test.rb b/test/models/old_relation_tag_test.rb index 21a6a1d66..de5a1008a 100644 --- a/test/models/old_relation_tag_test.rb +++ b/test/models/old_relation_tag_test.rb @@ -13,7 +13,7 @@ class OldRelationTagTest < ActiveSupport::TestCase 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 @@ -26,13 +26,13 @@ class OldRelationTagTest < ActiveSupport::TestCase 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 @@ -44,7 +44,7 @@ class OldRelationTagTest < ActiveSupport::TestCase 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 @@ -69,7 +69,7 @@ class OldRelationTagTest < ActiveSupport::TestCase 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 diff --git a/test/models/old_way_tag_test.rb b/test/models/old_way_tag_test.rb index 1194641da..e85cb3497 100644 --- a/test/models/old_way_tag_test.rb +++ b/test/models/old_way_tag_test.rb @@ -13,7 +13,7 @@ class OldWayTagTest < ActiveSupport::TestCase 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 @@ -26,13 +26,13 @@ class OldWayTagTest < ActiveSupport::TestCase 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 @@ -44,7 +44,7 @@ class OldWayTagTest < ActiveSupport::TestCase 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 @@ -69,7 +69,7 @@ class OldWayTagTest < ActiveSupport::TestCase 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 diff --git a/test/models/old_way_test.rb b/test/models/old_way_test.rb index d9b2a186a..77dcf92c2 100644 --- a/test/models/old_way_test.rb +++ b/test/models/old_way_test.rb @@ -92,13 +92,13 @@ class OldWayTest < ActiveSupport::TestCase 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 diff --git a/test/models/redaction_test.rb b/test/models/redaction_test.rb index 61b64f211..3d1aecc72 100644 --- a/test/models/redaction_test.rb +++ b/test/models/redaction_test.rb @@ -32,5 +32,4 @@ class RedactionTest < ActiveSupport::TestCase end assert_equal(true, n.redacted?, "Expected node to be redacted after redact! call.") end - end diff --git a/test/models/relation_tag_test.rb b/test/models/relation_tag_test.rb index ea095574c..9db80f0bf 100644 --- a/test/models/relation_tag_test.rb +++ b/test/models/relation_tag_test.rb @@ -12,7 +12,7 @@ class RelationTagTest < ActiveSupport::TestCase (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 @@ -24,13 +24,13 @@ class RelationTagTest < ActiveSupport::TestCase 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 @@ -41,7 +41,7 @@ class RelationTagTest < ActiveSupport::TestCase 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" @@ -64,7 +64,7 @@ class RelationTagTest < ActiveSupport::TestCase 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 diff --git a/test/models/relation_test.rb b/test/models/relation_test.rb index 33e2fa0b0..f21a8d029 100644 --- a/test/models/relation_test.rb +++ b/test/models/relation_test.rb @@ -9,35 +9,35 @@ class RelationTest < ActiveSupport::TestCase def test_from_xml_no_id noid = "" - 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 = "" - 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 = "" - 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 @@ -45,61 +45,61 @@ class RelationTest < ActiveSupport::TestCase id_list = ["", "0", "00", "0.0", "a"] id_list.each do |id| zero_id = "" - 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 = "" - 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 = "" - 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 = "" - 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 @@ -148,7 +148,7 @@ class RelationTest < ActiveSupport::TestCase 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 diff --git a/test/models/trace_test.rb b/test/models/trace_test.rb index 4b3c5b07d..3aaf75e87 100644 --- a/test/models/trace_test.rb +++ b/test/models/trace_test.rb @@ -39,17 +39,17 @@ class TraceTest < ActiveSupport::TestCase 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 @@ -106,7 +106,7 @@ class TraceTest < ActiveSupport::TestCase 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 diff --git a/test/models/tracepoint_test.rb b/test/models/tracepoint_test.rb index 7e2d449d0..0dedb713a 100644 --- a/test/models/tracepoint_test.rb +++ b/test/models/tracepoint_test.rb @@ -6,5 +6,4 @@ class TracepointTest < ActiveSupport::TestCase def test_tracepoint_count assert_equal 4, Tracepoint.count end - end diff --git a/test/models/tracetag_test.rb b/test/models/tracetag_test.rb index d5849e37f..0ad8cae2f 100644 --- a/test/models/tracetag_test.rb +++ b/test/models/tracetag_test.rb @@ -9,19 +9,19 @@ class TracetagTest < ActiveSupport::TestCase 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) diff --git a/test/models/user_preference_test.rb b/test/models/user_preference_test.rb index 2cadac3e8..de35193f5 100644 --- a/test/models/user_preference_test.rb +++ b/test/models/user_preference_test.rb @@ -20,7 +20,7 @@ class UserPreferenceTest < ActiveSupport::TestCase 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 @@ -29,27 +29,26 @@ class UserPreferenceTest < ActiveSupport::TestCase (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 diff --git a/test/models/user_test.rb b/test/models/user_test.rb index 0f74f8f3e..b517fd2af 100644 --- a/test/models/user_test.rb +++ b/test/models/user_test.rb @@ -44,10 +44,10 @@ class UserTest < ActiveSupport::TestCase 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) @@ -81,15 +81,15 @@ class UserTest < ActiveSupport::TestCase # 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\"", "
", "*ho", "\"help\"@", - "vergrößern", "ルシステムにも対応します", "輕觸搖晃的遊戲" ] + ok = ["Name", "'me", "he\"", "
", "*ho", "\"help\"@", + "vergrößern", "ルシステムにも対応します", "輕觸搖晃的遊戲"] # These need to be 3 chars in length, otherwise the length test above # should be used. - bad = [ "
", "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 = ["
", "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 @@ -129,10 +129,10 @@ class UserTest < ActiveSupport::TestCase 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 @@ -143,8 +143,8 @@ class UserTest < ActiveSupport::TestCase 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 @@ -190,12 +190,12 @@ class UserTest < ActiveSupport::TestCase 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? diff --git a/test/models/user_token_test.rb b/test/models/user_token_test.rb index c6d9a9554..fb2cc8f74 100644 --- a/test/models/user_token_test.rb +++ b/test/models/user_token_test.rb @@ -7,5 +7,4 @@ class UserTokenTest < ActiveSupport::TestCase def test_user_token_count assert_equal 0, UserToken.count end - end diff --git a/test/models/way_tag_test.rb b/test/models/way_tag_test.rb index 498c1ff10..3ac310780 100644 --- a/test/models/way_tag_test.rb +++ b/test/models/way_tag_test.rb @@ -12,7 +12,7 @@ class WayTagTest < ActiveSupport::TestCase (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 @@ -24,13 +24,13 @@ class WayTagTest < ActiveSupport::TestCase 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 @@ -41,7 +41,7 @@ class WayTagTest < ActiveSupport::TestCase 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" @@ -64,7 +64,7 @@ class WayTagTest < ActiveSupport::TestCase 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 diff --git a/test/models/way_test.rb b/test/models/way_test.rb index 69529e654..fb0a02f57 100644 --- a/test/models/way_test.rb +++ b/test/models/way_test.rb @@ -11,9 +11,9 @@ class WayTest < ActiveSupport::TestCase 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' @@ -29,12 +29,12 @@ class WayTest < ActiveSupport::TestCase 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? @@ -42,35 +42,35 @@ class WayTest < ActiveSupport::TestCase def test_from_xml_no_id noid = "" - 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 = "" - 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 = "" - 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 @@ -78,61 +78,61 @@ class WayTest < ActiveSupport::TestCase id_list = ["", "0", "00", "0.0", "a"] id_list.each do |id| zero_id = "" - 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 = "" - 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 = "" - 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 = "" - 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 @@ -184,7 +184,7 @@ class WayTest < ActiveSupport::TestCase 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 diff --git a/test/test_helper.rb b/test/test_helper.rb index 2787ed83f..718f7d643 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -6,14 +6,14 @@ load 'composite_primary_keys/fixtures.rb' 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 @@ -121,39 +121,36 @@ class ActiveSupport::TestCase # 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 @@ -162,9 +159,8 @@ class ActiveSupport::TestCase 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 -- 2.43.2