aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.rubocop.yml18
-rw-r--r--actioncable/CHANGELOG.md2
-rw-r--r--actioncable/lib/action_cable/channel/base.rb1
-rw-r--r--actioncable/lib/action_cable/subscription_adapter/postgresql.rb2
-rw-r--r--actioncable/test/channel/base_test.rb6
-rw-r--r--actioncable/test/client_test.rb44
-rw-r--r--actioncable/test/stubs/test_server.rb12
-rw-r--r--actioncable/test/subscription_adapter/common.rb2
-rw-r--r--actioncable/test/test_helper.rb2
-rwxr-xr-xactionmailer/bin/test4
-rw-r--r--actionmailer/lib/action_mailer/inline_preview_interceptor.rb2
-rw-r--r--actionmailer/lib/action_mailer/preview.rb6
-rw-r--r--actionmailer/lib/rails/generators/mailer/mailer_generator.rb6
-rw-r--r--actionmailer/test/base_test.rb19
-rw-r--r--actionmailer/test/caching_test.rb7
-rw-r--r--actionmailer/test/delivery_methods_test.rb10
-rw-r--r--actionmailer/test/mailers/base_mailer.rb8
-rw-r--r--actionmailer/test/url_test.rb2
-rw-r--r--actionpack/CHANGELOG.md40
-rwxr-xr-xactionpack/bin/test4
-rw-r--r--actionpack/lib/abstract_controller/caching.rb3
-rw-r--r--actionpack/lib/abstract_controller/caching/fragments.rb2
-rw-r--r--actionpack/lib/abstract_controller/callbacks.rb2
-rw-r--r--actionpack/lib/abstract_controller/collector.rb2
-rw-r--r--actionpack/lib/action_controller.rb1
-rw-r--r--actionpack/lib/action_controller/base.rb2
-rw-r--r--actionpack/lib/action_controller/log_subscriber.rb4
-rw-r--r--actionpack/lib/action_controller/metal.rb4
-rw-r--r--actionpack/lib/action_controller/metal/conditional_get.rb2
-rw-r--r--actionpack/lib/action_controller/metal/head.rb2
-rw-r--r--actionpack/lib/action_controller/metal/http_authentication.rb2
-rw-r--r--actionpack/lib/action_controller/metal/implicit_render.rb2
-rw-r--r--actionpack/lib/action_controller/metal/instrumentation.rb2
-rw-r--r--actionpack/lib/action_controller/metal/live.rb7
-rw-r--r--actionpack/lib/action_controller/metal/mime_responds.rb4
-rw-r--r--actionpack/lib/action_controller/metal/parameter_encoding.rb30
-rw-r--r--actionpack/lib/action_controller/metal/rendering.rb2
-rw-r--r--actionpack/lib/action_controller/metal/strong_parameters.rb10
-rw-r--r--actionpack/lib/action_controller/metal/testing.rb2
-rw-r--r--actionpack/lib/action_controller/test_case.rb44
-rw-r--r--actionpack/lib/action_dispatch/http/headers.rb2
-rw-r--r--actionpack/lib/action_dispatch/http/parameters.rb18
-rw-r--r--actionpack/lib/action_dispatch/http/request.rb3
-rw-r--r--actionpack/lib/action_dispatch/journey/formatter.rb2
-rw-r--r--actionpack/lib/action_dispatch/journey/parser.rb5
-rw-r--r--actionpack/lib/action_dispatch/journey/router.rb6
-rw-r--r--actionpack/lib/action_dispatch/journey/router/utils.rb4
-rw-r--r--actionpack/lib/action_dispatch/middleware/cookies.rb4
-rw-r--r--actionpack/lib/action_dispatch/middleware/debug_exceptions.rb2
-rw-r--r--actionpack/lib/action_dispatch/middleware/debug_locks.rb4
-rw-r--r--actionpack/lib/action_dispatch/middleware/public_exceptions.rb4
-rw-r--r--actionpack/lib/action_dispatch/middleware/show_exceptions.rb2
-rw-r--r--actionpack/lib/action_dispatch/railtie.rb4
-rw-r--r--actionpack/lib/action_dispatch/routing/mapper.rb10
-rw-r--r--actionpack/lib/action_dispatch/routing/polymorphic_routes.rb8
-rw-r--r--actionpack/lib/action_dispatch/routing/redirection.rb8
-rw-r--r--actionpack/lib/action_dispatch/routing/route_set.rb4
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/routing.rb4
-rw-r--r--actionpack/lib/action_dispatch/testing/integration.rb41
-rw-r--r--actionpack/test/abstract/translation_test.rb3
-rw-r--r--actionpack/test/abstract_unit.rb27
-rw-r--r--actionpack/test/controller/action_pack_assertions_test.rb2
-rw-r--r--actionpack/test/controller/api/params_wrapper_test.rb2
-rw-r--r--actionpack/test/controller/caching_test.rb8
-rw-r--r--actionpack/test/controller/default_url_options_with_before_action_test.rb2
-rw-r--r--actionpack/test/controller/filters_test.rb8
-rw-r--r--actionpack/test/controller/flash_hash_test.rb28
-rw-r--r--actionpack/test/controller/flash_test.rb8
-rw-r--r--actionpack/test/controller/helper_test.rb1
-rw-r--r--actionpack/test/controller/http_digest_authentication_test.rb4
-rw-r--r--actionpack/test/controller/http_token_authentication_test.rb6
-rw-r--r--actionpack/test/controller/integration_test.rb47
-rw-r--r--actionpack/test/controller/live_stream_test.rb24
-rw-r--r--actionpack/test/controller/log_subscriber_test.rb18
-rw-r--r--actionpack/test/controller/mime/respond_to_test.rb18
-rw-r--r--actionpack/test/controller/new_base/content_negotiation_test.rb2
-rw-r--r--actionpack/test/controller/new_base/render_action_test.rb3
-rw-r--r--actionpack/test/controller/new_base/render_file_test.rb2
-rw-r--r--actionpack/test/controller/parameter_encoding_test.rb73
-rw-r--r--actionpack/test/controller/parameters/accessors_test.rb2
-rw-r--r--actionpack/test/controller/parameters/always_permitted_parameters_test.rb3
-rw-r--r--actionpack/test/controller/parameters/dup_test.rb2
-rw-r--r--actionpack/test/controller/parameters/log_on_unpermitted_params_test.rb20
-rw-r--r--actionpack/test/controller/parameters/multi_parameter_attributes_test.rb3
-rw-r--r--actionpack/test/controller/parameters/mutators_test.rb2
-rw-r--r--actionpack/test/controller/parameters/nested_parameters_permit_test.rb34
-rw-r--r--actionpack/test/controller/parameters/parameters_permit_test.rb18
-rw-r--r--actionpack/test/controller/parameters/raise_on_unpermitted_params_test.rb6
-rw-r--r--actionpack/test/controller/params_wrapper_test.rb8
-rw-r--r--actionpack/test/controller/redirect_test.rb4
-rw-r--r--actionpack/test/controller/render_json_test.rb3
-rw-r--r--actionpack/test/controller/render_test.rb2
-rw-r--r--actionpack/test/controller/request_forgery_protection_test.rb33
-rw-r--r--actionpack/test/controller/required_params_test.rb4
-rw-r--r--actionpack/test/controller/resources_test.rb68
-rw-r--r--actionpack/test/controller/routing_test.rb289
-rw-r--r--actionpack/test/controller/send_file_test.rb3
-rw-r--r--actionpack/test/controller/test_case_test.rb40
-rw-r--r--actionpack/test/controller/url_for_integration_test.rb8
-rw-r--r--actionpack/test/controller/url_for_test.rb46
-rw-r--r--actionpack/test/controller/url_rewriter_test.rb2
-rw-r--r--actionpack/test/dispatch/cookies_test.rb32
-rw-r--r--actionpack/test/dispatch/debug_exceptions_test.rb6
-rw-r--r--actionpack/test/dispatch/header_test.rb30
-rw-r--r--actionpack/test/dispatch/mapper_test.rb8
-rw-r--r--actionpack/test/dispatch/middleware_stack_test.rb2
-rw-r--r--actionpack/test/dispatch/mount_test.rb4
-rw-r--r--actionpack/test/dispatch/prefix_generation_test.rb6
-rw-r--r--actionpack/test/dispatch/reloader_test.rb2
-rw-r--r--actionpack/test/dispatch/request/json_params_parsing_test.rb22
-rw-r--r--actionpack/test/dispatch/request/multipart_params_parsing_test.rb8
-rw-r--r--actionpack/test/dispatch/request/query_string_parsing_test.rb58
-rw-r--r--actionpack/test/dispatch/request/session_test.rb4
-rw-r--r--actionpack/test/dispatch/request_id_test.rb1
-rw-r--r--actionpack/test/dispatch/request_test.rb53
-rw-r--r--actionpack/test/dispatch/response_test.rb20
-rw-r--r--actionpack/test/dispatch/routing/inspector_test.rb5
-rw-r--r--actionpack/test/dispatch/routing_assertions_test.rb2
-rw-r--r--actionpack/test/dispatch/routing_test.rb52
-rw-r--r--actionpack/test/dispatch/session/cache_store_test.rb2
-rw-r--r--actionpack/test/dispatch/static_test.rb9
-rw-r--r--actionpack/test/dispatch/test_request_test.rb10
-rw-r--r--actionpack/test/fixtures/load_me.rb2
-rw-r--r--actionpack/test/journey/gtg/transition_table_test.rb2
-rw-r--r--actionpack/test/journey/nfa/simulator_test.rb2
-rw-r--r--actionpack/test/journey/path/pattern_test.rb2
-rw-r--r--actionpack/test/journey/route_test.rb20
-rw-r--r--actionpack/test/journey/router_test.rb32
-rw-r--r--actionview/CHANGELOG.md26
-rwxr-xr-xactionview/bin/test4
-rw-r--r--actionview/lib/action_view/base.rb2
-rw-r--r--actionview/lib/action_view/dependency_tracker.rb1
-rw-r--r--actionview/lib/action_view/helpers/asset_url_helper.rb24
-rw-r--r--actionview/lib/action_view/helpers/atom_feed_helper.rb4
-rw-r--r--actionview/lib/action_view/helpers/cache_helper.rb8
-rw-r--r--actionview/lib/action_view/helpers/date_helper.rb6
-rw-r--r--actionview/lib/action_view/helpers/form_helper.rb18
-rw-r--r--actionview/lib/action_view/helpers/javascript_helper.rb2
-rw-r--r--actionview/lib/action_view/helpers/tag_helper.rb4
-rw-r--r--actionview/lib/action_view/helpers/tags/base.rb4
-rw-r--r--actionview/lib/action_view/helpers/tags/password_field.rb2
-rw-r--r--actionview/lib/action_view/helpers/url_helper.rb2
-rw-r--r--actionview/lib/action_view/layouts.rb2
-rw-r--r--actionview/lib/action_view/log_subscriber.rb19
-rw-r--r--actionview/lib/action_view/lookup_context.rb2
-rw-r--r--actionview/lib/action_view/renderer/partial_renderer.rb32
-rw-r--r--actionview/lib/action_view/renderer/template_renderer.rb2
-rw-r--r--actionview/lib/action_view/template.rb3
-rw-r--r--actionview/lib/action_view/template/resolver.rb8
-rw-r--r--actionview/lib/action_view/test_case.rb4
-rw-r--r--actionview/lib/action_view/testing/resolvers.rb4
-rw-r--r--actionview/lib/action_view/view_paths.rb2
-rw-r--r--actionview/test/abstract_unit.rb4
-rw-r--r--actionview/test/actionpack/abstract/abstract_controller_test.rb8
-rw-r--r--actionview/test/actionpack/controller/render_test.rb12
-rw-r--r--actionview/test/actionpack/controller/view_paths_test.rb8
-rw-r--r--actionview/test/active_record_unit.rb5
-rw-r--r--actionview/test/activerecord/debug_helper_test.rb2
-rw-r--r--actionview/test/activerecord/relation_cache_test.rb2
-rw-r--r--actionview/test/template/asset_tag_helper_test.rb10
-rw-r--r--actionview/test/template/capture_helper_test.rb2
-rw-r--r--actionview/test/template/controller_helper_test.rb4
-rw-r--r--actionview/test/template/date_helper_i18n_test.rb8
-rw-r--r--actionview/test/template/date_helper_test.rb34
-rw-r--r--actionview/test/template/dependency_tracker_test.rb4
-rw-r--r--actionview/test/template/digestor_test.rb6
-rw-r--r--actionview/test/template/form_collections_helper_test.rb34
-rw-r--r--actionview/test/template/form_helper_test.rb12
-rw-r--r--actionview/test/template/form_options_helper_test.rb15
-rw-r--r--actionview/test/template/form_tag_helper_test.rb3
-rw-r--r--actionview/test/template/log_subscriber_test.rb64
-rw-r--r--actionview/test/template/lookup_context_test.rb2
-rw-r--r--actionview/test/template/number_helper_test.rb4
-rw-r--r--actionview/test/template/render_test.rb14
-rw-r--r--actionview/test/template/tag_helper_test.rb42
-rw-r--r--actionview/test/template/template_test.rb24
-rw-r--r--actionview/test/template/test_case_test.rb6
-rw-r--r--actionview/test/template/text_helper_test.rb2
-rw-r--r--actionview/test/template/url_helper_test.rb6
-rw-r--r--activejob/CHANGELOG.md6
-rw-r--r--activejob/lib/active_job/enqueuing.rb4
-rw-r--r--activejob/lib/active_job/exceptions.rb6
-rw-r--r--activejob/lib/active_job/logging.rb4
-rw-r--r--activejob/test/cases/exceptions_test.rb4
-rw-r--r--activejob/test/cases/queuing_test.rb2
-rw-r--r--activejob/test/cases/test_case_test.rb2
-rw-r--r--activejob/test/jobs/callback_job.rb1
-rw-r--r--activejob/test/jobs/retry_job.rb2
-rw-r--r--activejob/test/support/delayed_job/delayed/backend/test.rb14
-rw-r--r--activejob/test/support/integration/adapters/sneakers.rb1
-rw-r--r--activejob/test/support/que/inline.rb2
-rwxr-xr-xactivemodel/bin/test4
-rw-r--r--activemodel/lib/active_model/errors.rb7
-rw-r--r--activemodel/lib/active_model/translation.rb2
-rw-r--r--activemodel/lib/active_model/type/integer.rb2
-rw-r--r--activemodel/lib/active_model/validations/clusivity.rb10
-rw-r--r--activemodel/test/cases/attribute_methods_test.rb2
-rw-r--r--activemodel/test/cases/callbacks_test.rb4
-rw-r--r--activemodel/test/cases/serialization_test.rb68
-rw-r--r--activemodel/test/cases/translation_test.rb8
-rw-r--r--activemodel/test/cases/validations/callbacks_test.rb33
-rw-r--r--activemodel/test/cases/validations/conditional_validation_test.rb4
-rw-r--r--activemodel/test/cases/validations/confirmation_validation_test.rb5
-rw-r--r--activemodel/test/cases/validations/i18n_validation_test.rb10
-rw-r--r--activemodel/test/cases/validations/inclusion_validation_test.rb2
-rw-r--r--activemodel/test/cases/validations/length_validation_test.rb3
-rw-r--r--activemodel/test/cases/validations/numericality_validation_test.rb10
-rw-r--r--activemodel/test/cases/validations/with_validation_test.rb2
-rw-r--r--activemodel/test/cases/validations_test.rb10
-rw-r--r--activerecord/CHANGELOG.md17
-rwxr-xr-xactiverecord/bin/test4
-rw-r--r--activerecord/lib/active_record.rb2
-rw-r--r--activerecord/lib/active_record/aggregations.rb4
-rw-r--r--activerecord/lib/active_record/associations/collection_association.rb74
-rw-r--r--activerecord/lib/active_record/associations/collection_proxy.rb53
-rw-r--r--activerecord/lib/active_record/associations/has_one_association.rb2
-rw-r--r--activerecord/lib/active_record/associations/preloader/through_association.rb1
-rw-r--r--activerecord/lib/active_record/attribute.rb2
-rw-r--r--activerecord/lib/active_record/attribute_methods.rb6
-rw-r--r--activerecord/lib/active_record/attribute_methods/serialization.rb10
-rw-r--r--activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb2
-rw-r--r--activerecord/lib/active_record/base.rb2
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb4
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb6
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb8
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb49
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract_adapter.rb12
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb38
-rw-r--r--activerecord/lib/active_record/connection_adapters/connection_specification.rb6
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb4
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb18
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql/explain_pretty_printer.rb2
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb2
-rw-r--r--activerecord/lib/active_record/connection_adapters/schema_cache.rb1
-rw-r--r--activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb10
-rw-r--r--activerecord/lib/active_record/core.rb15
-rw-r--r--activerecord/lib/active_record/counter_cache.rb2
-rw-r--r--activerecord/lib/active_record/enum.rb2
-rw-r--r--activerecord/lib/active_record/fixture_set/file.rb2
-rw-r--r--activerecord/lib/active_record/locking/optimistic.rb1
-rw-r--r--activerecord/lib/active_record/log_subscriber.rb5
-rw-r--r--activerecord/lib/active_record/migration.rb2
-rw-r--r--activerecord/lib/active_record/migration/compatibility.rb4
-rw-r--r--activerecord/lib/active_record/model_schema.rb6
-rw-r--r--activerecord/lib/active_record/nested_attributes.rb4
-rw-r--r--activerecord/lib/active_record/no_touching.rb4
-rw-r--r--activerecord/lib/active_record/railtie.rb1
-rw-r--r--activerecord/lib/active_record/railties/databases.rake14
-rw-r--r--activerecord/lib/active_record/readonly_attributes.rb2
-rw-r--r--activerecord/lib/active_record/reflection.rb1
-rw-r--r--activerecord/lib/active_record/relation.rb2
-rw-r--r--activerecord/lib/active_record/relation/calculations.rb12
-rw-r--r--activerecord/lib/active_record/relation/delegation.rb2
-rw-r--r--activerecord/lib/active_record/relation/finder_methods.rb103
-rw-r--r--activerecord/lib/active_record/relation/predicate_builder.rb71
-rw-r--r--activerecord/lib/active_record/relation/predicate_builder/case_sensitive_handler.rb21
-rw-r--r--activerecord/lib/active_record/relation/query_methods.rb8
-rw-r--r--activerecord/lib/active_record/relation/where_clause_factory.rb2
-rw-r--r--activerecord/lib/active_record/sanitization.rb9
-rw-r--r--activerecord/lib/active_record/schema_dumper.rb6
-rw-r--r--activerecord/lib/active_record/scoping/default.rb4
-rw-r--r--activerecord/lib/active_record/scoping/named.rb2
-rw-r--r--activerecord/lib/active_record/secure_token.rb2
-rw-r--r--activerecord/lib/active_record/store.rb4
-rw-r--r--activerecord/lib/active_record/table_metadata.rb4
-rw-r--r--activerecord/lib/active_record/tasks/database_tasks.rb6
-rw-r--r--activerecord/lib/active_record/timestamp.rb4
-rw-r--r--activerecord/lib/active_record/validations/uniqueness.rb32
-rw-r--r--activerecord/lib/rails/generators/active_record/migration/migration_generator.rb2
-rw-r--r--activerecord/test/cases/adapter_test.rb8
-rw-r--r--activerecord/test/cases/adapters/mysql2/active_schema_test.rb4
-rw-r--r--activerecord/test/cases/adapters/mysql2/case_sensitivity_test.rb2
-rw-r--r--activerecord/test/cases/adapters/mysql2/connection_test.rb4
-rw-r--r--activerecord/test/cases/adapters/mysql2/json_test.rb24
-rw-r--r--activerecord/test/cases/adapters/mysql2/schema_test.rb8
-rw-r--r--activerecord/test/cases/adapters/postgresql/active_schema_test.rb6
-rw-r--r--activerecord/test/cases/adapters/postgresql/array_test.rb8
-rw-r--r--activerecord/test/cases/adapters/postgresql/connection_test.rb12
-rw-r--r--activerecord/test/cases/adapters/postgresql/datatype_test.rb1
-rw-r--r--activerecord/test/cases/adapters/postgresql/hstore_test.rb52
-rw-r--r--activerecord/test/cases/adapters/postgresql/json_test.rb30
-rw-r--r--activerecord/test/cases/adapters/postgresql/range_test.rb6
-rw-r--r--activerecord/test/cases/adapters/postgresql/schema_test.rb2
-rw-r--r--activerecord/test/cases/adapters/postgresql/utils_test.rb2
-rw-r--r--activerecord/test/cases/adapters/sqlite3/copy_table_test.rb14
-rw-r--r--activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb2
-rw-r--r--activerecord/test/cases/ar_schema_test.rb16
-rw-r--r--activerecord/test/cases/associations/belongs_to_associations_test.rb14
-rw-r--r--activerecord/test/cases/associations/callbacks_test.rb3
-rw-r--r--activerecord/test/cases/associations/cascaded_eager_loading_test.rb32
-rw-r--r--activerecord/test/cases/associations/eager_load_nested_include_test.rb6
-rw-r--r--activerecord/test/cases/associations/eager_singularization_test.rb1
-rw-r--r--activerecord/test/cases/associations/eager_test.rb78
-rw-r--r--activerecord/test/cases/associations/extension_test.rb2
-rw-r--r--activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb11
-rw-r--r--activerecord/test/cases/associations/has_many_associations_test.rb95
-rw-r--r--activerecord/test/cases/associations/has_many_through_associations_test.rb12
-rw-r--r--activerecord/test/cases/associations/has_one_associations_test.rb8
-rw-r--r--activerecord/test/cases/associations/has_one_through_associations_test.rb10
-rw-r--r--activerecord/test/cases/associations/inner_join_association_test.rb14
-rw-r--r--activerecord/test/cases/associations/inverse_associations_test.rb27
-rw-r--r--activerecord/test/cases/associations/join_model_test.rb17
-rw-r--r--activerecord/test/cases/associations/left_outer_join_association_test.rb31
-rw-r--r--activerecord/test/cases/associations_test.rb16
-rw-r--r--activerecord/test/cases/autosave_association_test.rb26
-rw-r--r--activerecord/test/cases/base_test.rb16
-rw-r--r--activerecord/test/cases/batches_test.rb20
-rw-r--r--activerecord/test/cases/calculations_test.rb4
-rw-r--r--activerecord/test/cases/callbacks_test.rb14
-rw-r--r--activerecord/test/cases/column_alias_test.rb6
-rw-r--r--activerecord/test/cases/column_definition_test.rb2
-rw-r--r--activerecord/test/cases/connection_adapters/connection_handler_test.rb2
-rw-r--r--activerecord/test/cases/connection_adapters/merge_and_resolve_default_url_config_test.rb4
-rw-r--r--activerecord/test/cases/connection_management_test.rb2
-rw-r--r--activerecord/test/cases/connection_specification/resolver_test.rb16
-rw-r--r--activerecord/test/cases/database_statements_test.rb7
-rw-r--r--activerecord/test/cases/dirty_test.rb12
-rw-r--r--activerecord/test/cases/explain_test.rb4
-rw-r--r--activerecord/test/cases/finder_respond_to_test.rb2
-rw-r--r--activerecord/test/cases/finder_test.rb37
-rw-r--r--activerecord/test/cases/fixture_set/file_test.rb2
-rw-r--r--activerecord/test/cases/fixtures_test.rb7
-rw-r--r--activerecord/test/cases/forbidden_attributes_protection_test.rb2
-rw-r--r--activerecord/test/cases/helper.rb17
-rw-r--r--activerecord/test/cases/i18n_test.rb14
-rw-r--r--activerecord/test/cases/inheritance_test.rb6
-rw-r--r--activerecord/test/cases/invertible_migration_test.rb4
-rw-r--r--activerecord/test/cases/locking_test.rb1
-rw-r--r--activerecord/test/cases/migration/change_schema_test.rb18
-rw-r--r--activerecord/test/cases/migration/change_table_test.rb10
-rw-r--r--activerecord/test/cases/migration/columns_test.rb7
-rw-r--r--activerecord/test/cases/migration/command_recorder_test.rb26
-rw-r--r--activerecord/test/cases/migration/create_join_table_test.rb6
-rw-r--r--activerecord/test/cases/migration/index_test.rb13
-rw-r--r--activerecord/test/cases/migration/references_foreign_key_test.rb4
-rw-r--r--activerecord/test/cases/migration/references_index_test.rb4
-rw-r--r--activerecord/test/cases/migration_test.rb15
-rw-r--r--activerecord/test/cases/modules_test.rb2
-rw-r--r--activerecord/test/cases/nested_attributes_test.rb53
-rw-r--r--activerecord/test/cases/nested_attributes_with_callbacks_test.rb16
-rw-r--r--activerecord/test/cases/persistence_test.rb5
-rw-r--r--activerecord/test/cases/readonly_test.rb1
-rw-r--r--activerecord/test/cases/reflection_test.rb2
-rw-r--r--activerecord/test/cases/relation/mutation_test.rb5
-rw-r--r--activerecord/test/cases/relation/or_test.rb4
-rw-r--r--activerecord/test/cases/relation/where_chain_test.rb2
-rw-r--r--activerecord/test/cases/relation/where_test.rb2
-rw-r--r--activerecord/test/cases/relation_test.rb16
-rw-r--r--activerecord/test/cases/relations_test.rb44
-rw-r--r--activerecord/test/cases/result_test.rb10
-rw-r--r--activerecord/test/cases/schema_dumper_test.rb4
-rw-r--r--activerecord/test/cases/scoping/default_scoping_test.rb2
-rw-r--r--activerecord/test/cases/scoping/named_scoping_test.rb20
-rw-r--r--activerecord/test/cases/scoping/relation_scoping_test.rb2
-rw-r--r--activerecord/test/cases/serialized_attribute_test.rb7
-rw-r--r--activerecord/test/cases/statement_cache_test.rb1
-rw-r--r--activerecord/test/cases/suppressor_test.rb2
-rw-r--r--activerecord/test/cases/tasks/database_tasks_test.rb34
-rw-r--r--activerecord/test/cases/test_case.rb20
-rw-r--r--activerecord/test/cases/timestamp_test.rb2
-rw-r--r--activerecord/test/cases/touch_later_test.rb9
-rw-r--r--activerecord/test/cases/transaction_callbacks_test.rb43
-rw-r--r--activerecord/test/cases/transaction_isolation_test.rb6
-rw-r--r--activerecord/test/cases/transactions_test.rb4
-rw-r--r--activerecord/test/cases/validations/i18n_generate_message_validation_test.rb10
-rw-r--r--activerecord/test/cases/validations/i18n_validation_test.rb18
-rw-r--r--activerecord/test/cases/validations/length_validation_test.rb3
-rw-r--r--activerecord/test/cases/validations_test.rb6
-rw-r--r--activerecord/test/cases/view_test.rb4
-rw-r--r--activerecord/test/cases/yaml_serialization_test.rb4
-rw-r--r--activerecord/test/models/author.rb12
-rw-r--r--activerecord/test/models/book.rb2
-rw-r--r--activerecord/test/models/comment.rb4
-rw-r--r--activerecord/test/models/customer.rb2
-rw-r--r--activerecord/test/models/invoice.rb2
-rw-r--r--activerecord/test/models/member.rb2
-rw-r--r--activerecord/test/models/person.rb1
-rw-r--r--activerecord/test/models/pirate.rb16
-rw-r--r--activerecord/test/models/post.rb14
-rw-r--r--activerecord/test/models/project.rb8
-rw-r--r--activerecord/test/models/sponsor.rb2
-rw-r--r--activerecord/test/models/subject.rb2
-rw-r--r--activerecord/test/models/topic.rb2
-rw-r--r--activerecord/test/schema/schema.rb2
-rw-r--r--activesupport/CHANGELOG.md40
-rwxr-xr-xactivesupport/bin/test4
-rw-r--r--activesupport/lib/active_support/cache.rb10
-rw-r--r--activesupport/lib/active_support/cache/file_store.rb6
-rw-r--r--activesupport/lib/active_support/cache/mem_cache_store.rb6
-rw-r--r--activesupport/lib/active_support/cache/memory_store.rb4
-rw-r--r--activesupport/lib/active_support/cache/strategy/local_cache.rb10
-rw-r--r--activesupport/lib/active_support/callbacks.rb10
-rw-r--r--activesupport/lib/active_support/concurrency/share_lock.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/date_and_time/zones.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/digest/uuid.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/hash/compact.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/hash/keys.rb12
-rw-r--r--activesupport/lib/active_support/core_ext/hash/reverse_merge.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/module/aliasing.rb3
-rw-r--r--activesupport/lib/active_support/core_ext/module/attr_internal.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb20
-rw-r--r--activesupport/lib/active_support/core_ext/object/inclusion.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/string/access.rb4
-rw-r--r--activesupport/lib/active_support/core_ext/string/indent.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/string/inflections.rb2
-rw-r--r--activesupport/lib/active_support/dependencies.rb4
-rw-r--r--activesupport/lib/active_support/duration.rb4
-rw-r--r--activesupport/lib/active_support/hash_with_indifferent_access.rb3
-rw-r--r--activesupport/lib/active_support/inflector/inflections.rb4
-rw-r--r--activesupport/lib/active_support/lazy_load_hooks.rb2
-rw-r--r--activesupport/lib/active_support/message_encryptor.rb2
-rw-r--r--activesupport/lib/active_support/multibyte/chars.rb2
-rw-r--r--activesupport/lib/active_support/multibyte/unicode.rb2
-rw-r--r--activesupport/lib/active_support/ordered_hash.rb2
-rw-r--r--activesupport/lib/active_support/test_case.rb1
-rw-r--r--activesupport/lib/active_support/testing/isolation.rb4
-rw-r--r--activesupport/lib/active_support/time_with_zone.rb4
-rw-r--r--activesupport/lib/active_support/values/time_zone.rb2
-rw-r--r--activesupport/lib/active_support/xml_mini.rb2
-rw-r--r--activesupport/lib/active_support/xml_mini/jdom.rb2
-rw-r--r--activesupport/lib/active_support/xml_mini/rexml.rb2
-rw-r--r--activesupport/test/benchmarkable_test.rb4
-rw-r--r--activesupport/test/caching_test.rb27
-rw-r--r--activesupport/test/callback_inheritance_test.rb10
-rw-r--r--activesupport/test/callbacks_test.rb24
-rw-r--r--activesupport/test/concern_test.rb2
-rw-r--r--activesupport/test/core_ext/duration_test.rb2
-rw-r--r--activesupport/test/core_ext/enumerable_test.rb16
-rw-r--r--activesupport/test/core_ext/hash/transform_keys_test.rb2
-rw-r--r--activesupport/test/core_ext/hash_ext_test.rb129
-rw-r--r--activesupport/test/core_ext/load_error_test.rb1
-rw-r--r--activesupport/test/core_ext/marshal_test.rb2
-rw-r--r--activesupport/test/core_ext/module/attribute_accessor_per_thread_test.rb16
-rw-r--r--activesupport/test/core_ext/module/attribute_accessor_test.rb2
-rw-r--r--activesupport/test/core_ext/module/concerning_test.rb2
-rw-r--r--activesupport/test/core_ext/module/qualified_const_test.rb14
-rw-r--r--activesupport/test/core_ext/module/remove_method_test.rb16
-rw-r--r--activesupport/test/core_ext/module_test.rb7
-rw-r--r--activesupport/test/core_ext/numeric_ext_test.rb14
-rw-r--r--activesupport/test/core_ext/object/instance_variables_test.rb2
-rw-r--r--activesupport/test/core_ext/object/to_query_test.rb8
-rw-r--r--activesupport/test/core_ext/time_with_zone_test.rb8
-rw-r--r--activesupport/test/dependencies_test.rb15
-rw-r--r--activesupport/test/deprecation_test.rb3
-rw-r--r--activesupport/test/evented_file_update_checker_test.rb2
-rw-r--r--activesupport/test/executor_test.rb10
-rw-r--r--activesupport/test/file_update_checker_shared_tests.rb2
-rw-r--r--activesupport/test/inflector_test.rb1
-rw-r--r--activesupport/test/json/decoding_test.rb76
-rw-r--r--activesupport/test/json/encoding_test.rb61
-rw-r--r--activesupport/test/json/encoding_test_cases.rb4
-rw-r--r--activesupport/test/logger_test.rb8
-rw-r--r--activesupport/test/multibyte_chars_test.rb4
-rw-r--r--activesupport/test/multibyte_conformance_test.rb4
-rw-r--r--activesupport/test/multibyte_grapheme_break_conformance_test.rb6
-rw-r--r--activesupport/test/multibyte_normalization_conformance_test.rb6
-rw-r--r--activesupport/test/multibyte_test_helpers.rb2
-rw-r--r--activesupport/test/multibyte_unicode_database_test.rb1
-rw-r--r--activesupport/test/notifications_test.rb2
-rw-r--r--activesupport/test/number_helper_i18n_test.rb10
-rw-r--r--activesupport/test/number_helper_test.rb14
-rw-r--r--activesupport/test/option_merger_test.rb6
-rw-r--r--activesupport/test/ordered_hash_test.rb6
-rw-r--r--activesupport/test/reloader_test.rb8
-rw-r--r--activesupport/test/rescuable_test.rb1
-rw-r--r--activesupport/test/safe_buffer_test.rb2
-rw-r--r--activesupport/test/share_lock_test.rb2
-rw-r--r--activesupport/test/transliterate_test.rb4
-rw-r--r--activesupport/test/xml_mini/jdom_engine_test.rb2
-rw-r--r--activesupport/test/xml_mini/libxml_engine_test.rb1
-rw-r--r--activesupport/test/xml_mini/rexml_engine_test.rb2
-rw-r--r--activesupport/test/xml_mini_test.rb12
-rw-r--r--guides/rails_guides/helpers.rb2
-rw-r--r--guides/rails_guides/kindle.rb18
-rw-r--r--guides/rails_guides/markdown.rb3
-rw-r--r--guides/source/5_0_release_notes.md2
-rw-r--r--guides/source/action_cable_overview.md6
-rw-r--r--guides/source/active_model_basics.md7
-rw-r--r--guides/source/active_record_querying.md5
-rw-r--r--guides/source/caching_with_rails.md24
-rw-r--r--guides/source/configuring.md18
-rw-r--r--guides/source/debugging_rails_applications.md1
-rw-r--r--guides/source/getting_started.md2
-rw-r--r--guides/source/i18n.md2
-rw-r--r--guides/source/upgrading_ruby_on_rails.md4
-rw-r--r--guides/w3c_validator.rb2
-rw-r--r--railties/lib/rails/application/finisher.rb4
-rw-r--r--railties/lib/rails/code_statistics.rb6
-rw-r--r--railties/lib/rails/code_statistics_calculator.rb2
-rw-r--r--railties/lib/rails/commands/commands_tasks.rb114
-rw-r--r--railties/lib/rails/commands/common_commands_tasks.rb68
-rw-r--r--railties/lib/rails/commands/dbconsole.rb2
-rw-r--r--railties/lib/rails/commands/plugin.rb9
-rw-r--r--railties/lib/rails/commands/rake_proxy.rb11
-rw-r--r--railties/lib/rails/commands/runner.rb4
-rw-r--r--railties/lib/rails/commands/server.rb3
-rw-r--r--railties/lib/rails/engine.rb8
-rw-r--r--railties/lib/rails/engine/commands_tasks.rb110
-rw-r--r--railties/lib/rails/generators.rb4
-rw-r--r--railties/lib/rails/generators/actions.rb1
-rw-r--r--railties/lib/rails/generators/base.rb6
-rw-r--r--railties/lib/rails/generators/generated_attribute.rb4
-rw-r--r--railties/lib/rails/generators/named_base.rb6
-rw-r--r--railties/lib/rails/generators/rails/app/app_generator.rb6
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt2
-rw-r--r--railties/lib/rails/generators/rails/plugin/plugin_generator.rb2
-rw-r--r--railties/lib/rails/generators/resource_helpers.rb2
-rw-r--r--railties/lib/rails/generators/testing/behaviour.rb8
-rw-r--r--railties/lib/rails/info.rb6
-rw-r--r--railties/lib/rails/info_controller.rb8
-rw-r--r--railties/lib/rails/mailers_controller.rb6
-rw-r--r--railties/lib/rails/railtie/configurable.rb2
-rw-r--r--railties/lib/rails/tasks/routes.rake2
-rw-r--r--railties/lib/rails/test_unit/reporter.rb2
-rw-r--r--railties/lib/rails/test_unit/testing.rake6
-rw-r--r--railties/test/application/asset_debugging_test.rb2
-rw-r--r--railties/test/application/configuration_test.rb7
-rw-r--r--railties/test/application/generators_test.rb4
-rw-r--r--railties/test/application/loading_test.rb2
-rw-r--r--railties/test/application/middleware/cache_test.rb4
-rw-r--r--railties/test/application/middleware_test.rb2
-rw-r--r--railties/test/application/rake/migrations_test.rb2
-rw-r--r--railties/test/application/rake_test.rb32
-rw-r--r--railties/test/application/routing_test.rb2
-rw-r--r--railties/test/application/runner_test.rb10
-rw-r--r--railties/test/commands/console_test.rb1
-rw-r--r--railties/test/commands/dbconsole_test.rb12
-rw-r--r--railties/test/engine/commands_tasks_test.rb24
-rw-r--r--railties/test/generators/actions_test.rb6
-rw-r--r--railties/test/generators/app_generator_test.rb4
-rw-r--r--railties/test/generators/controller_generator_test.rb2
-rw-r--r--railties/test/generators/generator_generator_test.rb8
-rw-r--r--railties/test/generators/helper_generator_test.rb2
-rw-r--r--railties/test/generators/mailer_generator_test.rb6
-rw-r--r--railties/test/generators/model_generator_test.rb16
-rw-r--r--railties/test/generators/plugin_generator_test.rb13
-rw-r--r--railties/test/generators/shared_generator_tests.rb10
-rw-r--r--railties/test/generators_test.rb20
-rw-r--r--railties/test/isolation/abstract_unit.rb6
-rw-r--r--railties/test/json_params_parsing_test.rb49
-rw-r--r--railties/test/path_generation_test.rb4
-rw-r--r--railties/test/paths_test.rb4
-rw-r--r--railties/test/rack_logger_test.rb2
-rw-r--r--railties/test/rails_info_test.rb4
-rw-r--r--railties/test/railties/engine_test.rb4
-rw-r--r--railties/test/railties/mounted_engine_test.rb2
-rwxr-xr-xtools/profile4
548 files changed, 3362 insertions, 2740 deletions
diff --git a/.rubocop.yml b/.rubocop.yml
index 6ab1146b40..8f619b7956 100644
--- a/.rubocop.yml
+++ b/.rubocop.yml
@@ -1,7 +1,7 @@
AllCops:
TargetRubyVersion: 2.3
# RuboCop has a bunch of cops enabled by default. This setting tells RuboCop
- # to ignore them, so only the ones explictily set in this file are enabled.
+ # to ignore them, so only the ones explicitly set in this file are enabled.
DisabledByDefault: true
Exclude:
- '**/templates/**/*'
@@ -20,6 +20,10 @@ Style/BracesAroundHashParameters:
Style/CaseIndentation:
Enabled: true
+# No extra empty lines.
+Style/EmptyLines:
+ Enabled: true
+
# In a regular class definition, no empty lines around the body.
Style/EmptyLinesAroundClassBody:
Enabled: true
@@ -46,6 +50,18 @@ Style/IndentationWidth:
Style/MethodDefParentheses:
Enabled: true
+# Use `foo {}` not `foo{}`.
+Style/SpaceBeforeBlockBraces:
+ Enabled: true
+
+# Use `foo { bar }` not `foo {bar}`.
+Style/SpaceInsideBlockBraces:
+ Enabled: true
+
+# Use `{ a: 1 }` not `{a:1}`.
+Style/SpaceInsideHashLiteralBraces:
+ Enabled: true
+
# Check quotes usage according to lint rule below.
Style/StringLiterals:
Enabled: true
diff --git a/actioncable/CHANGELOG.md b/actioncable/CHANGELOG.md
index cc15e9bf61..dec6f7c027 100644
--- a/actioncable/CHANGELOG.md
+++ b/actioncable/CHANGELOG.md
@@ -3,7 +3,7 @@
*Tinco Andringa*
-* Add ActiveSupport::Notifications hook to Broadcaster#broadcast
+* Add ActiveSupport::Notifications hook to Broadcaster#broadcast.
*Matthew Wear*
diff --git a/actioncable/lib/action_cable/channel/base.rb b/actioncable/lib/action_cable/channel/base.rb
index 1dda0e407f..8ab061171e 100644
--- a/actioncable/lib/action_cable/channel/base.rb
+++ b/actioncable/lib/action_cable/channel/base.rb
@@ -177,7 +177,6 @@ module ActionCable
end
end
-
protected
# Called once a consumer has become a subscriber of the channel. Usually the place to setup any streams
# you want this channel to be sending to the subscriber.
diff --git a/actioncable/lib/action_cable/subscription_adapter/postgresql.rb b/actioncable/lib/action_cable/subscription_adapter/postgresql.rb
index 2637bfbea3..bdab5205ec 100644
--- a/actioncable/lib/action_cable/subscription_adapter/postgresql.rb
+++ b/actioncable/lib/action_cable/subscription_adapter/postgresql.rb
@@ -33,7 +33,7 @@ module ActionCable
pg_conn = ar_conn.raw_connection
unless pg_conn.is_a?(PG::Connection)
- raise "ActiveRecord database must be Postgres in order to use the Postgres ActionCable storage adapter"
+ raise "The Active Record database must be PostgreSQL in order to use the PostgreSQL Action Cable storage adapter"
end
yield pg_conn
diff --git a/actioncable/test/channel/base_test.rb b/actioncable/test/channel/base_test.rb
index 69bbeb7818..2bb3214f74 100644
--- a/actioncable/test/channel/base_test.rb
+++ b/actioncable/test/channel/base_test.rb
@@ -146,7 +146,7 @@ class ActionCable::Channel::BaseTest < ActiveSupport::TestCase
test "transmitting data" do
@channel.perform_action "action" => :get_latest
- expected = { "identifier" => "{id: 1}", "message" => { "data" => "latest" }}
+ expected = { "identifier" => "{id: 1}", "message" => { "data" => "latest" } }
assert_equal expected, @connection.last_transmission
end
@@ -173,7 +173,7 @@ class ActionCable::Channel::BaseTest < ActiveSupport::TestCase
events << ActiveSupport::Notifications::Event.new(*args)
end
- data = {"action" => :speak, "content" => "hello"}
+ data = { "action" => :speak, "content" => "hello" }
@channel.perform_action data
assert_equal 1, events.length
@@ -194,7 +194,7 @@ class ActionCable::Channel::BaseTest < ActiveSupport::TestCase
end
@channel.perform_action "action" => :get_latest
- expected_data = {data: "latest"}
+ expected_data = { data: "latest" }
assert_equal 1, events.length
assert_equal "transmit.action_cable", events[0].name
diff --git a/actioncable/test/client_test.rb b/actioncable/test/client_test.rb
index 16fe2abdee..2e3821828f 100644
--- a/actioncable/test/client_test.rb
+++ b/actioncable/test/client_test.rb
@@ -168,11 +168,11 @@ class ClientTest < ActionCable::TestCase
def test_single_client
with_puma_server do |port|
c = faye_client(port)
- assert_equal({"type" => "welcome"}, c.read_message) # pop the first welcome message off the stack
+ assert_equal({ "type" => "welcome" }, c.read_message) # pop the first welcome message off the stack
c.send_message command: "subscribe", identifier: JSON.generate(channel: "ClientTest::EchoChannel")
- assert_equal({"identifier"=>"{\"channel\":\"ClientTest::EchoChannel\"}", "type"=>"confirm_subscription"}, c.read_message)
+ assert_equal({ "identifier"=>"{\"channel\":\"ClientTest::EchoChannel\"}", "type"=>"confirm_subscription" }, c.read_message)
c.send_message command: "message", identifier: JSON.generate(channel: "ClientTest::EchoChannel"), data: JSON.generate(action: "ding", message: "hello")
- assert_equal({"identifier"=>"{\"channel\":\"ClientTest::EchoChannel\"}", "message"=>{"dong"=>"hello"}}, c.read_message)
+ assert_equal({ "identifier"=>"{\"channel\":\"ClientTest::EchoChannel\"}", "message"=>{ "dong"=>"hello" } }, c.read_message)
c.close
end
end
@@ -184,19 +184,19 @@ class ClientTest < ActionCable::TestCase
barrier_1 = Concurrent::CyclicBarrier.new(clients.size)
barrier_2 = Concurrent::CyclicBarrier.new(clients.size)
- clients.map {|c| Concurrent::Future.execute {
- assert_equal({"type" => "welcome"}, c.read_message) # pop the first welcome message off the stack
+ clients.map { |c| Concurrent::Future.execute {
+ assert_equal({ "type" => "welcome" }, c.read_message) # pop the first welcome message off the stack
c.send_message command: "subscribe", identifier: JSON.generate(channel: "ClientTest::EchoChannel")
- assert_equal({"identifier"=>'{"channel":"ClientTest::EchoChannel"}', "type"=>"confirm_subscription"}, c.read_message)
+ assert_equal({ "identifier"=>'{"channel":"ClientTest::EchoChannel"}', "type"=>"confirm_subscription" }, c.read_message)
c.send_message command: "message", identifier: JSON.generate(channel: "ClientTest::EchoChannel"), data: JSON.generate(action: "ding", message: "hello")
- assert_equal({"identifier"=>'{"channel":"ClientTest::EchoChannel"}', "message"=>{"dong"=>"hello"}}, c.read_message)
+ assert_equal({ "identifier"=>'{"channel":"ClientTest::EchoChannel"}', "message"=>{ "dong"=>"hello" } }, c.read_message)
barrier_1.wait WAIT_WHEN_EXPECTING_EVENT
c.send_message command: "message", identifier: JSON.generate(channel: "ClientTest::EchoChannel"), data: JSON.generate(action: "bulk", message: "hello")
barrier_2.wait WAIT_WHEN_EXPECTING_EVENT
assert_equal clients.size, c.read_messages(clients.size).size
} }.each(&:wait!)
- clients.map {|c| Concurrent::Future.execute { c.close } }.each(&:wait!)
+ clients.map { |c| Concurrent::Future.execute { c.close } }.each(&:wait!)
end
end
@@ -204,33 +204,33 @@ class ClientTest < ActionCable::TestCase
with_puma_server do |port|
clients = 100.times.map { faye_client(port) }
- clients.map {|c| Concurrent::Future.execute {
- assert_equal({"type" => "welcome"}, c.read_message) # pop the first welcome message off the stack
+ clients.map { |c| Concurrent::Future.execute {
+ assert_equal({ "type" => "welcome" }, c.read_message) # pop the first welcome message off the stack
c.send_message command: "subscribe", identifier: JSON.generate(channel: "ClientTest::EchoChannel")
- assert_equal({"identifier"=>'{"channel":"ClientTest::EchoChannel"}', "type"=>"confirm_subscription"}, c.read_message)
+ assert_equal({ "identifier"=>'{"channel":"ClientTest::EchoChannel"}', "type"=>"confirm_subscription" }, c.read_message)
c.send_message command: "message", identifier: JSON.generate(channel: "ClientTest::EchoChannel"), data: JSON.generate(action: "ding", message: "hello")
- assert_equal({"identifier"=>'{"channel":"ClientTest::EchoChannel"}', "message"=>{"dong"=>"hello"}}, c.read_message)
+ assert_equal({ "identifier"=>'{"channel":"ClientTest::EchoChannel"}', "message"=>{ "dong"=>"hello" } }, c.read_message)
} }.each(&:wait!)
- clients.map {|c| Concurrent::Future.execute { c.close } }.each(&:wait!)
+ clients.map { |c| Concurrent::Future.execute { c.close } }.each(&:wait!)
end
end
def test_disappearing_client
with_puma_server do |port|
c = faye_client(port)
- assert_equal({"type" => "welcome"}, c.read_message) # pop the first welcome message off the stack
+ assert_equal({ "type" => "welcome" }, c.read_message) # pop the first welcome message off the stack
c.send_message command: "subscribe", identifier: JSON.generate(channel: "ClientTest::EchoChannel")
- assert_equal({"identifier"=>"{\"channel\":\"ClientTest::EchoChannel\"}", "type"=>"confirm_subscription"}, c.read_message)
+ assert_equal({ "identifier"=>"{\"channel\":\"ClientTest::EchoChannel\"}", "type"=>"confirm_subscription" }, c.read_message)
c.send_message command: "message", identifier: JSON.generate(channel: "ClientTest::EchoChannel"), data: JSON.generate(action: "delay", message: "hello")
c.close # disappear before write
c = faye_client(port)
- assert_equal({"type" => "welcome"}, c.read_message) # pop the first welcome message off the stack
+ assert_equal({ "type" => "welcome" }, c.read_message) # pop the first welcome message off the stack
c.send_message command: "subscribe", identifier: JSON.generate(channel: "ClientTest::EchoChannel")
- assert_equal({"identifier"=>"{\"channel\":\"ClientTest::EchoChannel\"}", "type"=>"confirm_subscription"}, c.read_message)
+ assert_equal({ "identifier"=>"{\"channel\":\"ClientTest::EchoChannel\"}", "type"=>"confirm_subscription" }, c.read_message)
c.send_message command: "message", identifier: JSON.generate(channel: "ClientTest::EchoChannel"), data: JSON.generate(action: "ding", message: "hello")
- assert_equal({"identifier"=>'{"channel":"ClientTest::EchoChannel"}', "message"=>{"dong"=>"hello"}}, c.read_message)
+ assert_equal({ "identifier"=>'{"channel":"ClientTest::EchoChannel"}', "message"=>{ "dong"=>"hello" } }, c.read_message)
c.close # disappear before read
end
end
@@ -241,9 +241,9 @@ class ClientTest < ActionCable::TestCase
identifier = JSON.generate(channel: "ClientTest::EchoChannel")
c = faye_client(port)
- assert_equal({"type" => "welcome"}, c.read_message)
+ assert_equal({ "type" => "welcome" }, c.read_message)
c.send_message command: "subscribe", identifier: identifier
- assert_equal({"identifier"=>"{\"channel\":\"ClientTest::EchoChannel\"}", "type"=>"confirm_subscription"}, c.read_message)
+ assert_equal({ "identifier"=>"{\"channel\":\"ClientTest::EchoChannel\"}", "type"=>"confirm_subscription" }, c.read_message)
assert_equal(1, app.connections.count)
assert(app.remote_connections.where(identifier: identifier))
@@ -262,9 +262,9 @@ class ClientTest < ActionCable::TestCase
def test_server_restart
with_puma_server do |port|
c = faye_client(port)
- assert_equal({"type" => "welcome"}, c.read_message)
+ assert_equal({ "type" => "welcome" }, c.read_message)
c.send_message command: "subscribe", identifier: JSON.generate(channel: "ClientTest::EchoChannel")
- assert_equal({"identifier"=>"{\"channel\":\"ClientTest::EchoChannel\"}", "type"=>"confirm_subscription"}, c.read_message)
+ assert_equal({ "identifier"=>"{\"channel\":\"ClientTest::EchoChannel\"}", "type"=>"confirm_subscription" }, c.read_message)
ActionCable.server.restart
c.wait_for_close
diff --git a/actioncable/test/stubs/test_server.rb b/actioncable/test/stubs/test_server.rb
index 71819a43dc..b64ff33789 100644
--- a/actioncable/test/stubs/test_server.rb
+++ b/actioncable/test/stubs/test_server.rb
@@ -13,9 +13,9 @@ class TestServer
@config.use_faye = ENV["FAYE"].present?
@config.client_socket_class = if @config.use_faye
ActionCable::Connection::FayeClientSocket
- else
- ActionCable::Connection::ClientSocket
- end
+ else
+ ActionCable::Connection::ClientSocket
+ end
@mutex = Monitor.new
end
@@ -27,9 +27,9 @@ class TestServer
def event_loop
@event_loop ||= if @config.use_faye
ActionCable::Connection::FayeEventLoop.new
- else
- ActionCable::Connection::StreamEventLoop.new
- end
+ else
+ ActionCable::Connection::StreamEventLoop.new
+ end
end
def worker_pool
diff --git a/actioncable/test/subscription_adapter/common.rb b/actioncable/test/subscription_adapter/common.rb
index bf4dd701fc..1538157995 100644
--- a/actioncable/test/subscription_adapter/common.rb
+++ b/actioncable/test/subscription_adapter/common.rb
@@ -23,7 +23,6 @@ module CommonSubscriptionAdapterTest
[@rx_adapter, @tx_adapter].uniq.each(&:shutdown)
end
-
def subscribe_as_queue(channel, adapter = @rx_adapter)
queue = Queue.new
@@ -41,7 +40,6 @@ module CommonSubscriptionAdapterTest
adapter.unsubscribe(channel, callback) if subscribed.set?
end
-
def test_subscribe_and_unsubscribe
subscribe_as_queue("channel") do |queue|
end
diff --git a/actioncable/test/test_helper.rb b/actioncable/test/test_helper.rb
index 469d69adf9..39855ea252 100644
--- a/actioncable/test/test_helper.rb
+++ b/actioncable/test/test_helper.rb
@@ -11,7 +11,7 @@ rescue LoadError
end
# Require all the stubs and models
-Dir[File.dirname(__FILE__) + "/stubs/*.rb"].each {|file| require file }
+Dir[File.dirname(__FILE__) + "/stubs/*.rb"].each { |file| require file }
if ENV["FAYE"].present?
require "faye/websocket"
diff --git a/actionmailer/bin/test b/actionmailer/bin/test
index 404cabba51..84a05bba08 100755
--- a/actionmailer/bin/test
+++ b/actionmailer/bin/test
@@ -1,4 +1,6 @@
#!/usr/bin/env ruby
-COMPONENT_ROOT = File.expand_path("../../", __FILE__)
+
+COMPONENT_ROOT = File.expand_path("..", __dir__)
require File.expand_path("../tools/test", COMPONENT_ROOT)
+
exit Minitest.run(ARGV)
diff --git a/actionmailer/lib/action_mailer/inline_preview_interceptor.rb b/actionmailer/lib/action_mailer/inline_preview_interceptor.rb
index fd9a7bce15..b7318f0092 100644
--- a/actionmailer/lib/action_mailer/inline_preview_interceptor.rb
+++ b/actionmailer/lib/action_mailer/inline_preview_interceptor.rb
@@ -55,7 +55,7 @@ module ActionMailer
end
def find_part(cid)
- message.all_parts.find{ |p| p.attachment? && p.cid == cid }
+ message.all_parts.find { |p| p.attachment? && p.cid == cid }
end
end
end
diff --git a/actionmailer/lib/action_mailer/preview.rb b/actionmailer/lib/action_mailer/preview.rb
index 7612cddf22..d88ca7ace4 100644
--- a/actionmailer/lib/action_mailer/preview.rb
+++ b/actionmailer/lib/action_mailer/preview.rb
@@ -80,12 +80,12 @@ module ActionMailer
# Returns true if the preview exists.
def exists?(preview)
- all.any?{ |p| p.preview_name == preview }
+ all.any? { |p| p.preview_name == preview }
end
# Find a mailer preview by its underscored class name.
def find(preview)
- all.find{ |p| p.preview_name == preview }
+ all.find { |p| p.preview_name == preview }
end
# Returns the underscored name of the mailer preview without the suffix.
@@ -96,7 +96,7 @@ module ActionMailer
protected
def load_previews #:nodoc:
if preview_path
- Dir["#{preview_path}/**/*_preview.rb"].each{ |file| require_dependency file }
+ Dir["#{preview_path}/**/*_preview.rb"].each { |file| require_dependency file }
end
end
diff --git a/actionmailer/lib/rails/generators/mailer/mailer_generator.rb b/actionmailer/lib/rails/generators/mailer/mailer_generator.rb
index 72e53fb993..9dd7ee7a27 100644
--- a/actionmailer/lib/rails/generators/mailer/mailer_generator.rb
+++ b/actionmailer/lib/rails/generators/mailer/mailer_generator.rb
@@ -28,9 +28,9 @@ module Rails
def application_mailer_file_name
@_application_mailer_file_name ||= if mountable_engine?
"app/mailers/#{namespaced_path}/application_mailer.rb"
- else
- "app/mailers/application_mailer.rb"
- end
+ else
+ "app/mailers/application_mailer.rb"
+ end
end
end
end
diff --git a/actionmailer/test/base_test.rb b/actionmailer/test/base_test.rb
index 5b0566a131..3bca69890d 100644
--- a/actionmailer/test/base_test.rb
+++ b/actionmailer/test/base_test.rb
@@ -87,7 +87,7 @@ class BaseTest < ActiveSupport::TestCase
end
test "can pass random headers in as a hash to mail" do
- hash = {"X-Special-Domain-Specific-Header" => "SecretValue",
+ hash = { "X-Special-Domain-Specific-Header" => "SecretValue",
"In-Reply-To" => "1234@mikel.me.com" }
mail = BaseMailer.welcome(hash)
assert_equal("SecretValue", mail["X-Special-Domain-Specific-Header"].decoded)
@@ -95,7 +95,7 @@ class BaseTest < ActiveSupport::TestCase
end
test "can pass random headers in as a hash to headers" do
- hash = {"X-Special-Domain-Specific-Header" => "SecretValue",
+ hash = { "X-Special-Domain-Specific-Header" => "SecretValue",
"In-Reply-To" => "1234@mikel.me.com" }
mail = BaseMailer.welcome_with_headers(hash)
assert_equal("SecretValue", mail["X-Special-Domain-Specific-Header"].decoded)
@@ -215,7 +215,7 @@ class BaseTest < ActiveSupport::TestCase
email = BaseMailer.welcome(subject: nil)
assert_equal "Welcome", email.subject
- with_translation "en", base_mailer: {welcome: {subject: "New Subject!"}} do
+ with_translation "en", base_mailer: { welcome: { subject: "New Subject!" } } do
email = BaseMailer.welcome(subject: nil)
assert_equal "New Subject!", email.subject
end
@@ -223,14 +223,14 @@ class BaseTest < ActiveSupport::TestCase
end
test "default subject can have interpolations" do
- with_translation "en", base_mailer: {with_subject_interpolations: {subject: "Will the real %{rapper_or_impersonator} please stand up?"}} do
+ with_translation "en", base_mailer: { with_subject_interpolations: { subject: "Will the real %{rapper_or_impersonator} please stand up?" } } do
email = BaseMailer.with_subject_interpolations
assert_equal "Will the real Slim Shady please stand up?", email.subject
end
end
test "translations are scoped properly" do
- with_translation "en", base_mailer: {email_with_translations: {greet_user: "Hello %{name}!"}} do
+ with_translation "en", base_mailer: { email_with_translations: { greet_user: "Hello %{name}!" } } do
email = BaseMailer.email_with_translations
assert_equal "Hello lifo!", email.body.encoded
end
@@ -271,7 +271,7 @@ class BaseTest < ActiveSupport::TestCase
assert_nothing_raised { mail.message }
assert_equal ["image/jpeg; filename=controller_attachments.jpg",
- "image/jpeg; filename=attachments.jpg"], mail.attachments.inline.map {|a| a["Content-Type"].to_s }
+ "image/jpeg; filename=attachments.jpg"], mail.attachments.inline.map { |a| a["Content-Type"].to_s }
end
test "accessing attachments works after mail was called" do
@@ -380,7 +380,6 @@ class BaseTest < ActiveSupport::TestCase
end
end
-
test "implicit multipart with several view paths uses the first one with template" do
old = BaseMailer.view_paths
begin
@@ -773,8 +772,8 @@ class BaseTest < ActiveSupport::TestCase
test "action methods should be refreshed after defining new method" do
class FooMailer < ActionMailer::Base
- # this triggers action_methods
- self.respond_to?(:foo)
+ # This triggers action_methods.
+ respond_to?(:foo)
def notify
end
@@ -799,7 +798,7 @@ class BaseTest < ActiveSupport::TestCase
test "default_from can be set" do
class DefaultFromMailer < ActionMailer::Base
default to: "system@test.lindsaar.net"
- self.default_options = {from: "robert.pankowecki@gmail.com"}
+ self.default_options = { from: "robert.pankowecki@gmail.com" }
def welcome
mail(subject: "subject", body: "hello world")
diff --git a/actionmailer/test/caching_test.rb b/actionmailer/test/caching_test.rb
index 17267667aa..cff49c8894 100644
--- a/actionmailer/test/caching_test.rb
+++ b/actionmailer/test/caching_test.rb
@@ -172,6 +172,7 @@ class FunctionalFragmentCachingTest < BaseCachingTest
end
def test_fragment_cache_instrumentation
+ @mailer.enable_fragment_cache_logging = true
payload = nil
subscriber = proc do |*args|
@@ -185,6 +186,8 @@ class FunctionalFragmentCachingTest < BaseCachingTest
assert_equal "caching_mailer", payload[:mailer]
assert_equal "views/caching/#{template_digest("caching_mailer/fragment_cache")}", payload[:key]
+ ensure
+ @mailer.enable_fragment_cache_logging = true
end
private
@@ -223,7 +226,7 @@ class CacheHelperOutputBufferTest < BaseCachingTest
cache_helper.stub :output_buffer, output_buffer do
assert_called_with cache_helper, :output_buffer=, [output_buffer.class.new(output_buffer)] do
assert_nothing_raised do
- cache_helper.send :fragment_for, "Test fragment name", "Test fragment", &Proc.new{ nil }
+ cache_helper.send :fragment_for, "Test fragment name", "Test fragment", &Proc.new { nil }
end
end
end
@@ -244,7 +247,7 @@ class CacheHelperOutputBufferTest < BaseCachingTest
cache_helper.stub :output_buffer, output_buffer do
assert_called_with cache_helper, :output_buffer=, [output_buffer.class.new(output_buffer)] do
assert_nothing_raised do
- cache_helper.send :fragment_for, "Test fragment name", "Test fragment", &Proc.new{ nil }
+ cache_helper.send :fragment_for, "Test fragment name", "Test fragment", &Proc.new { nil }
end
end
end
diff --git a/actionmailer/test/delivery_methods_test.rb b/actionmailer/test/delivery_methods_test.rb
index a508c0aae9..898d32c1e2 100644
--- a/actionmailer/test/delivery_methods_test.rb
+++ b/actionmailer/test/delivery_methods_test.rb
@@ -32,7 +32,7 @@ class DefaultsDeliveryMethodsTest < ActiveSupport::TestCase
end
test "default file delivery settings (with Rails.root)" do
- settings = {location: "#{Rails.root}/tmp/mails"}
+ settings = { location: "#{Rails.root}/tmp/mails" }
assert_equal settings, ActionMailer::Base.file_settings
end
@@ -127,16 +127,16 @@ class MailDeliveryTest < ActiveSupport::TestCase
end
test "delivery method options default to class level options" do
- default_options = {a: "b"}
+ default_options = { a: "b" }
ActionMailer::Base.add_delivery_method :optioned, MyOptionedDelivery, default_options
mail_instance = DeliveryMailer.welcome(delivery_method: :optioned)
assert_equal default_options, mail_instance.delivery_method.options
end
test "delivery method options can be overridden per mail instance" do
- default_options = {a: "b"}
+ default_options = { a: "b" }
ActionMailer::Base.add_delivery_method :optioned, MyOptionedDelivery, default_options
- overridden_options = {a: "a"}
+ overridden_options = { a: "a" }
mail_instance = DeliveryMailer.welcome(delivery_method: :optioned, delivery_method_options: overridden_options)
assert_equal overridden_options, mail_instance.delivery_method.options
end
@@ -152,7 +152,7 @@ class MailDeliveryTest < ActiveSupport::TestCase
enable_starttls_auto: true
}
assert_equal settings, ActionMailer::Base.smtp_settings
- overridden_options = {user_name: "overridden", password: "somethingobtuse"}
+ overridden_options = { user_name: "overridden", password: "somethingobtuse" }
mail_instance = DeliveryMailer.welcome(delivery_method_options: overridden_options)
delivery_method_instance = mail_instance.delivery_method
assert_equal "overridden", delivery_method_instance.settings[:user_name]
diff --git a/actionmailer/test/mailers/base_mailer.rb b/actionmailer/test/mailers/base_mailer.rb
index fd7397be84..8ced74c214 100644
--- a/actionmailer/test/mailers/base_mailer.rb
+++ b/actionmailer/test/mailers/base_mailer.rb
@@ -7,7 +7,7 @@ class BaseMailer < ActionMailer::Base
def welcome(hash = {})
headers["X-SPAM"] = "Not SPAM"
- mail({subject: "The first email on new API!"}.merge!(hash))
+ mail({ subject: "The first email on new API!" }.merge!(hash))
end
def welcome_with_headers(hash = {})
@@ -76,7 +76,7 @@ class BaseMailer < ActionMailer::Base
def explicit_multipart_with_any(hash = {})
mail(hash) do |format|
- format.any(:text, :html){ render text: "Format with any!" }
+ format.any(:text, :html) { render text: "Format with any!" }
end
end
@@ -88,8 +88,8 @@ class BaseMailer < ActionMailer::Base
def explicit_multipart_with_options(include_html = false)
mail do |format|
- format.text(content_transfer_encoding: "base64"){ render "welcome" }
- format.html{ render "welcome" } if include_html
+ format.text(content_transfer_encoding: "base64") { render "welcome" }
+ format.html { render "welcome" } if include_html
end
end
diff --git a/actionmailer/test/url_test.rb b/actionmailer/test/url_test.rb
index 9e393c9e49..27f6e8a491 100644
--- a/actionmailer/test/url_test.rb
+++ b/actionmailer/test/url_test.rb
@@ -94,7 +94,7 @@ class ActionMailerUrlTest < ActionMailer::TestCase
# hash
assert_url_for "/a/b/c", controller: "a", action: "b", id: "c"
- assert_url_for "/a/b/c", {controller: "a", action: "b", id: "c", only_path: true}, true
+ assert_url_for "/a/b/c", { controller: "a", action: "b", id: "c", only_path: true }, true
# model
assert_url_for "/dummy_model", DummyModel.new
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md
index 7bb9b62468..1fb7e20417 100644
--- a/actionpack/CHANGELOG.md
+++ b/actionpack/CHANGELOG.md
@@ -1,7 +1,37 @@
-* Fix 'defaults' option for root route.
+* Show cache hits and misses when rendering partials.
+
+ Partials using the `cache` helper will show whether a render hit or missed
+ the cache:
+
+ ```
+ Rendered messages/_message.html.erb in 1.2 ms [cache hit]
+ Rendered recordings/threads/_thread.html.erb in 1.5 ms [cache miss]
+ ```
+
+ This removes the need for the old fragment cache logging:
+
+ ```
+ Read fragment views/v1/2914079/v1/2914079/recordings/70182313-20160225015037000000/d0bdf2974e1ef6d31685c3b392ad0b74 (0.6ms)
+ Rendered messages/_message.html.erb in 1.2 ms [cache hit]
+ Write fragment views/v1/2914079/v1/2914079/recordings/70182313-20160225015037000000/3b4e249ac9d168c617e32e84b99218b5 (1.1ms)
+ Rendered recordings/threads/_thread.html.erb in 1.5 ms [cache miss]
+ ```
+
+ Though that full output can be reenabled with
+ `config.action_controller.enable_fragment_cache_logging = true`.
+
+ *Stan Lo*
+
+* Don't override the `Accept` header in integration tests when called with `xhr: true`.
+
+ Fixes #25859.
+
+ *David Chen*
+
+* Fix `defaults` option for root route.
A regression from some refactoring for the 5.0 release, this change
- fixes the use of 'defaults' (default parameters) in the 'root' routing method.
+ fixes the use of `defaults` (default parameters) in the `root` routing method.
*Chris Arcand*
@@ -15,16 +45,16 @@
*Grey Baker*
-* Don't raise ActionController::UnknownHttpMethod from ActionDispatch::Static
+* Don't raise `ActionController::UnknownHttpMethod` from `ActionDispatch::Static`.
Pass `Rack::Request` objects to `ActionDispatch::FileHandler` to avoid it
raising `ActionController::UnknownHttpMethod`. If an unknown method is
- passed, it should exception higher in the stack instead, once we've had a
+ passed, it should pass exception higher in the stack instead, once we've had a
chance to define exception handling behaviour.
*Grey Baker*
-* Handle `Rack::QueryParser` errors in `ActionDispatch::ExceptionWrapper`
+* Handle `Rack::QueryParser` errors in `ActionDispatch::ExceptionWrapper`.
Updated `ActionDispatch::ExceptionWrapper` to handle the Rack 2.0 namespace
for `ParameterTypeError` and `InvalidParameterError` errors.
diff --git a/actionpack/bin/test b/actionpack/bin/test
index 404cabba51..84a05bba08 100755
--- a/actionpack/bin/test
+++ b/actionpack/bin/test
@@ -1,4 +1,6 @@
#!/usr/bin/env ruby
-COMPONENT_ROOT = File.expand_path("../../", __FILE__)
+
+COMPONENT_ROOT = File.expand_path("..", __dir__)
require File.expand_path("../tools/test", COMPONENT_ROOT)
+
exit Minitest.run(ARGV)
diff --git a/actionpack/lib/abstract_controller/caching.rb b/actionpack/lib/abstract_controller/caching.rb
index a37ee9ec97..d222880922 100644
--- a/actionpack/lib/abstract_controller/caching.rb
+++ b/actionpack/lib/abstract_controller/caching.rb
@@ -34,6 +34,9 @@ module AbstractController
config_accessor :perform_caching
self.perform_caching = true if perform_caching.nil?
+ config_accessor :enable_fragment_cache_logging
+ self.enable_fragment_cache_logging = false
+
class_attribute :_view_cache_dependencies
self._view_cache_dependencies = []
helper_method :view_cache_dependencies if respond_to?(:helper_method)
diff --git a/actionpack/lib/abstract_controller/caching/fragments.rb b/actionpack/lib/abstract_controller/caching/fragments.rb
index 3257a731ed..c85b4adba1 100644
--- a/actionpack/lib/abstract_controller/caching/fragments.rb
+++ b/actionpack/lib/abstract_controller/caching/fragments.rb
@@ -51,7 +51,7 @@ module AbstractController
# end
# end
def fragment_cache_key(value = nil, &key)
- self.fragment_cache_keys += [key || ->{ value }]
+ self.fragment_cache_keys += [key || -> { value }]
end
end
diff --git a/actionpack/lib/abstract_controller/callbacks.rb b/actionpack/lib/abstract_controller/callbacks.rb
index 873e88fcd5..73775e12c2 100644
--- a/actionpack/lib/abstract_controller/callbacks.rb
+++ b/actionpack/lib/abstract_controller/callbacks.rb
@@ -49,7 +49,7 @@ module AbstractController
def _normalize_callback_option(options, from, to) # :nodoc:
if from = options[from]
_from = Array(from).map(&:to_s).to_set
- from = proc {|c| _from.include? c.action_name }
+ from = proc { |c| _from.include? c.action_name }
options[to] = Array(options[to]).unshift(from)
end
end
diff --git a/actionpack/lib/abstract_controller/collector.rb b/actionpack/lib/abstract_controller/collector.rb
index 55654be224..57714b0588 100644
--- a/actionpack/lib/abstract_controller/collector.rb
+++ b/actionpack/lib/abstract_controller/collector.rb
@@ -16,7 +16,7 @@ module AbstractController
end
Mime::Type.register_callback do |mime|
- generate_method_for_mime(mime) unless self.instance_methods.include?(mime.to_sym)
+ generate_method_for_mime(mime) unless instance_methods.include?(mime.to_sym)
end
protected
diff --git a/actionpack/lib/action_controller.rb b/actionpack/lib/action_controller.rb
index b9ef11a7e0..fc86a907b3 100644
--- a/actionpack/lib/action_controller.rb
+++ b/actionpack/lib/action_controller.rb
@@ -40,6 +40,7 @@ module ActionController
autoload :Rescue
autoload :Streaming
autoload :StrongParameters
+ autoload :ParameterEncoding
autoload :Testing
autoload :UrlFor
end
diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb
index 2c7a223971..68a526eccb 100644
--- a/actionpack/lib/action_controller/base.rb
+++ b/actionpack/lib/action_controller/base.rb
@@ -217,7 +217,7 @@ module ActionController
MimeResponds,
ImplicitRender,
StrongParameters,
-
+ ParameterEncoding,
Cookies,
Flash,
FormBuilder,
diff --git a/actionpack/lib/action_controller/log_subscriber.rb b/actionpack/lib/action_controller/log_subscriber.rb
index a0917b4fdb..d29a5fe68f 100644
--- a/actionpack/lib/action_controller/log_subscriber.rb
+++ b/actionpack/lib/action_controller/log_subscriber.rb
@@ -51,7 +51,7 @@ module ActionController
def unpermitted_parameters(event)
debug do
unpermitted_keys = event.payload[:keys]
- "Unpermitted parameter#{'s' if unpermitted_keys.size > 1}: #{unpermitted_keys.join(", ")}"
+ "Unpermitted parameter#{'s' if unpermitted_keys.size > 1}: #{unpermitted_keys.map { |e| ":#{e}" }.join(", ")}"
end
end
@@ -59,7 +59,7 @@ module ActionController
expire_fragment expire_page write_page).each do |method|
class_eval <<-METHOD, __FILE__, __LINE__ + 1
def #{method}(event)
- return unless logger.info?
+ return unless logger.info? && ActionController::Base.enable_fragment_cache_logging
key_or_path = event.payload[:key] || event.payload[:path]
human_name = #{method.to_s.humanize.inspect}
info("\#{human_name} \#{key_or_path} (\#{event.duration.round(1)}ms)")
diff --git a/actionpack/lib/action_controller/metal.rb b/actionpack/lib/action_controller/metal.rb
index 0364500944..075e4504c2 100644
--- a/actionpack/lib/action_controller/metal.rb
+++ b/actionpack/lib/action_controller/metal.rb
@@ -139,6 +139,10 @@ module ActionController
end
end
+ def self.encoding_for_param(action, param) # :nodoc:
+ ::Encoding::UTF_8
+ end
+
# Delegates to the class' <tt>controller_name</tt>
def controller_name
self.class.controller_name
diff --git a/actionpack/lib/action_controller/metal/conditional_get.rb b/actionpack/lib/action_controller/metal/conditional_get.rb
index eee17082b7..a26ebd2b24 100644
--- a/actionpack/lib/action_controller/metal/conditional_get.rb
+++ b/actionpack/lib/action_controller/metal/conditional_get.rb
@@ -238,7 +238,7 @@ module ActionController
)
options.delete(:private)
- response.cache_control[:extras] = options.map {|k,v| "#{k}=#{v}"}
+ response.cache_control[:extras] = options.map { |k,v| "#{k}=#{v}" }
response.date = Time.now unless response.date?
end
diff --git a/actionpack/lib/action_controller/metal/head.rb b/actionpack/lib/action_controller/metal/head.rb
index 97306b5265..86b5eb20d7 100644
--- a/actionpack/lib/action_controller/metal/head.rb
+++ b/actionpack/lib/action_controller/metal/head.rb
@@ -41,7 +41,7 @@ module ActionController
self.response_body = ""
- if include_content?(self.response_code)
+ if include_content?(response_code)
self.content_type = content_type || (Mime[formats.first] if formats)
self.response.charset = false
end
diff --git a/actionpack/lib/action_controller/metal/http_authentication.rb b/actionpack/lib/action_controller/metal/http_authentication.rb
index 22aadb9dfa..a335bf109e 100644
--- a/actionpack/lib/action_controller/metal/http_authentication.rb
+++ b/actionpack/lib/action_controller/metal/http_authentication.rb
@@ -236,7 +236,7 @@ module ActionController
def encode_credentials(http_method, credentials, password, password_is_ha1)
credentials[:response] = expected_response(http_method, credentials[:uri], credentials, password, password_is_ha1)
- "Digest " + credentials.sort_by {|x| x[0].to_s }.map {|v| "#{v[0]}='#{v[1]}'" }.join(", ")
+ "Digest " + credentials.sort_by { |x| x[0].to_s }.map { |v| "#{v[0]}='#{v[1]}'" }.join(", ")
end
def decode_credentials_header(request)
diff --git a/actionpack/lib/action_controller/metal/implicit_render.rb b/actionpack/lib/action_controller/metal/implicit_render.rb
index 9332da5721..c414527d63 100644
--- a/actionpack/lib/action_controller/metal/implicit_render.rb
+++ b/actionpack/lib/action_controller/metal/implicit_render.rb
@@ -61,7 +61,7 @@ module ActionController
def method_for_action(action_name)
super || if template_exists?(action_name.to_s, _prefixes)
- "default_render"
+ "default_render"
end
end
diff --git a/actionpack/lib/action_controller/metal/instrumentation.rb b/actionpack/lib/action_controller/metal/instrumentation.rb
index 6a8129e88b..2ede96c667 100644
--- a/actionpack/lib/action_controller/metal/instrumentation.rb
+++ b/actionpack/lib/action_controller/metal/instrumentation.rb
@@ -17,7 +17,7 @@ module ActionController
def process_action(*args)
raw_payload = {
controller: self.class.name,
- action: self.action_name,
+ action: action_name,
params: request.filtered_parameters,
headers: request.headers,
format: request.format.ref,
diff --git a/actionpack/lib/action_controller/metal/live.rb b/actionpack/lib/action_controller/metal/live.rb
index a18055c899..26a16104db 100644
--- a/actionpack/lib/action_controller/metal/live.rb
+++ b/actionpack/lib/action_controller/metal/live.rb
@@ -205,7 +205,12 @@ module ActionController
private
def each_chunk(&block)
- while str = @buf.pop
+ loop do
+ str = nil
+ ActiveSupport::Dependencies.interlock.permit_concurrent_loads do
+ str = @buf.pop
+ end
+ break unless str
yield str
end
end
diff --git a/actionpack/lib/action_controller/metal/mime_responds.rb b/actionpack/lib/action_controller/metal/mime_responds.rb
index 0d998632fc..f6aabcb102 100644
--- a/actionpack/lib/action_controller/metal/mime_responds.rb
+++ b/actionpack/lib/action_controller/metal/mime_responds.rb
@@ -280,8 +280,8 @@ module ActionController #:nodoc:
def any(*args, &block)
if block_given?
- if args.any? && args.none?{ |a| a == @variant }
- args.each{ |v| @variants[v] = block }
+ if args.any? && args.none? { |a| a == @variant }
+ args.each { |v| @variants[v] = block }
else
@variants[:any] = block
end
diff --git a/actionpack/lib/action_controller/metal/parameter_encoding.rb b/actionpack/lib/action_controller/metal/parameter_encoding.rb
new file mode 100644
index 0000000000..c457fd0d06
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/parameter_encoding.rb
@@ -0,0 +1,30 @@
+module ActionController
+ # Allows encoding to be specified per parameter per action.
+ module ParameterEncoding
+ extend ActiveSupport::Concern
+
+ module ClassMethods
+ def inherited(klass) # :nodoc:
+ super
+ klass.setup_param_encode
+ end
+
+ def setup_param_encode # :nodoc:
+ @_parameter_encodings = {}
+ end
+
+ def encoding_for_param(action, param) # :nodoc:
+ if @_parameter_encodings[action.to_s] && @_parameter_encodings[action.to_s][param.to_s]
+ @_parameter_encodings[action.to_s][param.to_s]
+ else
+ super
+ end
+ end
+
+ def parameter_encoding(action, param_name, encoding)
+ @_parameter_encodings[action.to_s] ||= {}
+ @_parameter_encodings[action.to_s][param_name.to_s] = encoding
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/rendering.rb b/actionpack/lib/action_controller/metal/rendering.rb
index 41b166b346..ac17d61b96 100644
--- a/actionpack/lib/action_controller/metal/rendering.rb
+++ b/actionpack/lib/action_controller/metal/rendering.rb
@@ -32,7 +32,7 @@ module ActionController
# Check for double render errors and set the content_type after rendering.
def render(*args) #:nodoc:
- raise ::AbstractController::DoubleRenderError if self.response_body
+ raise ::AbstractController::DoubleRenderError if response_body
super
end
diff --git a/actionpack/lib/action_controller/metal/strong_parameters.rb b/actionpack/lib/action_controller/metal/strong_parameters.rb
index 32ab8ca2ac..d62e01d185 100644
--- a/actionpack/lib/action_controller/metal/strong_parameters.rb
+++ b/actionpack/lib/action_controller/metal/strong_parameters.rb
@@ -32,13 +32,13 @@ module ActionController
#
# params = ActionController::Parameters.new(a: "123", b: "456")
# params.permit(:c)
- # # => ActionController::UnpermittedParameters: found unpermitted parameters: a, b
+ # # => ActionController::UnpermittedParameters: found unpermitted parameters: :a, :b
class UnpermittedParameters < IndexError
attr_reader :params # :nodoc:
def initialize(params) # :nodoc:
@params = params
- super("found unpermitted parameter#{'s' if params.size > 1 }: #{params.join(", ")}")
+ super("found unpermitted parameter#{'s' if params.size > 1 }: #{params.map { |e| ":#{e}" }.join(", ")}")
end
end
@@ -719,7 +719,7 @@ module ActionController
end
def unpermitted_keys(params)
- self.keys - params.keys - self.always_permitted_parameters
+ keys - params.keys - always_permitted_parameters
end
#
@@ -750,7 +750,7 @@ module ActionController
]
def permitted_scalar?(value)
- PERMITTED_SCALAR_TYPES.any? {|type| value.is_a?(type)}
+ PERMITTED_SCALAR_TYPES.any? { |type| value.is_a?(type) }
end
def permitted_scalar_filter(params, key)
@@ -766,7 +766,7 @@ module ActionController
end
def array_of_permitted_scalars?(value)
- if value.is_a?(Array) && value.all? {|element| permitted_scalar?(element)}
+ if value.is_a?(Array) && value.all? { |element| permitted_scalar?(element) }
yield value
end
end
diff --git a/actionpack/lib/action_controller/metal/testing.rb b/actionpack/lib/action_controller/metal/testing.rb
index ac37b00010..9bb416178a 100644
--- a/actionpack/lib/action_controller/metal/testing.rb
+++ b/actionpack/lib/action_controller/metal/testing.rb
@@ -13,7 +13,7 @@ module ActionController
module ClassMethods
def before_filters
- _process_action_callbacks.find_all{|x| x.kind == :before}.map(&:name)
+ _process_action_callbacks.find_all { |x| x.kind == :before }.map(&:name)
end
end
end
diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb
index 19bd18e110..83c32136dd 100644
--- a/actionpack/lib/action_controller/test_case.rb
+++ b/actionpack/lib/action_controller/test_case.rb
@@ -7,7 +7,6 @@ require "action_controller/template_assertions"
require "rails-dom-testing"
module ActionController
- # :stopdoc:
class Metal
include Testing::Functional
end
@@ -33,12 +32,14 @@ module ActionController
TestSession.new
end
+ attr_reader :controller_class
+
# Create a new test request with default `env` values
- def self.create
+ def self.create(controller_class)
env = {}
env = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application
env["rack.request.cookie_hash"] = {}.with_indifferent_access
- new(default_env.merge(env), new_session)
+ new(default_env.merge(env), new_session, controller_class)
end
def self.default_env
@@ -46,11 +47,12 @@ module ActionController
end
private_class_method :default_env
- def initialize(env, session)
+ def initialize(env, session, controller_class)
super(env)
self.session = session
self.session_options = TestSession::DEFAULT_OPTIONS
+ @controller_class = controller_class
@custom_param_parsers = {
xml: lambda { |raw_post| Hash.from_xml(raw_post)["hash"] }
}
@@ -83,7 +85,7 @@ module ActionController
end
if get?
- if self.query_string.blank?
+ if query_string.blank?
self.query_string = non_path_parameters.to_query
end
else
@@ -208,10 +210,18 @@ module ActionController
end
# Superclass for ActionController functional tests. Functional tests allow you to
- # test a single controller action per test method. This should not be confused with
- # integration tests (see ActionDispatch::IntegrationTest), which are more like
- # "stories" that can involve multiple controllers and multiple actions (i.e. multiple
- # different HTTP requests).
+ # test a single controller action per test method.
+ #
+ # == Use integration style controller tests over functional style controller tests.
+ #
+ # Rails discourages the use of functional tests in favor of integration tests
+ # (use ActionDispatch::IntegrationTest).
+ #
+ # New Rails applications no longer generate functional style controller tests and they should
+ # only be used for backward compatibility. Integration style controller tests perform actual
+ # requests, whereas functional style controller tests merely simulate a request. Besides,
+ # integration tests are as fast as functional tests and provide lot of helpers such as +as+,
+ # +parsed_body+ for effective testing of controller actions including even API endpoints.
#
# == Basic example
#
@@ -492,12 +502,12 @@ module ActionController
@html_document = nil
- self.cookies.update @request.cookies
- self.cookies.update_cookies_from_jar
+ cookies.update(@request.cookies)
+ cookies.update_cookies_from_jar
@request.set_header "HTTP_COOKIE", cookies.to_header
@request.delete_header "action_dispatch.cookies"
- @request = TestRequest.new scrub_env!(@request.env), @request.session
+ @request = TestRequest.new scrub_env!(@request.env), @request.session, @controller.class
@response = build_response @response_klass
@response.request = @request
@controller.recycle!
@@ -538,7 +548,7 @@ module ActionController
if @request.have_cookie_jar?
unless @request.cookie_jar.committed?
@request.cookie_jar.write(@response)
- self.cookies.update(@request.cookie_jar.instance_variable_get(:@cookies))
+ cookies.update(@request.cookie_jar.instance_variable_get(:@cookies))
end
end
@response.prepare!
@@ -591,7 +601,7 @@ module ActionController
end
end
- @request = TestRequest.create
+ @request = TestRequest.create(@controller.class)
@response = build_response @response_klass
@response.request = @request
@@ -668,14 +678,8 @@ module ActionController
end
end
end
-
- def html_format?(parameters)
- return true unless parameters.key?(:format)
- Mime.fetch(parameters[:format]) { Mime["html"] }.html?
- end
end
include Behavior
end
- # :startdoc:
end
diff --git a/actionpack/lib/action_dispatch/http/headers.rb b/actionpack/lib/action_dispatch/http/headers.rb
index 91c45767ef..d5eef2987d 100644
--- a/actionpack/lib/action_dispatch/http/headers.rb
+++ b/actionpack/lib/action_dispatch/http/headers.rb
@@ -3,7 +3,7 @@ module ActionDispatch
# Provides access to the request's HTTP headers from the environment.
#
# env = { "CONTENT_TYPE" => "text/plain", "HTTP_USER_AGENT" => "curl/7.43.0" }
- # headers = ActionDispatch::Http::Headers.new(env)
+ # headers = ActionDispatch::Http::Headers.from_hash(env)
# headers["Content-Type"] # => "text/plain"
# headers["User-Agent"] # => "curl/7.43.0"
#
diff --git a/actionpack/lib/action_dispatch/http/parameters.rb b/actionpack/lib/action_dispatch/http/parameters.rb
index f25e50f9f3..31ef0af791 100644
--- a/actionpack/lib/action_dispatch/http/parameters.rb
+++ b/actionpack/lib/action_dispatch/http/parameters.rb
@@ -8,7 +8,7 @@ module ActionDispatch
DEFAULT_PARSERS = {
Mime[:json].symbol => -> (raw_post) {
data = ActiveSupport::JSON.decode(raw_post)
- data.is_a?(Hash) ? data : {_json: data}
+ data.is_a?(Hash) ? data : { _json: data }
}
}
@@ -37,6 +37,7 @@ module ActionDispatch
query_parameters.dup
end
params.merge!(path_parameters)
+ params = set_custom_encoding(params)
set_header("action_dispatch.request.parameters", params)
params
end
@@ -64,6 +65,21 @@ module ActionDispatch
private
+ def set_custom_encoding(params)
+ action = params[:action]
+ params.each do |k, v|
+ if v.is_a?(String) && v.encoding != encoding_template(action, k)
+ params[k] = v.force_encoding(encoding_template(action, k))
+ end
+ end
+
+ params
+ end
+
+ def encoding_template(action, param)
+ controller_class.encoding_for_param(action, param)
+ end
+
def parse_formatted_parameters(parsers)
return yield if content_length.zero? || content_mime_type.nil?
diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb
index 46409a325e..e4ef9783f3 100644
--- a/actionpack/lib/action_dispatch/http/request.rb
+++ b/actionpack/lib/action_dispatch/http/request.rb
@@ -68,7 +68,8 @@ module ActionDispatch
PASS_NOT_FOUND = Class.new { # :nodoc:
def self.action(_); self; end
- def self.call(_); [404, {"X-Cascade" => "pass"}, []]; end
+ def self.call(_); [404, { "X-Cascade" => "pass" }, []]; end
+ def self.encoding_for_param(action, param); ::Encoding::UTF_8; end
}
def controller_class
diff --git a/actionpack/lib/action_dispatch/journey/formatter.rb b/actionpack/lib/action_dispatch/journey/formatter.rb
index d3d79f8750..a289c34e8b 100644
--- a/actionpack/lib/action_dispatch/journey/formatter.rb
+++ b/actionpack/lib/action_dispatch/journey/formatter.rb
@@ -44,7 +44,7 @@ module ActionDispatch
return [route.format(parameterized_parts), params]
end
- message = "No route matches #{Hash[constraints.sort_by{|k,v| k.to_s}].inspect}"
+ message = "No route matches #{Hash[constraints.sort_by { |k,v| k.to_s }].inspect}"
message << " missing required keys: #{missing_keys.sort.inspect}" if missing_keys && !missing_keys.empty?
raise ActionController::UrlGenerationError, message
diff --git a/actionpack/lib/action_dispatch/journey/parser.rb b/actionpack/lib/action_dispatch/journey/parser.rb
index 38984edd3b..7ec9d63859 100644
--- a/actionpack/lib/action_dispatch/journey/parser.rb
+++ b/actionpack/lib/action_dispatch/journey/parser.rb
@@ -6,7 +6,6 @@
require "racc/parser.rb"
-
require "action_dispatch/journey/parser_extras"
module ActionDispatch
module Journey
@@ -193,5 +192,5 @@ module ActionDispatch
val[0]
end
end # class Parser
- end # module Journey
- end # module ActionDispatch
+ end # module Journey
+end # module ActionDispatch
diff --git a/actionpack/lib/action_dispatch/journey/router.rb b/actionpack/lib/action_dispatch/journey/router.rb
index 727763c972..d0ef549335 100644
--- a/actionpack/lib/action_dispatch/journey/router.rb
+++ b/actionpack/lib/action_dispatch/journey/router.rb
@@ -48,7 +48,7 @@ module ActionDispatch
return [status, headers, body]
end
- return [404, {"X-Cascade" => "pass"}, ["Not Found"]]
+ return [404, { "X-Cascade" => "pass" }, ["Not Found"]]
end
def recognize(rails_req)
@@ -72,7 +72,9 @@ module ActionDispatch
private
def partitioned_routes
- routes.partitioned_routes
+ routes.partition { |r|
+ r.path.anchored && r.ast.grep(Nodes::Symbol).all? { |n| n.default_regexp? }
+ }
end
def ast
diff --git a/actionpack/lib/action_dispatch/journey/router/utils.rb b/actionpack/lib/action_dispatch/journey/router/utils.rb
index e72db2e8f6..ce5d350763 100644
--- a/actionpack/lib/action_dispatch/journey/router/utils.rb
+++ b/actionpack/lib/action_dispatch/journey/router/utils.rb
@@ -28,7 +28,7 @@ module ActionDispatch
US_ASCII = Encoding::US_ASCII
UTF_8 = Encoding::UTF_8
EMPTY = "".force_encoding(US_ASCII).freeze
- DEC2HEX = (0..255).to_a.map{ |i| ENCODE % i }.map{ |s| s.force_encoding(US_ASCII) }
+ DEC2HEX = (0..255).to_a.map { |i| ENCODE % i }.map { |s| s.force_encoding(US_ASCII) }
ALPHA = "a-zA-Z".freeze
DIGIT = "0-9".freeze
@@ -60,7 +60,7 @@ module ActionDispatch
protected
def escape(component, pattern)
- component.gsub(pattern){ |unsafe| percent_encode(unsafe) }.force_encoding(US_ASCII)
+ component.gsub(pattern) { |unsafe| percent_encode(unsafe) }.force_encoding(US_ASCII)
end
def percent_encode(unsafe)
diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb
index bebf220488..ff83c4beca 100644
--- a/actionpack/lib/action_dispatch/middleware/cookies.rb
+++ b/actionpack/lib/action_dispatch/middleware/cookies.rb
@@ -355,7 +355,7 @@ module ActionDispatch
end
elsif options[:domain].is_a? Array
# if host matches one of the supplied domains without a dot in front of it
- options[:domain] = options[:domain].find {|domain| request.host.include? domain.sub(/^\./, "") }
+ options[:domain] = options[:domain].find { |domain| request.host.include? domain.sub(/^\./, "") }
end
end
@@ -406,7 +406,7 @@ module ActionDispatch
# Removes all cookies on the client machine by calling <tt>delete</tt> for each cookie
def clear(options = {})
- @cookies.each_key{ |k| delete(k, options) }
+ @cookies.each_key { |k| delete(k, options) }
end
def write(headers)
diff --git a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
index d585e7042e..ee644f41c8 100644
--- a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
+++ b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
@@ -151,7 +151,7 @@ module ActionDispatch
end
def render(status, body, format)
- [status, {"Content-Type" => "#{format}; charset=#{Response.default_charset}", "Content-Length" => body.bytesize.to_s}, [body]]
+ [status, { "Content-Type" => "#{format}; charset=#{Response.default_charset}", "Content-Length" => body.bytesize.to_s }, [body]]
end
def log_error(request, wrapper)
diff --git a/actionpack/lib/action_dispatch/middleware/debug_locks.rb b/actionpack/lib/action_dispatch/middleware/debug_locks.rb
index 91c2fbac01..74b952528e 100644
--- a/actionpack/lib/action_dispatch/middleware/debug_locks.rb
+++ b/actionpack/lib/action_dispatch/middleware/debug_locks.rb
@@ -86,11 +86,11 @@ module ActionDispatch
end
blockers = threads.values.select { |binfo| blocked_by?(info, binfo, threads.values) }
- msg << " blocked by: #{blockers.map {|i| i[:index] }.join(', ')}\n" if blockers.any?
+ msg << " blocked by: #{blockers.map { |i| i[:index] }.join(', ')}\n" if blockers.any?
end
blockees = threads.values.select { |binfo| blocked_by?(binfo, info, threads.values) }
- msg << " blocking: #{blockees.map {|i| i[:index] }.join(', ')}\n" if blockees.any?
+ msg << " blocking: #{blockees.map { |i| i[:index] }.join(', ')}\n" if blockees.any?
msg << "\n#{info[:backtrace].join("\n")}\n" if info[:backtrace]
end.join("\n\n---\n\n\n")
diff --git a/actionpack/lib/action_dispatch/middleware/public_exceptions.rb b/actionpack/lib/action_dispatch/middleware/public_exceptions.rb
index e3555ce638..46f0f675b9 100644
--- a/actionpack/lib/action_dispatch/middleware/public_exceptions.rb
+++ b/actionpack/lib/action_dispatch/middleware/public_exceptions.rb
@@ -37,8 +37,8 @@ module ActionDispatch
end
def render_format(status, content_type, body)
- [status, {"Content-Type" => "#{content_type}; charset=#{ActionDispatch::Response.default_charset}",
- "Content-Length" => body.bytesize.to_s}, [body]]
+ [status, { "Content-Type" => "#{content_type}; charset=#{ActionDispatch::Response.default_charset}",
+ "Content-Length" => body.bytesize.to_s }, [body]]
end
def render_html(status)
diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
index 5aff130bc3..90f26a1c33 100644
--- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
+++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
@@ -54,7 +54,7 @@ module ActionDispatch
end
def pass_response(status)
- [status, {"Content-Type" => "text/html; charset=#{Response.default_charset}", "Content-Length" => "0"}, []]
+ [status, { "Content-Type" => "text/html; charset=#{Response.default_charset}", "Content-Length" => "0" }, []]
end
end
end
diff --git a/actionpack/lib/action_dispatch/railtie.rb b/actionpack/lib/action_dispatch/railtie.rb
index ea948076fa..48cc91bbfa 100644
--- a/actionpack/lib/action_dispatch/railtie.rb
+++ b/actionpack/lib/action_dispatch/railtie.rb
@@ -8,8 +8,8 @@ module ActionDispatch
config.action_dispatch.show_exceptions = true
config.action_dispatch.tld_length = 1
config.action_dispatch.ignore_accept_header = false
- config.action_dispatch.rescue_templates = { }
- config.action_dispatch.rescue_responses = { }
+ config.action_dispatch.rescue_templates = {}
+ config.action_dispatch.rescue_responses = {}
config.action_dispatch.default_charset = nil
config.action_dispatch.rack_cache = false
config.action_dispatch.http_auth_salt = "http authentication"
diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb
index a6b177480d..3f4f920a87 100644
--- a/actionpack/lib/action_dispatch/routing/mapper.rb
+++ b/actionpack/lib/action_dispatch/routing/mapper.rb
@@ -41,7 +41,7 @@ module ActionDispatch
end
def serve(req)
- return [ 404, {"X-Cascade" => "pass"}, [] ] unless matches?(req)
+ return [ 404, { "X-Cascade" => "pass" }, [] ] unless matches?(req)
@strategy.call @app, req
end
@@ -270,7 +270,7 @@ module ActionDispatch
{ requirements: { format: Regexp.compile(formatted) },
defaults: { format: formatted } }
else
- { requirements: { }, defaults: { } }
+ { requirements: {}, defaults: {} }
end
end
@@ -1685,9 +1685,9 @@ to this:
as = if !options.fetch(:as, true) # if it's set to nil or false
options.delete(:as)
- else
- name_for_action(options.delete(:as), action)
- end
+ else
+ name_for_action(options.delete(:as), action)
+ end
path = Mapping.normalize_path URI.parser.escape(path), formatted
ast = Journey::Parser.parse path
diff --git a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
index 3e2b21ac72..4f1aaeefc8 100644
--- a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
+++ b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
@@ -134,7 +134,6 @@ module ActionDispatch
opts
end
-
%w(edit new).each do |action|
module_eval <<-EOT, __FILE__, __LINE__ + 1
def #{action}_polymorphic_url(record_or_hash, options = {})
@@ -211,7 +210,6 @@ module ActionDispatch
method, args = builder.handle_model record_or_hash_or_array
end
-
if options.empty?
recipient.send(method, *args)
else
@@ -250,9 +248,9 @@ module ActionDispatch
named_route = if model.persisted?
args << model
get_method_for_string model.model_name.singular_route_key
- else
- get_method_for_class model
- end
+ else
+ get_method_for_class model
+ end
[named_route, args]
end
diff --git a/actionpack/lib/action_dispatch/routing/redirection.rb b/actionpack/lib/action_dispatch/routing/redirection.rb
index abb51ce357..87bcceccc0 100644
--- a/actionpack/lib/action_dispatch/routing/redirection.rb
+++ b/actionpack/lib/action_dispatch/routing/redirection.rb
@@ -61,15 +61,15 @@ module ActionDispatch
end
def escape(params)
- Hash[params.map{ |k,v| [k, Rack::Utils.escape(v)] }]
+ Hash[params.map { |k,v| [k, Rack::Utils.escape(v)] }]
end
def escape_fragment(params)
- Hash[params.map{ |k,v| [k, Journey::Router::Utils.escape_fragment(v)] }]
+ Hash[params.map { |k,v| [k, Journey::Router::Utils.escape_fragment(v)] }]
end
def escape_path(params)
- Hash[params.map{ |k,v| [k, Journey::Router::Utils.escape_path(v)] }]
+ Hash[params.map { |k,v| [k, Journey::Router::Utils.escape_path(v)] }]
end
end
@@ -128,7 +128,7 @@ module ActionDispatch
end
def inspect
- "redirect(#{status}, #{options.map{ |k,v| "#{k}: #{v}" }.join(', ')})"
+ "redirect(#{status}, #{options.map { |k,v| "#{k}: #{v}" }.join(', ')})"
end
end
diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb
index b9eda039a1..112a38b868 100644
--- a/actionpack/lib/action_dispatch/routing/route_set.rb
+++ b/actionpack/lib/action_dispatch/routing/route_set.rb
@@ -34,7 +34,7 @@ module ActionDispatch
if @raise_on_name_error
raise
else
- return [404, {"X-Cascade" => "pass"}, []]
+ return [404, { "X-Cascade" => "pass" }, []]
end
end
@@ -208,7 +208,7 @@ module ActionDispatch
params = parameterize_args(args) { |missing_key|
missing_keys << missing_key
}
- constraints = Hash[@route.requirements.merge(params).sort_by{|k,v| k.to_s}]
+ constraints = Hash[@route.requirements.merge(params).sort_by { |k,v| k.to_s }]
message = "No route matches #{constraints.inspect}"
message << " missing required keys: #{missing_keys.sort.inspect}"
diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb
index cba67b2839..e53bc6af12 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb
@@ -127,7 +127,7 @@ module ActionDispatch
options[:controller] = "/#{controller}"
end
- generate_options = options.dup.delete_if{ |k, _| defaults.key?(k) }
+ generate_options = options.dup.delete_if { |k, _| defaults.key?(k) }
assert_generates(path.is_a?(Hash) ? path[:path] : path, generate_options, defaults, extras, message)
end
@@ -184,7 +184,7 @@ module ActionDispatch
end
# Assume given controller
- request = ActionController::TestRequest.create
+ request = ActionController::TestRequest.create @controller.class
if path =~ %r{://}
fail_on(URI::InvalidURIError, msg) do
diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb
index 3008d10992..13f7fc6fa6 100644
--- a/actionpack/lib/action_dispatch/testing/integration.rb
+++ b/actionpack/lib/action_dispatch/testing/integration.rb
@@ -366,14 +366,17 @@ module ActionDispatch
"HTTP_ACCEPT" => accept
}
+ wrapped_headers = Http::Headers.from_hash({})
+ wrapped_headers.merge!(headers) if headers
+
if xhr
- headers["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest"
- headers["HTTP_ACCEPT"] ||= [Mime[:js], Mime[:html], Mime[:xml], "text/xml", "*/*"].join(", ")
+ wrapped_headers["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest"
+ wrapped_headers["HTTP_ACCEPT"] ||= [Mime[:js], Mime[:html], Mime[:xml], "text/xml", "*/*"].join(", ")
end
# this modifies the passed request_env directly
- if headers.present?
- Http::Headers.from_hash(request_env).merge!(headers)
+ if wrapped_headers.present?
+ Http::Headers.from_hash(request_env).merge!(wrapped_headers)
end
if env.present?
Http::Headers.from_hash(request_env).merge!(env)
@@ -664,38 +667,42 @@ module ActionDispatch
# end
# end
#
+ # See the {request helpers documentation}[rdoc-ref:ActionDispatch::Integration::RequestHelpers] for help on how to
+ # use +get+, etc.
+ #
+ # === Changing the request encoding
+ #
# You can also test your JSON API easily by setting what the request should
# be encoded as:
#
- # require 'test_helper'
+ # require "test_helper"
#
# class ApiTest < ActionDispatch::IntegrationTest
- # test 'creates articles' do
+ # test "creates articles" do
# assert_difference -> { Article.count } do
- # post articles_path, params: { article: { title: 'Ahoy!' } }, as: :json
+ # post articles_path, params: { article: { title: "Ahoy!" } }, as: :json
# end
#
# assert_response :success
- # assert_equal({ id: Arcticle.last.id, title: 'Ahoy!' }, response.parsed_body)
+ # assert_equal({ id: Arcticle.last.id, title: "Ahoy!" }, response.parsed_body)
# end
# end
#
- # The `as` option sets the format to JSON, sets the content type to
- # 'application/json' and encodes the parameters as JSON.
+ # The +as+ option sets the format to JSON, sets the content type to
+ # "application/json" and encodes the parameters as JSON.
#
- # Calling `parsed_body` on the response parses the response body as what
- # the last request was encoded as. If the request wasn't encoded `as` something,
- # it's the same as calling `body`.
+ # Calling +parsed_body+ on the response parses the response body based on the
+ # last response MIME type.
#
- # For any custom MIME Types you've registered, you can even add your own encoders with:
+ # For any custom MIME types you've registered, you can even add your own encoders with:
#
# ActionDispatch::IntegrationTest.register_encoder :wibble,
# param_encoder: -> params { params.to_wibble },
# response_parser: -> body { body }
#
- # Where `param_encoder` defines how the params should be encoded and
- # `response_parser` defines how the response body should be parsed through
- # `parsed_body`.
+ # Where +param_encoder+ defines how the params should be encoded and
+ # +response_parser+ defines how the response body should be parsed through
+ # +parsed_body+.
#
# Consult the Rails Testing Guide for more.
diff --git a/actionpack/test/abstract/translation_test.rb b/actionpack/test/abstract/translation_test.rb
index 1e17cb9777..0c4071df8d 100644
--- a/actionpack/test/abstract/translation_test.rb
+++ b/actionpack/test/abstract/translation_test.rb
@@ -9,7 +9,8 @@ module AbstractController
class TranslationControllerTest < ActiveSupport::TestCase
def setup
@controller = TranslationController.new
- I18n.backend.store_translations(:en, one: {
+ I18n.backend.store_translations(:en,
+ one: {
two: "bar",
},
abstract_controller: {
diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb
index 367eb90831..c5b2493e06 100644
--- a/actionpack/test/abstract_unit.rb
+++ b/actionpack/test/abstract_unit.rb
@@ -122,27 +122,19 @@ class ActionDispatch::IntegrationTest < ActiveSupport::TestCase
# Stub Rails dispatcher so it does not get controller references and
# simply return the controller#action as Rack::Body.
class NullController < ::ActionController::Metal
- def initialize(controller_name)
- @controller = controller_name
- end
-
- def make_response!(request)
- self.class.make_response! request
- end
-
- def dispatch(action, req, res)
- [200, {"Content-Type" => "text/html"}, ["#{@controller}##{action}"]]
+ def self.dispatch(action, req, res)
+ [200, { "Content-Type" => "text/html" }, ["#{req.params[:controller]}##{action}"]]
end
end
- class NullControllerRequest < DelegateClass(ActionDispatch::Request)
+ class NullControllerRequest < ActionDispatch::Request
def controller_class
- NullController.new params[:controller]
+ NullController
end
end
def make_request(env)
- NullControllerRequest.new super
+ NullControllerRequest.new env
end
end
@@ -159,7 +151,7 @@ class ActionDispatch::IntegrationTest < ActiveSupport::TestCase
yield temporary_routes
ensure
self.class.app = old_app
- self.remove!
+ remove!
silence_warnings { Object.const_set(:SharedTestRoutes, old_routes) }
end
@@ -172,7 +164,7 @@ class ActionDispatch::IntegrationTest < ActiveSupport::TestCase
ActiveSupport::Dependencies.autoload_paths << path
yield
ensure
- ActiveSupport::Dependencies.autoload_paths.reject! {|p| p == path}
+ ActiveSupport::Dependencies.autoload_paths.reject! { |p| p == path }
ActiveSupport::Dependencies.clear
end
end
@@ -247,7 +239,6 @@ module ActionController
end
end
-
class ::ApplicationController < ActionController::Base
end
@@ -268,9 +259,9 @@ module ActionDispatch
host = uri_or_host.host unless path
path ||= uri_or_host.path
- params = {"PATH_INFO" => path,
+ params = { "PATH_INFO" => path,
"REQUEST_METHOD" => method,
- "HTTP_HOST" => host}
+ "HTTP_HOST" => host }
routes.call(params)
end
diff --git a/actionpack/test/controller/action_pack_assertions_test.rb b/actionpack/test/controller/action_pack_assertions_test.rb
index 55b4c1e6a6..b08f1f1707 100644
--- a/actionpack/test/controller/action_pack_assertions_test.rb
+++ b/actionpack/test/controller/action_pack_assertions_test.rb
@@ -165,7 +165,7 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase
def test_string_constraint
with_routing do |set|
set.draw do
- get "photos", to: "action_pack_assertions#nothing", constraints: {subdomain: "admin"}
+ get "photos", to: "action_pack_assertions#nothing", constraints: { subdomain: "admin" }
end
end
end
diff --git a/actionpack/test/controller/api/params_wrapper_test.rb b/actionpack/test/controller/api/params_wrapper_test.rb
index cdf5acecae..a1da852040 100644
--- a/actionpack/test/controller/api/params_wrapper_test.rb
+++ b/actionpack/test/controller/api/params_wrapper_test.rb
@@ -20,7 +20,7 @@ class ParamsWrapperForApiTest < ActionController::TestCase
@request.env["CONTENT_TYPE"] = "application/json"
post :test, params: { "username" => "sikachu" }
- expected = { "username" => "sikachu", "person" => { "username" => "sikachu" }}
+ expected = { "username" => "sikachu", "person" => { "username" => "sikachu" } }
assert_equal expected, @controller.last_parameters
end
end
diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb
index 97d77706d1..18490c7d73 100644
--- a/actionpack/test/controller/caching_test.rb
+++ b/actionpack/test/controller/caching_test.rb
@@ -49,7 +49,7 @@ class FragmentCachingTest < ActionController::TestCase
@controller = FragmentCachingTestController.new
@controller.perform_caching = true
@controller.cache_store = @store
- @params = {controller: "posts", action: "index"}
+ @params = { controller: "posts", action: "index" }
@controller.params = @params
@controller.request = @request
@controller.response = @response
@@ -184,6 +184,7 @@ class FunctionalFragmentCachingTest < ActionController::TestCase
@controller = FunctionalCachingController.new
@controller.perform_caching = true
@controller.cache_store = @store
+ @controller.enable_fragment_cache_logging = true
end
def test_fragment_caching
@@ -277,7 +278,6 @@ CACHED
@store.read("views/test.host/functional_caching/formatted_fragment_cached/#{template_digest("functional_caching/formatted_fragment_cached")}")
end
-
def test_fragment_caching_with_variant
get :formatted_fragment_cached_with_variant, format: "html", params: { v: :phone }
assert_response :success
@@ -324,7 +324,7 @@ class CacheHelperOutputBufferTest < ActionController::TestCase
cache_helper.stub :output_buffer, output_buffer do
assert_called_with cache_helper, :output_buffer=, [output_buffer.class.new(output_buffer)] do
assert_nothing_raised do
- cache_helper.send :fragment_for, "Test fragment name", "Test fragment", &Proc.new{ nil }
+ cache_helper.send :fragment_for, "Test fragment name", "Test fragment", &Proc.new { nil }
end
end
end
@@ -345,7 +345,7 @@ class CacheHelperOutputBufferTest < ActionController::TestCase
cache_helper.stub :output_buffer, output_buffer do
assert_called_with cache_helper, :output_buffer=, [output_buffer.class.new(output_buffer)] do
assert_nothing_raised do
- cache_helper.send :fragment_for, "Test fragment name", "Test fragment", &Proc.new{ nil }
+ cache_helper.send :fragment_for, "Test fragment name", "Test fragment", &Proc.new { nil }
end
end
end
diff --git a/actionpack/test/controller/default_url_options_with_before_action_test.rb b/actionpack/test/controller/default_url_options_with_before_action_test.rb
index 703f9f1fde..e3fe7a6495 100644
--- a/actionpack/test/controller/default_url_options_with_before_action_test.rb
+++ b/actionpack/test/controller/default_url_options_with_before_action_test.rb
@@ -13,7 +13,7 @@ class ControllerWithBeforeActionAndDefaultUrlOptions < ActionController::Base
end
def default_url_options
- {locale: "de"}
+ { locale: "de" }
end
end
diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb
index 237711452a..e0987070a3 100644
--- a/actionpack/test/controller/filters_test.rb
+++ b/actionpack/test/controller/filters_test.rb
@@ -174,11 +174,11 @@ class FilterTest < ActionController::TestCase
end
class OnlyConditionProcController < ConditionalFilterController
- before_action(only: :show) {|c| c.instance_variable_set(:"@ran_proc_action", true) }
+ before_action(only: :show) { |c| c.instance_variable_set(:"@ran_proc_action", true) }
end
class ExceptConditionProcController < ConditionalFilterController
- before_action(except: :show_without_action) {|c| c.instance_variable_set(:"@ran_proc_action", true) }
+ before_action(except: :show_without_action) { |c| c.instance_variable_set(:"@ran_proc_action", true) }
end
class ConditionalClassFilter
@@ -194,11 +194,11 @@ class FilterTest < ActionController::TestCase
end
class AnomolousYetValidConditionController < ConditionalFilterController
- before_action(ConditionalClassFilter, :ensure_login, Proc.new {|c| c.instance_variable_set(:"@ran_proc_action1", true)}, except: :show_without_action) { |c| c.instance_variable_set(:"@ran_proc_action2", true)}
+ before_action(ConditionalClassFilter, :ensure_login, Proc.new { |c| c.instance_variable_set(:"@ran_proc_action1", true) }, except: :show_without_action) { |c| c.instance_variable_set(:"@ran_proc_action2", true) }
end
class OnlyConditionalOptionsFilter < ConditionalFilterController
- before_action :ensure_login, only: :index, if: Proc.new {|c| c.instance_variable_set(:"@ran_conditional_index_proc", true) }
+ before_action :ensure_login, only: :index, if: Proc.new { |c| c.instance_variable_set(:"@ran_conditional_index_proc", true) }
end
class ConditionalOptionsFilter < ConditionalFilterController
diff --git a/actionpack/test/controller/flash_hash_test.rb b/actionpack/test/controller/flash_hash_test.rb
index 16651a3fd7..32f0db71f5 100644
--- a/actionpack/test/controller/flash_hash_test.rb
+++ b/actionpack/test/controller/flash_hash_test.rb
@@ -48,11 +48,11 @@ module ActionDispatch
def test_to_hash
@hash["foo"] = "bar"
- assert_equal({"foo" => "bar"}, @hash.to_hash)
+ assert_equal({ "foo" => "bar" }, @hash.to_hash)
@hash.to_hash["zomg"] = "aaron"
assert !@hash.key?("zomg")
- assert_equal({"foo" => "bar"}, @hash.to_hash)
+ assert_equal({ "foo" => "bar" }, @hash.to_hash)
end
def test_to_session_value
@@ -74,7 +74,7 @@ module ActionDispatch
rails_3_2_cookie = "BAh7B0kiD3Nlc3Npb25faWQGOgZFRkkiJWY4ZTFiODE1MmJhNzYwOWMyOGJiYjE3ZWM5MjYzYmE3BjsAVEkiCmZsYXNoBjsARm86JUFjdGlvbkRpc3BhdGNoOjpGbGFzaDo6Rmxhc2hIYXNoCToKQHVzZWRvOghTZXQGOgpAaGFzaHsGSSINZmFyZXdlbGwGOwBUVDoMQGNsb3NlZEY6DUBmbGFzaGVzewdJIg1ncmVldGluZwY7AFRJIgpIZWxsbwY7AFRJIg1mYXJld2VsbAY7AFRJIgxHb29kYnllBjsAVDoJQG5vdzA="
session = Marshal.load(Base64.decode64(rails_3_2_cookie))
hash = Flash::FlashHash.from_session_value(session["flash"])
- assert_equal({"greeting" => "Hello"}, hash.to_hash)
+ assert_equal({ "greeting" => "Hello" }, hash.to_hash)
assert_equal(nil, hash.to_session_value)
end
@@ -83,7 +83,7 @@ module ActionDispatch
session = ActionDispatch::Cookies::JsonSerializer.load(decrypted_data)
hash = Flash::FlashHash.from_session_value(session["flash"])
- assert_equal({"greeting" => "Hello"}, hash.to_hash)
+ assert_equal({ "greeting" => "Hello" }, hash.to_hash)
assert_equal(nil, hash.to_session_value)
assert_equal "Hello", hash[:greeting]
assert_equal "Hello", hash["greeting"]
@@ -112,7 +112,7 @@ module ActionDispatch
def test_replace
@hash["hello"] = "world"
@hash.replace("omg" => "aaron")
- assert_equal({"omg" => "aaron"}, @hash.to_hash)
+ assert_equal({ "omg" => "aaron" }, @hash.to_hash)
end
def test_discard_no_args
@@ -129,14 +129,14 @@ module ActionDispatch
@hash.discard "hello"
@hash.sweep
- assert_equal({"omg" => "world"}, @hash.to_hash)
+ assert_equal({ "omg" => "world" }, @hash.to_hash)
end
def test_keep_sweep
@hash["hello"] = "world"
@hash.sweep
- assert_equal({"hello" => "world"}, @hash.to_hash)
+ assert_equal({ "hello" => "world" }, @hash.to_hash)
end
def test_update_sweep
@@ -144,7 +144,7 @@ module ActionDispatch
@hash.update("hi" => "mom")
@hash.sweep
- assert_equal({"hello" => "world", "hi" => "mom"}, @hash.to_hash)
+ assert_equal({ "hello" => "world", "hi" => "mom" }, @hash.to_hash)
end
def test_update_delete_sweep
@@ -153,7 +153,7 @@ module ActionDispatch
@hash.update("hello" => "mom")
@hash.sweep
- assert_equal({"hello" => "mom"}, @hash.to_hash)
+ assert_equal({ "hello" => "mom" }, @hash.to_hash)
end
def test_delete_sweep
@@ -162,7 +162,7 @@ module ActionDispatch
@hash.delete "hi"
@hash.sweep
- assert_equal({"hello" => "world"}, @hash.to_hash)
+ assert_equal({ "hello" => "world" }, @hash.to_hash)
end
def test_clear_sweep
@@ -178,7 +178,7 @@ module ActionDispatch
@hash.replace("hi" => "mom")
@hash.sweep
- assert_equal({"hi" => "mom"}, @hash.to_hash)
+ assert_equal({ "hi" => "mom" }, @hash.to_hash)
end
def test_discard_then_add
@@ -188,7 +188,7 @@ module ActionDispatch
@hash["hello"] = "world"
@hash.sweep
- assert_equal({"omg" => "world", "hello" => "world"}, @hash.to_hash)
+ assert_equal({ "omg" => "world", "hello" => "world" }, @hash.to_hash)
end
def test_keep_all_sweep
@@ -198,14 +198,14 @@ module ActionDispatch
@hash.keep
@hash.sweep
- assert_equal({"omg" => "world", "hello" => "world"}, @hash.to_hash)
+ assert_equal({ "omg" => "world", "hello" => "world" }, @hash.to_hash)
end
def test_double_sweep
@hash["hello"] = "world"
@hash.sweep
- assert_equal({"hello" => "world"}, @hash.to_hash)
+ assert_equal({ "hello" => "world" }, @hash.to_hash)
@hash.sweep
assert_equal({}, @hash.to_hash)
diff --git a/actionpack/test/controller/flash_test.rb b/actionpack/test/controller/flash_test.rb
index 4e046b2fc8..cabbe2d608 100644
--- a/actionpack/test/controller/flash_test.rb
+++ b/actionpack/test/controller/flash_test.rb
@@ -176,13 +176,13 @@ class FlashTest < ActionController::TestCase
assert_equal(:foo_indeed, flash.discard(:foo)) # valid key passed
assert_nil flash.discard(:unknown) # non existent key passed
- assert_equal({"foo" => :foo_indeed, "bar" => :bar_indeed}, flash.discard().to_hash) # nothing passed
- assert_equal({"foo" => :foo_indeed, "bar" => :bar_indeed}, flash.discard(nil).to_hash) # nothing passed
+ assert_equal({ "foo" => :foo_indeed, "bar" => :bar_indeed }, flash.discard().to_hash) # nothing passed
+ assert_equal({ "foo" => :foo_indeed, "bar" => :bar_indeed }, flash.discard(nil).to_hash) # nothing passed
assert_equal(:foo_indeed, flash.keep(:foo)) # valid key passed
assert_nil flash.keep(:unknown) # non existent key passed
- assert_equal({"foo" => :foo_indeed, "bar" => :bar_indeed}, flash.keep().to_hash) # nothing passed
- assert_equal({"foo" => :foo_indeed, "bar" => :bar_indeed}, flash.keep(nil).to_hash) # nothing passed
+ assert_equal({ "foo" => :foo_indeed, "bar" => :bar_indeed }, flash.keep().to_hash) # nothing passed
+ assert_equal({ "foo" => :foo_indeed, "bar" => :bar_indeed }, flash.keep(nil).to_hash) # nothing passed
end
def test_redirect_to_with_alert
diff --git a/actionpack/test/controller/helper_test.rb b/actionpack/test/controller/helper_test.rb
index d18e19f961..981b67f685 100644
--- a/actionpack/test/controller/helper_test.rb
+++ b/actionpack/test/controller/helper_test.rb
@@ -247,7 +247,6 @@ class HelperTest < ActiveSupport::TestCase
end
end
-
class IsolatedHelpersTest < ActionController::TestCase
class A < ActionController::Base
def index
diff --git a/actionpack/test/controller/http_digest_authentication_test.rb b/actionpack/test/controller/http_digest_authentication_test.rb
index 5e9b801f8b..343b7b643d 100644
--- a/actionpack/test/controller/http_digest_authentication_test.rb
+++ b/actionpack/test/controller/http_digest_authentication_test.rb
@@ -7,7 +7,7 @@ class HttpDigestAuthenticationTest < ActionController::TestCase
before_action :authenticate_with_request, only: :display
USERS = { "lifo" => "world", "pretty" => "please",
- "dhh" => ::Digest::MD5::hexdigest(["dhh","SuperSecret","secret"].join(":"))}
+ "dhh" => ::Digest::MD5::hexdigest(["dhh","SuperSecret","secret"].join(":")) }
def index
render plain: "Hello Secret"
@@ -199,7 +199,7 @@ class HttpDigestAuthenticationTest < ActionController::TestCase
test "validate_digest_response should fail with nil returning password_procedure" do
@request.env["HTTP_AUTHORIZATION"] = encode_credentials(username: nil, password: nil)
- assert !ActionController::HttpAuthentication::Digest.validate_digest_response(@request, "SuperSecret"){nil}
+ assert !ActionController::HttpAuthentication::Digest.validate_digest_response(@request, "SuperSecret") { nil }
end
test "authentication request with request-uri ending in '/'" do
diff --git a/actionpack/test/controller/http_token_authentication_test.rb b/actionpack/test/controller/http_token_authentication_test.rb
index b7a4c550d7..3842136682 100644
--- a/actionpack/test/controller/http_token_authentication_test.rb
+++ b/actionpack/test/controller/http_token_authentication_test.rb
@@ -156,10 +156,10 @@ class HttpTokenAuthenticationTest < ActionController::TestCase
test "token_and_options returns correct token with nounce option" do
token = "rcHu+HzSFw89Ypyhn/896A="
- nonce_hash = {nonce: "123abc"}
+ nonce_hash = { nonce: "123abc" }
actual = ActionController::HttpAuthentication::Token.token_and_options(sample_request(token, nonce_hash))
expected_token = token
- expected_nonce = {"nonce" => nonce_hash[:nonce]}
+ expected_nonce = { "nonce" => nonce_hash[:nonce] }
assert_equal(expected_token, actual.first)
assert_equal(expected_nonce, actual.last)
end
@@ -190,7 +190,7 @@ class HttpTokenAuthenticationTest < ActionController::TestCase
private
- def sample_request(token, options = {nonce: "def"})
+ def sample_request(token, options = { nonce: "def" })
authorization = options.inject([%{Token token="#{token}"}]) do |arr, (k, v)|
arr << "#{k}=\"#{v}\""
end.join(", ")
diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb
index 0d6a441789..9044eff801 100644
--- a/actionpack/test/controller/integration_test.rb
+++ b/actionpack/test/controller/integration_test.rb
@@ -4,7 +4,7 @@ require "rails/engine"
class SessionTest < ActiveSupport::TestCase
StubApp = lambda { |env|
- [200, {"Content-Type" => "text/html", "Content-Length" => "13"}, ["Hello, World!"]]
+ [200, { "Content-Type" => "text/html", "Content-Length" => "13" }, ["Hello, World!"]]
}
def setup
@@ -32,7 +32,7 @@ class SessionTest < ActiveSupport::TestCase
end
def test_request_via_redirect_uses_given_method
- path = "/somepath"; args = {id: "1"}; headers = {"X-Test-Header" => "testvalue"}
+ path = "/somepath"; args = { id: "1" }; headers = { "X-Test-Header" => "testvalue" }
assert_called_with @session, :process, [:put, path, params: args, headers: headers] do
@session.stub :redirect?, false do
assert_deprecated { @session.request_via_redirect(:put, path, params: args, headers: headers) }
@@ -50,17 +50,17 @@ class SessionTest < ActiveSupport::TestCase
end
def test_request_via_redirect_follows_redirects
- path = "/somepath"; args = {id: "1"}; headers = {"X-Test-Header" => "testvalue"}
+ path = "/somepath"; args = { id: "1" }; headers = { "X-Test-Header" => "testvalue" }
value_series = [true, true, false]
assert_called @session, :follow_redirect!, times: 2 do
- @session.stub :redirect?, ->{ value_series.shift } do
+ @session.stub :redirect?, -> { value_series.shift } do
assert_deprecated { @session.request_via_redirect(:get, path, params: args, headers: headers) }
end
end
end
def test_request_via_redirect_returns_status
- path = "/somepath"; args = {id: "1"}; headers = {"X-Test-Header" => "testvalue"}
+ path = "/somepath"; args = { id: "1" }; headers = { "X-Test-Header" => "testvalue" }
@session.stub :redirect?, false do
@session.stub :status, 200 do
assert_deprecated do
@@ -403,6 +403,7 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
respond_to do |format|
format.html { render plain: "OK", status: 200 }
format.js { render plain: "JS OK", status: 200 }
+ format.json { render json: "JSON OK", status: 200 }
format.xml { render xml: "<root></root>", status: 200 }
format.rss { render xml: "<root></root>", status: 200 }
format.atom { render xml: "<root></root>", status: 200 }
@@ -465,7 +466,7 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
def test_get_xml_rss_atom
%w[ application/xml application/rss+xml application/atom+xml ].each do |mime_string|
with_test_route_set do
- get "/get", headers: {"HTTP_ACCEPT" => mime_string}
+ get "/get", headers: { "HTTP_ACCEPT" => mime_string }
assert_equal 200, status
assert_equal "OK", status_message
assert_response 200
@@ -502,7 +503,7 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
self.cookies["cookie_2"] = "oatmeal"
get "/cookie_monster"
assert_equal "cookie_1=; path=/\ncookie_3=chocolate; path=/", headers["Set-Cookie"]
- assert_equal({"cookie_1"=>"", "cookie_2"=>"oatmeal", "cookie_3"=>"chocolate"}, cookies.to_hash)
+ assert_equal({ "cookie_1"=>"", "cookie_2"=>"oatmeal", "cookie_3"=>"chocolate" }, cookies.to_hash)
end
end
@@ -512,14 +513,14 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
assert_response :success
assert_equal "foo=bar; path=/", headers["Set-Cookie"]
- assert_equal({"foo"=>"bar"}, cookies.to_hash)
+ assert_equal({ "foo"=>"bar" }, cookies.to_hash)
get "/get_cookie"
assert_response :success
assert_equal "bar", body
assert_equal nil, headers["Set-Cookie"]
- assert_equal({"foo"=>"bar"}, cookies.to_hash)
+ assert_equal({ "foo"=>"bar" }, cookies.to_hash)
end
end
@@ -531,14 +532,14 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
assert_response :success
assert_equal "foo=bar; path=/", headers["Set-Cookie"]
- assert_equal({"foo"=>"bar"}, cookies.to_hash)
+ assert_equal({ "foo"=>"bar" }, cookies.to_hash)
get "/get_cookie"
assert_response :success
assert_equal "bar", body
assert_equal nil, headers["Set-Cookie"]
- assert_equal({"foo"=>"bar"}, cookies.to_hash)
+ assert_equal({ "foo"=>"bar" }, cookies.to_hash)
end
end
@@ -727,6 +728,18 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
assert_includes @response.headers, "c"
end
+ def test_accept_not_overriden_when_xhr_true
+ with_test_route_set do
+ get "/get", headers: { "Accept" => "application/json" }, xhr: true
+ assert_equal "application/json", request.accept
+ assert_equal "application/json", response.content_type
+
+ get "/get", headers: { "HTTP_ACCEPT" => "application/json" }, xhr: true
+ assert_equal "application/json", request.accept
+ assert_equal "application/json", response.content_type
+ end
+ end
+
private
def with_default_headers(headers)
original = ActionDispatch::Response.default_headers
@@ -752,7 +765,7 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
end
end
- self.singleton_class.include(set.url_helpers)
+ singleton_class.include(set.url_helpers)
yield
end
@@ -765,9 +778,9 @@ class MetalIntegrationTest < ActionDispatch::IntegrationTest
class Poller
def self.call(env)
if env["PATH_INFO"] =~ /^\/success/
- [200, {"Content-Type" => "text/plain", "Content-Length" => "12"}, ["Hello World!"]]
+ [200, { "Content-Type" => "text/plain", "Content-Length" => "12" }, ["Hello World!"]]
else
- [404, {"Content-Type" => "text/plain", "Content-Length" => "0"}, []]
+ [404, { "Content-Type" => "text/plain", "Content-Length" => "0" }, []]
end
end
end
@@ -796,7 +809,7 @@ class MetalIntegrationTest < ActionDispatch::IntegrationTest
end
def test_pass_headers
- get "/success", headers: {"Referer" => "http://www.example.com/foo", "Host" => "http://nohost.com"}
+ get "/success", headers: { "Referer" => "http://www.example.com/foo", "Host" => "http://nohost.com" }
assert_equal "http://nohost.com", @request.env["HTTP_HOST"]
assert_equal "http://www.example.com/foo", @request.env["HTTP_REFERER"]
@@ -872,7 +885,7 @@ class ApplicationIntegrationTest < ActionDispatch::IntegrationTest
get "bar", to: "application_integration_test/test#index", as: :bar
mount MountedApp => "/mounted", :as => "mounted"
- get "fooz" => proc { |env| [ 200, {"X-Cascade" => "pass"}, [ "omg" ] ] }, :anchor => false
+ get "fooz" => proc { |env| [ 200, { "X-Cascade" => "pass" }, [ "omg" ] ] }, :anchor => false
get "fooz", to: "application_integration_test/test#index"
end
@@ -1145,7 +1158,7 @@ class IntegrationRequestsWithSessionSetup < ActionDispatch::IntegrationTest
def test_cookies_set_in_setup_are_persisted_through_the_session
get "/foo"
- assert_equal({"user_name"=>"david"}, cookies.to_hash)
+ assert_equal({ "user_name"=>"david" }, cookies.to_hash)
end
end
diff --git a/actionpack/test/controller/live_stream_test.rb b/actionpack/test/controller/live_stream_test.rb
index 3ea02f0a19..1361e95081 100644
--- a/actionpack/test/controller/live_stream_test.rb
+++ b/actionpack/test/controller/live_stream_test.rb
@@ -150,6 +150,20 @@ module ActionController
response.stream.close
end
+ def write_sleep_autoload
+ path = File.join(File.dirname(__FILE__), "../fixtures")
+ ActiveSupport::Dependencies.autoload_paths << path
+
+ response.headers["Content-Type"] = "text/event-stream"
+ response.stream.write "before load"
+ sleep 0.01
+ ::LoadMe
+ response.stream.close
+ latch.count_down
+
+ ActiveSupport::Dependencies.autoload_paths.reject! { |p| p == path }
+ end
+
def thread_locals
tc.assert_equal "aaron", Thread.current[:setting]
@@ -271,7 +285,7 @@ module ActionController
def test_set_cookie
get :set_cookie
- assert_equal({"hello" => "world"}, @response.cookies)
+ assert_equal({ "hello" => "world" }, @response.cookies)
assert_equal "hello world", @response.body
end
@@ -281,6 +295,14 @@ module ActionController
assert_equal "text/event-stream", @response.headers["Content-Type"]
end
+ def test_delayed_autoload_after_write_within_interlock_hook
+ # Simulate InterlockHook
+ ActiveSupport::Dependencies.interlock.start_running
+ res = get :write_sleep_autoload
+ res.each {}
+ ActiveSupport::Dependencies.interlock.done_running
+ end
+
def test_async_stream
rubinius_skip "https://github.com/rubinius/rubinius/issues/2934"
diff --git a/actionpack/test/controller/log_subscriber_test.rb b/actionpack/test/controller/log_subscriber_test.rb
index dfc0edea69..45a120acb6 100644
--- a/actionpack/test/controller/log_subscriber_test.rb
+++ b/actionpack/test/controller/log_subscriber_test.rb
@@ -92,6 +92,7 @@ class ACLogSubscriberTest < ActionController::TestCase
def setup
super
+ ActionController::Base.enable_fragment_cache_logging = true
@old_logger = ActionController::Base.logger
@@ -105,6 +106,7 @@ class ACLogSubscriberTest < ActionController::TestCase
ActiveSupport::LogSubscriber.log_subscribers.clear
FileUtils.rm_rf(@cache_path)
ActionController::Base.logger = @old_logger
+ ActionController::Base.enable_fragment_cache_logging = true
end
def set_logger(logger)
@@ -136,7 +138,7 @@ class ACLogSubscriberTest < ActionController::TestCase
def test_process_action_without_parameters
get :show
wait
- assert_nil logs.detect {|l| l =~ /Parameters/ }
+ assert_nil logs.detect { |l| l =~ /Parameters/ }
end
def test_process_action_with_parameters
@@ -258,6 +260,20 @@ class ACLogSubscriberTest < ActionController::TestCase
@controller.config.perform_caching = true
end
+ def test_with_fragment_cache_when_log_disabled
+ @controller.config.perform_caching = true
+ ActionController::Base.enable_fragment_cache_logging = false
+ get :with_fragment_cache
+ wait
+
+ assert_equal 2, logs.size
+ assert_equal "Processing by Another::LogSubscribersController#with_fragment_cache as HTML", logs[0]
+ assert_match(/Completed 200 OK in \d+ms/, logs[1])
+ ensure
+ @controller.config.perform_caching = true
+ ActionController::Base.enable_fragment_cache_logging = true
+ end
+
def test_with_fragment_cache_if_with_true
@controller.config.perform_caching = true
get :with_fragment_cache_if_with_true_condition
diff --git a/actionpack/test/controller/mime/respond_to_test.rb b/actionpack/test/controller/mime/respond_to_test.rb
index 26545686df..c5f8165d04 100644
--- a/actionpack/test/controller/mime/respond_to_test.rb
+++ b/actionpack/test/controller/mime/respond_to_test.rb
@@ -51,7 +51,6 @@ class RespondToController < ActionController::Base
end
end
-
def forced_xml
request.format = :xml
@@ -77,7 +76,7 @@ class RespondToController < ActionController::Base
def missing_templates
respond_to do |type|
# This test requires a block that is empty
- type.json { }
+ type.json {}
type.xml
end
end
@@ -109,7 +108,6 @@ class RespondToController < ActionController::Base
end
end
-
def custom_constant_handling
respond_to do |type|
type.html { render body: "HTML" }
@@ -223,7 +221,7 @@ class RespondToController < ActionController::Base
def variant_any
respond_to do |format|
format.html do |variant|
- variant.any(:tablet, :phablet){ render body: "any" }
+ variant.any(:tablet, :phablet) { render body: "any" }
variant.phone { render body: "phone" }
end
end
@@ -240,7 +238,7 @@ class RespondToController < ActionController::Base
def variant_inline_any
respond_to do |format|
- format.html.any(:tablet, :phablet){ render body: "any" }
+ format.html.any(:tablet, :phablet) { render body: "any" }
format.html.phone { render body: "phone" }
end
end
@@ -261,7 +259,7 @@ class RespondToController < ActionController::Base
def variant_any_with_none
respond_to do |format|
- format.html.any(:none, :phone){ render body: "none or phone" }
+ format.html.any(:none, :phone) { render body: "none or phone" }
end
end
@@ -269,8 +267,8 @@ class RespondToController < ActionController::Base
respond_to do |format|
format.html { render body: "HTML" }
format.any(:js, :xml) do |variant|
- variant.phone{ render body: "phone" }
- variant.any(:tablet, :phablet){ render body: "tablet" }
+ variant.phone { render body: "phone" }
+ variant.any(:tablet, :phablet) { render body: "tablet" }
end
end
end
@@ -676,7 +674,7 @@ class RespondToControllerTest < ActionController::TestCase
get :variant_without_implicit_template_rendering, xhr: true, params: { v: :does_not_matter }
assert_response :no_content
- assert_equal 1, logger.logged(:info).select{ |s| s == NO_CONTENT_WARNING }.size, "Implicit head :no_content not logged"
+ assert_equal 1, logger.logged(:info).select { |s| s == NO_CONTENT_WARNING }.size, "Implicit head :no_content not logged"
ensure
ActionController::Base.logger = old_logger
end
@@ -688,7 +686,7 @@ class RespondToControllerTest < ActionController::TestCase
get :variant_without_implicit_template_rendering, format: "json", params: { v: :does_not_matter }
assert_response :no_content
- assert_equal 1, logger.logged(:info).select{ |s| s == NO_CONTENT_WARNING }.size, "Implicit head :no_content not logged"
+ assert_equal 1, logger.logged(:info).select { |s| s == NO_CONTENT_WARNING }.size, "Implicit head :no_content not logged"
ensure
ActionController::Base.logger = old_logger
end
diff --git a/actionpack/test/controller/new_base/content_negotiation_test.rb b/actionpack/test/controller/new_base/content_negotiation_test.rb
index 8e83e1966a..b870745031 100644
--- a/actionpack/test/controller/new_base/content_negotiation_test.rb
+++ b/actionpack/test/controller/new_base/content_negotiation_test.rb
@@ -8,7 +8,7 @@ module ContentNegotiation
)]
def all
- render plain: self.formats.inspect
+ render plain: formats.inspect
end
end
diff --git a/actionpack/test/controller/new_base/render_action_test.rb b/actionpack/test/controller/new_base/render_action_test.rb
index e88f83b594..4b59a3d676 100644
--- a/actionpack/test/controller/new_base/render_action_test.rb
+++ b/actionpack/test/controller/new_base/render_action_test.rb
@@ -258,7 +258,8 @@ end
module RenderActionWithBothLayouts
class BasicController < ActionController::Base
- self.view_paths = [ActionView::FixtureResolver.new( "render_action_with_both_layouts/basic/hello_world.html.erb" => "Hello World!",
+ self.view_paths = [ActionView::FixtureResolver.new(
+ "render_action_with_both_layouts/basic/hello_world.html.erb" => "Hello World!",
"layouts/application.html.erb" => "Oh Hi <%= yield %> Bye",
"layouts/render_action_with_both_layouts/basic.html.erb" => "With Controller Layout! <%= yield %> Bye")]
diff --git a/actionpack/test/controller/new_base/render_file_test.rb b/actionpack/test/controller/new_base/render_file_test.rb
index 9618157657..6d651e0104 100644
--- a/actionpack/test/controller/new_base/render_file_test.rb
+++ b/actionpack/test/controller/new_base/render_file_test.rb
@@ -30,7 +30,7 @@ module RenderFile
def with_locals
path = File.join(File.dirname(__FILE__), "../../fixtures/test/render_file_with_locals")
- render file: path, locals: {secret: "in the sauce"}
+ render file: path, locals: { secret: "in the sauce" }
end
end
diff --git a/actionpack/test/controller/parameter_encoding_test.rb b/actionpack/test/controller/parameter_encoding_test.rb
new file mode 100644
index 0000000000..7840b4f5c4
--- /dev/null
+++ b/actionpack/test/controller/parameter_encoding_test.rb
@@ -0,0 +1,73 @@
+require "abstract_unit"
+
+class ParameterEncodingController < ActionController::Base
+ parameter_encoding :test_bar, :bar, Encoding::ASCII_8BIT
+ parameter_encoding :test_baz, :baz, Encoding::ISO_8859_1
+ parameter_encoding :test_baz_to_ascii, :baz, Encoding::ASCII_8BIT
+
+ def test_foo
+ render body: params[:foo].encoding
+ end
+
+ def test_bar
+ render body: params[:bar].encoding
+ end
+
+ def test_baz
+ render body: params[:baz].encoding
+ end
+
+ def test_no_change_to_baz
+ render body: params[:baz].encoding
+ end
+
+ def test_baz_to_ascii
+ render body: params[:baz].encoding
+ end
+end
+
+class ParameterEncodingTest < ActionController::TestCase
+ tests ParameterEncodingController
+
+ test "properly transcodes UTF8 parameters into declared encodings" do
+ post :test_foo, params: { "foo" => "foo", "bar" => "bar", "baz" => "baz" }
+
+ assert_response :success
+ assert_equal "UTF-8", @response.body
+ end
+
+ test "properly transcodes ASCII_8BIT parameters into declared encodings" do
+ post :test_bar, params: { "foo" => "foo", "bar" => "bar", "baz" => "baz" }
+
+ assert_response :success
+ assert_equal "ASCII-8BIT", @response.body
+ end
+
+ test "properly transcodes ISO_8859_1 parameters into declared encodings" do
+ post :test_baz, params: { "foo" => "foo", "bar" => "bar", "baz" => "baz" }
+
+ assert_response :success
+ assert_equal "ISO-8859-1", @response.body
+ end
+
+ test "does not transcode parameters when not specified" do
+ post :test_no_change_to_baz, params: { "foo" => "foo", "bar" => "bar", "baz" => "baz" }
+
+ assert_response :success
+ assert_equal "UTF-8", @response.body
+ end
+
+ test "respects different encoding declarations for a param per action" do
+ post :test_baz_to_ascii, params: { "foo" => "foo", "bar" => "bar", "baz" => "baz" }
+
+ assert_response :success
+ assert_equal "ASCII-8BIT", @response.body
+ end
+
+ test "does not raise an error when passed a param declared as ASCII-8BIT that contains invalid bytes" do
+ get :test_bar, params: { "bar" => URI.parser.escape("bar\xE2baz".b) }
+
+ assert_response :success
+ assert_equal "ASCII-8BIT", @response.body
+ end
+end
diff --git a/actionpack/test/controller/parameters/accessors_test.rb b/actionpack/test/controller/parameters/accessors_test.rb
index a63512e8bd..8a522b2df8 100644
--- a/actionpack/test/controller/parameters/accessors_test.rb
+++ b/actionpack/test/controller/parameters/accessors_test.rb
@@ -13,7 +13,7 @@ class ParametersAccessorsTest < ActiveSupport::TestCase
first: "David",
last: "Heinemeier Hansson"
},
- addresses: [{city: "Chicago", state: "Illinois"}]
+ addresses: [{ city: "Chicago", state: "Illinois" }]
}
)
end
diff --git a/actionpack/test/controller/parameters/always_permitted_parameters_test.rb b/actionpack/test/controller/parameters/always_permitted_parameters_test.rb
index 9c9749c037..cd7c98f112 100644
--- a/actionpack/test/controller/parameters/always_permitted_parameters_test.rb
+++ b/actionpack/test/controller/parameters/always_permitted_parameters_test.rb
@@ -19,7 +19,8 @@ class AlwaysPermittedParametersTest < ActiveSupport::TestCase
end
test "permits parameters that are whitelisted" do
- params = ActionController::Parameters.new( book: { pages: 65 },
+ params = ActionController::Parameters.new(
+ book: { pages: 65 },
format: "json")
permitted = params.permit book: [:pages]
assert permitted.permitted?
diff --git a/actionpack/test/controller/parameters/dup_test.rb b/actionpack/test/controller/parameters/dup_test.rb
index 152f608266..d88891ca30 100644
--- a/actionpack/test/controller/parameters/dup_test.rb
+++ b/actionpack/test/controller/parameters/dup_test.rb
@@ -12,7 +12,7 @@ class ParametersDupTest < ActiveSupport::TestCase
first: "David",
last: "Heinemeier Hansson"
},
- addresses: [{city: "Chicago", state: "Illinois"}]
+ addresses: [{ city: "Chicago", state: "Illinois" }]
}
)
end
diff --git a/actionpack/test/controller/parameters/log_on_unpermitted_params_test.rb b/actionpack/test/controller/parameters/log_on_unpermitted_params_test.rb
index bf2c3d1ed2..c800c1d3df 100644
--- a/actionpack/test/controller/parameters/log_on_unpermitted_params_test.rb
+++ b/actionpack/test/controller/parameters/log_on_unpermitted_params_test.rb
@@ -11,36 +11,40 @@ class LogOnUnpermittedParamsTest < ActiveSupport::TestCase
end
test "logs on unexpected param" do
- params = ActionController::Parameters.new( book: { pages: 65 },
+ params = ActionController::Parameters.new(
+ book: { pages: 65 },
fishing: "Turnips")
- assert_logged("Unpermitted parameter: fishing") do
+ assert_logged("Unpermitted parameter: :fishing") do
params.permit(book: [:pages])
end
end
test "logs on unexpected params" do
- params = ActionController::Parameters.new( book: { pages: 65 },
+ params = ActionController::Parameters.new(
+ book: { pages: 65 },
fishing: "Turnips",
car: "Mersedes")
- assert_logged("Unpermitted parameters: fishing, car") do
+ assert_logged("Unpermitted parameters: :fishing, :car") do
params.permit(book: [:pages])
end
end
test "logs on unexpected nested param" do
- params = ActionController::Parameters.new( book: { pages: 65, title: "Green Cats and where to find then." })
+ params = ActionController::Parameters.new(
+ book: { pages: 65, title: "Green Cats and where to find then." })
- assert_logged("Unpermitted parameter: title") do
+ assert_logged("Unpermitted parameter: :title") do
params.permit(book: [:pages])
end
end
test "logs on unexpected nested params" do
- params = ActionController::Parameters.new( book: { pages: 65, title: "Green Cats and where to find then.", author: "G. A. Dog" })
+ params = ActionController::Parameters.new(
+ book: { pages: 65, title: "Green Cats and where to find then.", author: "G. A. Dog" })
- assert_logged("Unpermitted parameters: title, author") do
+ assert_logged("Unpermitted parameters: :title, :author") do
params.permit(book: [:pages])
end
end
diff --git a/actionpack/test/controller/parameters/multi_parameter_attributes_test.rb b/actionpack/test/controller/parameters/multi_parameter_attributes_test.rb
index 44e39135a2..88fb477c10 100644
--- a/actionpack/test/controller/parameters/multi_parameter_attributes_test.rb
+++ b/actionpack/test/controller/parameters/multi_parameter_attributes_test.rb
@@ -3,7 +3,8 @@ require "action_controller/metal/strong_parameters"
class MultiParameterAttributesTest < ActiveSupport::TestCase
test "permitted multi-parameter attribute keys" do
- params = ActionController::Parameters.new( book: {
+ params = ActionController::Parameters.new(
+ book: {
"shipped_at(1i)" => "2012",
"shipped_at(2i)" => "3",
"shipped_at(3i)" => "25",
diff --git a/actionpack/test/controller/parameters/mutators_test.rb b/actionpack/test/controller/parameters/mutators_test.rb
index a2dc84f2f7..e060e5180f 100644
--- a/actionpack/test/controller/parameters/mutators_test.rb
+++ b/actionpack/test/controller/parameters/mutators_test.rb
@@ -11,7 +11,7 @@ class ParametersMutatorsTest < ActiveSupport::TestCase
first: "David",
last: "Heinemeier Hansson"
},
- addresses: [{city: "Chicago", state: "Illinois"}]
+ addresses: [{ city: "Chicago", state: "Illinois" }]
}
)
end
diff --git a/actionpack/test/controller/parameters/nested_parameters_permit_test.rb b/actionpack/test/controller/parameters/nested_parameters_permit_test.rb
index e3f1ba5f0a..5f86901e30 100644
--- a/actionpack/test/controller/parameters/nested_parameters_permit_test.rb
+++ b/actionpack/test/controller/parameters/nested_parameters_permit_test.rb
@@ -7,7 +7,8 @@ class NestedParametersPermitTest < ActiveSupport::TestCase
end
test "permitted nested parameters" do
- params = ActionController::Parameters.new( book: {
+ params = ActionController::Parameters.new(
+ book: {
title: "Romeo and Juliet",
authors: [{
name: "William Shakespeare",
@@ -43,7 +44,8 @@ class NestedParametersPermitTest < ActiveSupport::TestCase
end
test "permitted nested parameters with a string or a symbol as a key" do
- params = ActionController::Parameters.new( book: {
+ params = ActionController::Parameters.new(
+ book: {
"authors" => [
{ name: "William Shakespeare", born: "1564-04-26" },
{ name: "Christopher Marlowe" }
@@ -66,29 +68,32 @@ class NestedParametersPermitTest < ActiveSupport::TestCase
end
test "nested arrays with strings" do
- params = ActionController::Parameters.new( book: {
+ params = ActionController::Parameters.new(
+ book: {
genres: ["Tragedy"]
})
- permitted = params.permit book: {genres: []}
+ permitted = params.permit book: { genres: [] }
assert_equal ["Tragedy"], permitted[:book][:genres]
end
test "permit may specify symbols or strings" do
- params = ActionController::Parameters.new( book: {
+ params = ActionController::Parameters.new(
+ book: {
title: "Romeo and Juliet",
author: "William Shakespeare"
},
magazine: "Shakespeare Today")
- permitted = params.permit({book: ["title", :author]}, "magazine")
+ permitted = params.permit({ book: ["title", :author] }, "magazine")
assert_equal "Romeo and Juliet", permitted[:book][:title]
assert_equal "William Shakespeare", permitted[:book][:author]
assert_equal "Shakespeare Today", permitted[:magazine]
end
test "nested array with strings that should be hashes" do
- params = ActionController::Parameters.new( book: {
+ params = ActionController::Parameters.new(
+ book: {
genres: ["Tragedy"]
})
@@ -97,7 +102,8 @@ class NestedParametersPermitTest < ActiveSupport::TestCase
end
test "nested array with strings that should be hashes and additional values" do
- params = ActionController::Parameters.new( book: {
+ params = ActionController::Parameters.new(
+ book: {
title: "Romeo and Juliet",
genres: ["Tragedy"]
})
@@ -108,7 +114,8 @@ class NestedParametersPermitTest < ActiveSupport::TestCase
end
test "nested string that should be a hash" do
- params = ActionController::Parameters.new( book: {
+ params = ActionController::Parameters.new(
+ book: {
genre: "Tragedy"
})
@@ -117,7 +124,8 @@ class NestedParametersPermitTest < ActiveSupport::TestCase
end
test "fields_for-style nested params" do
- params = ActionController::Parameters.new( book: {
+ params = ActionController::Parameters.new(
+ book: {
authors_attributes: {
'0': { name: "William Shakespeare", age_of_death: "52" },
'1': { name: "Unattributed Assistant" },
@@ -136,7 +144,8 @@ class NestedParametersPermitTest < ActiveSupport::TestCase
end
test "fields_for-style nested params with negative numbers" do
- params = ActionController::Parameters.new( book: {
+ params = ActionController::Parameters.new(
+ book: {
authors_attributes: {
'-1': { name: "William Shakespeare", age_of_death: "52" },
'-2': { name: "Unattributed Assistant" }
@@ -153,7 +162,8 @@ class NestedParametersPermitTest < ActiveSupport::TestCase
end
test "nested number as key" do
- params = ActionController::Parameters.new( product: {
+ params = ActionController::Parameters.new(
+ product: {
properties: {
"0" => "prop0",
"1" => "prop1"
diff --git a/actionpack/test/controller/parameters/parameters_permit_test.rb b/actionpack/test/controller/parameters/parameters_permit_test.rb
index b42288636e..164efd936c 100644
--- a/actionpack/test/controller/parameters/parameters_permit_test.rb
+++ b/actionpack/test/controller/parameters/parameters_permit_test.rb
@@ -15,7 +15,7 @@ class ParametersPermitTest < ActiveSupport::TestCase
first: "David",
last: "Heinemeier Hansson"
},
- addresses: [{city: "Chicago", state: "Illinois"}]
+ addresses: [{ city: "Chicago", state: "Illinois" }]
}
)
@@ -39,13 +39,13 @@ class ParametersPermitTest < ActiveSupport::TestCase
end
test "iteration should not impact permit" do
- hash = {"foo"=>{"bar"=>{"0"=>{"baz"=>"hello", "zot"=>"1"}}}}
+ hash = { "foo"=>{ "bar"=>{ "0"=>{ "baz"=>"hello", "zot"=>"1" } } } }
params = ActionController::Parameters.new(hash)
walk_permitted params
sanitized = params[:foo].permit(bar: [:baz])
- assert_equal({"0"=>{"baz"=>"hello"}}, sanitized[:bar].to_unsafe_h)
+ assert_equal({ "0"=>{ "baz"=>"hello" } }, sanitized[:bar].to_unsafe_h)
end
test "if nothing is permitted, the hash becomes empty" do
@@ -98,7 +98,7 @@ class ParametersPermitTest < ActiveSupport::TestCase
end
test "key: hashes are filtered out" do
- [{}, {foo: 1}, {foo: "bar"}].each do |hash|
+ [{}, { foo: 1 }, { foo: "bar" }].each do |hash|
params = ActionController::Parameters.new(id: hash)
permitted = params.permit(:id)
assert_filtered_out permitted, :id
@@ -161,7 +161,7 @@ class ParametersPermitTest < ActiveSupport::TestCase
end
test "key to empty array: arrays of non-permitted scalar do not pass" do
- [[Object.new], [[]], [[1]], [{}], [{id: "1"}]].each do |non_permitted_scalar|
+ [[Object.new], [[]], [[1]], [{}], [{ id: "1" }]].each do |non_permitted_scalar|
params = ActionController::Parameters.new(id: non_permitted_scalar)
permitted = params.permit(id: [])
assert_filtered_out permitted, :id
@@ -203,10 +203,10 @@ class ParametersPermitTest < ActiveSupport::TestCase
# the cache does not get fooled, the hash is still wrapped as strong params,
# and not permitted.
test "mutated arrays are detected" do
- params = ActionController::Parameters.new(users: [{id: 1}])
+ params = ActionController::Parameters.new(users: [{ id: 1 }])
permitted = params.permit(users: [:id])
- permitted[:users] << {injected: 1}
+ permitted[:users] << { injected: 1 }
assert_not permitted[:users].last.permitted?
end
@@ -315,8 +315,8 @@ class ParametersPermitTest < ActiveSupport::TestCase
end
test "to_unsafe_h returns unfiltered params even after accessing few keys" do
- params = ActionController::Parameters.new("f"=>{"language_facet"=>["Tibetan"]})
- expected = {"f"=>{"language_facet"=>["Tibetan"]}}
+ params = ActionController::Parameters.new("f"=>{ "language_facet"=>["Tibetan"] })
+ expected = { "f"=>{ "language_facet"=>["Tibetan"] } }
assert params["f"].is_a? ActionController::Parameters
assert_equal expected, params.to_unsafe_h
diff --git a/actionpack/test/controller/parameters/raise_on_unpermitted_params_test.rb b/actionpack/test/controller/parameters/raise_on_unpermitted_params_test.rb
index bcb16eaf89..8fab7b28e9 100644
--- a/actionpack/test/controller/parameters/raise_on_unpermitted_params_test.rb
+++ b/actionpack/test/controller/parameters/raise_on_unpermitted_params_test.rb
@@ -11,7 +11,8 @@ class RaiseOnUnpermittedParamsTest < ActiveSupport::TestCase
end
test "raises on unexpected params" do
- params = ActionController::Parameters.new( book: { pages: 65 },
+ params = ActionController::Parameters.new(
+ book: { pages: 65 },
fishing: "Turnips")
assert_raises(ActionController::UnpermittedParameters) do
@@ -20,7 +21,8 @@ class RaiseOnUnpermittedParamsTest < ActiveSupport::TestCase
end
test "raises on unexpected nested params" do
- params = ActionController::Parameters.new( book: { pages: 65, title: "Green Cats and where to find then." })
+ params = ActionController::Parameters.new(
+ book: { pages: 65, title: "Green Cats and where to find then." })
assert_raises(ActionController::UnpermittedParameters) do
params.permit(book: [:pages])
diff --git a/actionpack/test/controller/params_wrapper_test.rb b/actionpack/test/controller/params_wrapper_test.rb
index 7800ff26d0..1549405fe7 100644
--- a/actionpack/test/controller/params_wrapper_test.rb
+++ b/actionpack/test/controller/params_wrapper_test.rb
@@ -150,7 +150,7 @@ class ParamsWrapperTest < ActionController::TestCase
def test_no_double_wrap_if_key_exists
with_default_wrapper_options do
@request.env["CONTENT_TYPE"] = "application/json"
- post :parse, params: { "user" => { "username" => "sikachu" }}
+ post :parse, params: { "user" => { "username" => "sikachu" } }
assert_parameters("user" => { "username" => "sikachu" })
end
end
@@ -158,8 +158,8 @@ class ParamsWrapperTest < ActionController::TestCase
def test_nested_params
with_default_wrapper_options do
@request.env["CONTENT_TYPE"] = "application/json"
- post :parse, params: { "person" => { "username" => "sikachu" }}
- assert_parameters("person" => { "username" => "sikachu" }, "user" => {"person" => { "username" => "sikachu" }})
+ post :parse, params: { "person" => { "username" => "sikachu" } }
+ assert_parameters("person" => { "username" => "sikachu" }, "user" => { "person" => { "username" => "sikachu" } })
end
end
@@ -208,7 +208,7 @@ class ParamsWrapperTest < ActionController::TestCase
@request.env["CONTENT_TYPE"] = "application/json"
post :parse, params: {}
assert_parameters(
- "user" => { }
+ "user" => {}
)
end
end
diff --git a/actionpack/test/controller/redirect_test.rb b/actionpack/test/controller/redirect_test.rb
index 0539580e14..495e41ce76 100644
--- a/actionpack/test/controller/redirect_test.rb
+++ b/actionpack/test/controller/redirect_test.rb
@@ -33,7 +33,7 @@ class RedirectController < ActionController::Base
end
def redirect_with_status_hash
- redirect_to({action: "hello_world"}, status: 301)
+ redirect_to({ action: "hello_world" }, status: 301)
end
def redirect_with_protocol
@@ -118,7 +118,7 @@ class RedirectController < ActionController::Base
end
def redirect_to_with_block_and_options
- redirect_to proc { {action: "hello_world"} }
+ redirect_to proc { { action: "hello_world" } }
end
def redirect_with_header_break
diff --git a/actionpack/test/controller/render_json_test.rb b/actionpack/test/controller/render_json_test.rb
index 69fbf59905..213829bd9e 100644
--- a/actionpack/test/controller/render_json_test.rb
+++ b/actionpack/test/controller/render_json_test.rb
@@ -52,7 +52,7 @@ class RenderJsonTest < ActionController::TestCase
end
def render_json_with_render_to_string
- render json: {hello: render_to_string(partial: "partial")}
+ render json: { hello: render_to_string(partial: "partial") }
end
def render_json_with_extra_options
@@ -86,7 +86,6 @@ class RenderJsonTest < ActionController::TestCase
assert_equal "[]", @response.body
end
-
def test_render_json
get :render_json_hello_world
assert_equal '{"hello":"world"}', @response.body
diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb
index ba556c1bff..bf83131189 100644
--- a/actionpack/test/controller/render_test.rb
+++ b/actionpack/test/controller/render_test.rb
@@ -805,7 +805,7 @@ class HttpCacheForeverTest < ActionController::TestCase
tests HttpCacheForeverController
def test_cache_with_public
- get :cache_me_forever, params: {public: true}
+ get :cache_me_forever, params: { public: true }
assert_response :ok
assert_equal "max-age=#{100.years}, public", @response.headers["Cache-Control"]
assert_not_nil @response.etag
diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb
index 2e6b7be88b..90d5ab3c67 100644
--- a/actionpack/test/controller/request_forgery_protection_test.rb
+++ b/actionpack/test/controller/request_forgery_protection_test.rb
@@ -99,7 +99,6 @@ class PrependProtectForgeryBaseController < ActionController::Base
@called_callbacks << name
end
-
def custom_action
add_called_callback("custom_action")
end
@@ -399,7 +398,7 @@ module RequestForgeryProtectionTests
end
assert_cross_origin_not_blocked { get :same_origin_js, xhr: true }
- assert_cross_origin_not_blocked { get :same_origin_js, xhr: true, format: "js"}
+ assert_cross_origin_not_blocked { get :same_origin_js, xhr: true, format: "js" }
assert_cross_origin_not_blocked do
@request.accept = "text/javascript"
get :negotiate_same_origin, xhr: true
@@ -444,7 +443,7 @@ module RequestForgeryProtectionTests
assert_cross_origin_not_blocked { post :same_origin_js, params: { format: "js", custom_authenticity_token: @token } }
assert_cross_origin_not_blocked do
@request.accept = "text/javascript"
- post :negotiate_same_origin, params: { custom_authenticity_token: @token}
+ post :negotiate_same_origin, params: { custom_authenticity_token: @token }
end
end
@@ -614,7 +613,7 @@ class FreeCookieControllerTest < ActionController::TestCase
def test_should_allow_all_methods_without_token
SecureRandom.stub :base64, @token do
[:post, :patch, :put, :delete].each do |method|
- assert_nothing_raised { send(method, :index)}
+ assert_nothing_raised { send(method, :index) }
end
end
end
@@ -693,7 +692,7 @@ class PerFormTokensControllerTest < ActionController::TestCase
# This is required because PATH_INFO isn't reset between requests.
@request.env["PATH_INFO"] = "/per_form_tokens/post_one"
assert_nothing_raised do
- post :post_one, params: {custom_authenticity_token: form_token}
+ post :post_one, params: { custom_authenticity_token: form_token }
end
assert_response :success
end
@@ -708,7 +707,7 @@ class PerFormTokensControllerTest < ActionController::TestCase
# This is required because PATH_INFO isn't reset between requests.
@request.env["PATH_INFO"] = "/per_form_tokens/post_two"
assert_raises(ActionController::InvalidAuthenticityToken) do
- post :post_two, params: {custom_authenticity_token: form_token}
+ post :post_two, params: { custom_authenticity_token: form_token }
end
end
@@ -722,7 +721,7 @@ class PerFormTokensControllerTest < ActionController::TestCase
# This is required because PATH_INFO isn't reset between requests.
@request.env["PATH_INFO"] = "/per_form_tokens/post_one"
assert_raises(ActionController::InvalidAuthenticityToken) do
- patch :post_one, params: {custom_authenticity_token: form_token}
+ patch :post_one, params: { custom_authenticity_token: form_token }
end
end
@@ -778,13 +777,13 @@ class PerFormTokensControllerTest < ActionController::TestCase
# This is required because PATH_INFO isn't reset between requests.
@request.env["PATH_INFO"] = "/per_form_tokens/post_one"
assert_nothing_raised do
- post :post_one, params: {custom_authenticity_token: token}
+ post :post_one, params: { custom_authenticity_token: token }
end
assert_response :success
end
def test_ignores_params
- get :index, params: {form_path: "/per_form_tokens/post_one?foo=bar"}
+ get :index, params: { form_path: "/per_form_tokens/post_one?foo=bar" }
form_token = assert_presence_and_fetch_form_csrf_token
@@ -793,33 +792,33 @@ class PerFormTokensControllerTest < ActionController::TestCase
# This is required because PATH_INFO isn't reset between requests.
@request.env["PATH_INFO"] = "/per_form_tokens/post_one?foo=baz"
assert_nothing_raised do
- post :post_one, params: {custom_authenticity_token: form_token, baz: "foo"}
+ post :post_one, params: { custom_authenticity_token: form_token, baz: "foo" }
end
assert_response :success
end
def test_ignores_trailing_slash_during_generation
- get :index, params: {form_path: "/per_form_tokens/post_one/"}
+ get :index, params: { form_path: "/per_form_tokens/post_one/" }
form_token = assert_presence_and_fetch_form_csrf_token
# This is required because PATH_INFO isn't reset between requests.
@request.env["PATH_INFO"] = "/per_form_tokens/post_one"
assert_nothing_raised do
- post :post_one, params: {custom_authenticity_token: form_token}
+ post :post_one, params: { custom_authenticity_token: form_token }
end
assert_response :success
end
def test_ignores_origin_during_generation
- get :index, params: {form_path: "https://example.com/per_form_tokens/post_one/"}
+ get :index, params: { form_path: "https://example.com/per_form_tokens/post_one/" }
form_token = assert_presence_and_fetch_form_csrf_token
# This is required because PATH_INFO isn't reset between requests.
@request.env["PATH_INFO"] = "/per_form_tokens/post_one"
assert_nothing_raised do
- post :post_one, params: {custom_authenticity_token: form_token}
+ post :post_one, params: { custom_authenticity_token: form_token }
end
assert_response :success
end
@@ -832,19 +831,19 @@ class PerFormTokensControllerTest < ActionController::TestCase
# This is required because PATH_INFO isn't reset between requests.
@request.env["PATH_INFO"] = "/per_form_tokens/post_one/"
assert_nothing_raised do
- post :post_one, params: {custom_authenticity_token: form_token}
+ post :post_one, params: { custom_authenticity_token: form_token }
end
assert_response :success
end
def test_method_is_case_insensitive
- get :index, params: {form_method: "POST"}
+ get :index, params: { form_method: "POST" }
form_token = assert_presence_and_fetch_form_csrf_token
# This is required because PATH_INFO isn't reset between requests.
@request.env["PATH_INFO"] = "/per_form_tokens/post_one/"
assert_nothing_raised do
- post :post_one, params: {custom_authenticity_token: form_token}
+ post :post_one, params: { custom_authenticity_token: form_token }
end
assert_response :success
end
diff --git a/actionpack/test/controller/required_params_test.rb b/actionpack/test/controller/required_params_test.rb
index c9b0ac874d..315d1ff3e8 100644
--- a/actionpack/test/controller/required_params_test.rb
+++ b/actionpack/test/controller/required_params_test.rb
@@ -49,7 +49,7 @@ class ParametersRequireTest < ActiveSupport::TestCase
end
test "require array when all required params are present" do
- safe_params = ActionController::Parameters.new(person: {first_name: "Gaurish", title: "Mjallo", city: "Barcelona"})
+ safe_params = ActionController::Parameters.new(person: { first_name: "Gaurish", title: "Mjallo", city: "Barcelona" })
.require(:person)
.require([:first_name, :title])
@@ -59,7 +59,7 @@ class ParametersRequireTest < ActiveSupport::TestCase
test "require array when a required param is missing" do
assert_raises(ActionController::ParameterMissing) do
- ActionController::Parameters.new(person: {first_name: "Gaurish", title: nil})
+ ActionController::Parameters.new(person: { first_name: "Gaurish", title: nil })
.require(:person)
.require([:first_name, :title])
end
diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb
index 6cb4b83208..29471939d0 100644
--- a/actionpack/test/controller/resources_test.rb
+++ b/actionpack/test/controller/resources_test.rb
@@ -28,7 +28,7 @@ class ResourcesTest < ActionController::TestCase
def test_override_paths_for_member_and_collection_methods
collection_methods = { rss: :get, reorder: :post, csv: :post }
member_methods = { rss: :get, atom: :get, upload: :post, fix: :post }
- path_names = {new: "nuevo", rss: "canal", fix: "corrigir" }
+ path_names = { new: "nuevo", rss: "canal", fix: "corrigir" }
with_restful_routing :messages,
collection: collection_methods,
@@ -77,7 +77,7 @@ class ResourcesTest < ActionController::TestCase
end
def test_multiple_resources_with_options
- expected_options = {controller: "threads", action: "index"}
+ expected_options = { controller: "threads", action: "index" }
with_restful_routing :messages, :comments, expected_options.slice(:controller) do
assert_recognizes(expected_options, path: "comments")
@@ -92,7 +92,7 @@ class ResourcesTest < ActionController::TestCase
end
def test_irregular_id_with_no_constraints_should_raise_error
- expected_options = {controller: "messages", action: "show", id: "1.1.1"}
+ expected_options = { controller: "messages", action: "show", id: "1.1.1" }
with_restful_routing :messages do
assert_raise(Assertion) do
@@ -102,24 +102,24 @@ class ResourcesTest < ActionController::TestCase
end
def test_irregular_id_with_constraints_should_pass
- expected_options = {controller: "messages", action: "show", id: "1.1.1"}
+ expected_options = { controller: "messages", action: "show", id: "1.1.1" }
- with_restful_routing(:messages, constraints: {id: /[0-9]\.[0-9]\.[0-9]/}) do
+ with_restful_routing(:messages, constraints: { id: /[0-9]\.[0-9]\.[0-9]/ }) do
assert_recognizes(expected_options, path: "messages/1.1.1", method: :get)
end
end
def test_with_path_prefix_constraints
- expected_options = {controller: "messages", action: "show", thread_id: "1.1.1", id: "1"}
- with_restful_routing :messages, path_prefix: "/thread/:thread_id", constraints: {thread_id: /[0-9]\.[0-9]\.[0-9]/} do
+ expected_options = { controller: "messages", action: "show", thread_id: "1.1.1", id: "1" }
+ with_restful_routing :messages, path_prefix: "/thread/:thread_id", constraints: { thread_id: /[0-9]\.[0-9]\.[0-9]/ } do
assert_recognizes(expected_options, path: "thread/1.1.1/messages/1", method: :get)
end
end
def test_irregular_id_constraints_should_get_passed_to_member_actions
- expected_options = {controller: "messages", action: "custom", id: "1.1.1"}
+ expected_options = { controller: "messages", action: "custom", id: "1.1.1" }
- with_restful_routing(:messages, member: {custom: :get}, constraints: {id: /[0-9]\.[0-9]\.[0-9]/}) do
+ with_restful_routing(:messages, member: { custom: :get }, constraints: { id: /[0-9]\.[0-9]\.[0-9]/ }) do
assert_recognizes(expected_options, path: "messages/1.1.1/custom", method: :get)
end
end
@@ -261,7 +261,7 @@ class ResourcesTest < ActionController::TestCase
def test_with_member_action
[:patch, :put, :post].each do |method|
with_restful_routing :messages, member: { mark: method } do
- mark_options = {action: "mark", id: "1"}
+ mark_options = { action: "mark", id: "1" }
mark_path = "/messages/1/mark"
assert_restful_routes_for :messages do |options|
assert_recognizes(options.merge(mark_options), path: mark_path, method: method)
@@ -275,24 +275,24 @@ class ResourcesTest < ActionController::TestCase
end
def test_with_member_action_and_requirement
- expected_options = {controller: "messages", action: "mark", id: "1.1.1"}
+ expected_options = { controller: "messages", action: "mark", id: "1.1.1" }
- with_restful_routing(:messages, constraints: {id: /[0-9]\.[0-9]\.[0-9]/}, member: { mark: :get }) do
+ with_restful_routing(:messages, constraints: { id: /[0-9]\.[0-9]\.[0-9]/ }, member: { mark: :get }) do
assert_recognizes(expected_options, path: "messages/1.1.1/mark", method: :get)
end
end
def test_member_when_override_paths_for_default_restful_actions_with
[:patch, :put, :post].each do |method|
- with_restful_routing :messages, member: { mark: method }, path_names: {new: "nuevo"} do
- mark_options = {action: "mark", id: "1", controller: "messages"}
+ with_restful_routing :messages, member: { mark: method }, path_names: { new: "nuevo" } do
+ mark_options = { action: "mark", id: "1", controller: "messages" }
mark_path = "/messages/1/mark"
- assert_restful_routes_for :messages, path_names: {new: "nuevo"} do |options|
+ assert_restful_routes_for :messages, path_names: { new: "nuevo" } do |options|
assert_recognizes(options.merge(mark_options), path: mark_path, method: method)
end
- assert_restful_named_routes_for :messages, path_names: {new: "nuevo"} do
+ assert_restful_named_routes_for :messages, path_names: { new: "nuevo" } do
assert_named_route mark_path, :mark_message_path, mark_options
end
end
@@ -312,7 +312,7 @@ class ResourcesTest < ActionController::TestCase
end
%w(mark unmark).each do |action|
- action_options = {action: action, id: "1"}
+ action_options = { action: action, id: "1" }
action_path = "/messages/1/#{action}"
assert_restful_routes_for :messages do |options|
assert_recognizes(options.merge(action_options), path: action_path, method: method)
@@ -359,7 +359,7 @@ class ResourcesTest < ActionController::TestCase
end
end
- preview_options = {action: "preview"}
+ preview_options = { action: "preview" }
preview_path = "/messages/new/preview"
assert_restful_routes_for :messages do |options|
assert_recognizes(options.merge(preview_options), path: preview_path, method: :post)
@@ -381,7 +381,7 @@ class ResourcesTest < ActionController::TestCase
end
end
- preview_options = {action: "preview", thread_id: "1"}
+ preview_options = { action: "preview", thread_id: "1" }
preview_path = "/threads/1/messages/new/preview"
assert_restful_routes_for :messages, path_prefix: "threads/1/", name_prefix: "thread_", options: { thread_id: "1" } do |options|
assert_recognizes(options.merge(preview_options), path: preview_path, method: :post)
@@ -403,7 +403,7 @@ class ResourcesTest < ActionController::TestCase
end
end
- preview_options = {action: "preview", thread_id: "1", format: "xml"}
+ preview_options = { action: "preview", thread_id: "1", format: "xml" }
preview_path = "/threads/1/messages/new/preview.xml"
assert_restful_routes_for :messages, path_prefix: "threads/1/", name_prefix: "thread_", options: { thread_id: "1" } do |options|
assert_recognizes(options.merge(preview_options), path: preview_path, method: :post)
@@ -561,7 +561,7 @@ class ResourcesTest < ActionController::TestCase
end
end
- reset_options = {action: "reset"}
+ reset_options = { action: "reset" }
reset_path = "/account/reset"
assert_singleton_routes_for :account do |options|
assert_recognizes(options.merge(reset_options), path: reset_path, method: method)
@@ -585,7 +585,7 @@ class ResourcesTest < ActionController::TestCase
end
%w(reset disable).each do |action|
- action_options = {action: action}
+ action_options = { action: action }
action_path = "/account/#{action}"
assert_singleton_routes_for :account do |options|
assert_recognizes(options.merge(action_options), path: action_path, method: method)
@@ -743,7 +743,7 @@ class ResourcesTest < ActionController::TestCase
end
end
- assert_simply_restful_for :images, controller: "backoffice/images", name_prefix: "backoffice_product_", path_prefix: "backoffice/products/1/", options: {product_id: "1"}
+ assert_simply_restful_for :images, controller: "backoffice/images", name_prefix: "backoffice_product_", path_prefix: "backoffice/products/1/", options: { product_id: "1" }
end
end
@@ -759,15 +759,15 @@ class ResourcesTest < ActionController::TestCase
end
end
- assert_simply_restful_for :images, controller: "backoffice/admin/images", name_prefix: "backoffice_admin_product_", path_prefix: "backoffice/admin/products/1/", options: {product_id: "1"}
+ assert_simply_restful_for :images, controller: "backoffice/admin/images", name_prefix: "backoffice_admin_product_", path_prefix: "backoffice/admin/products/1/", options: { product_id: "1" }
end
end
def test_with_path_segment
with_restful_routing :messages do
assert_simply_restful_for :messages
- assert_recognizes({controller: "messages", action: "index"}, "/messages")
- assert_recognizes({controller: "messages", action: "index"}, "/messages/")
+ assert_recognizes({ controller: "messages", action: "index" }, "/messages")
+ assert_recognizes({ controller: "messages", action: "index" }, "/messages/")
end
with_routing do |set|
@@ -775,8 +775,8 @@ class ResourcesTest < ActionController::TestCase
resources :messages, path: "reviews"
end
assert_simply_restful_for :messages, as: "reviews"
- assert_recognizes({controller: "messages", action: "index"}, "/reviews")
- assert_recognizes({controller: "messages", action: "index"}, "/reviews/")
+ assert_recognizes({ controller: "messages", action: "index" }, "/reviews")
+ assert_recognizes({ controller: "messages", action: "index" }, "/reviews/")
end
end
@@ -791,13 +791,13 @@ class ResourcesTest < ActionController::TestCase
end
end
- assert_simply_restful_for :product_reviews, controller: "messages", as: "reviews", name_prefix: "product_", path_prefix: "products/1/", options: {product_id: "1"}
- assert_simply_restful_for :tutor_reviews,controller: "comments", as: "reviews", name_prefix: "tutor_", path_prefix: "tutors/1/", options: {tutor_id: "1"}
+ assert_simply_restful_for :product_reviews, controller: "messages", as: "reviews", name_prefix: "product_", path_prefix: "products/1/", options: { product_id: "1" }
+ assert_simply_restful_for :tutor_reviews,controller: "comments", as: "reviews", name_prefix: "tutor_", path_prefix: "tutors/1/", options: { tutor_id: "1" }
end
end
def test_with_path_segment_path_prefix_constraints
- expected_options = {controller: "messages", action: "show", thread_id: "1.1.1", id: "1"}
+ expected_options = { controller: "messages", action: "show", thread_id: "1.1.1", id: "1" }
with_routing do |set|
set.draw do
scope "/thread/:thread_id", constraints: { thread_id: /[0-9]\.[0-9]\.[0-9]/ } do
@@ -1125,7 +1125,7 @@ class ResourcesTest < ActionController::TestCase
def with_singleton_resources(*args)
with_routing do |set|
- set.draw {resource(*args) }
+ set.draw { resource(*args) }
yield
end
end
@@ -1313,8 +1313,8 @@ class ResourcesTest < ActionController::TestCase
def assert_resource_methods(expected, resource, action_method, method)
assert_equal expected.length, resource.send("#{action_method}_methods")[method].size, "#{resource.send("#{action_method}_methods")[method].inspect}"
expected.each do |action|
- assert resource.send("#{action_method}_methods")[method].include?(action)
- "#{method} not in #{action_method} methods: #{resource.send("#{action_method}_methods")[method].inspect}"
+ assert resource.send("#{action_method}_methods")[method].include?(action),
+ "#{method} not in #{action_method} methods: #{resource.send("#{action_method}_methods")[method].inspect}"
end
end
diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb
index 05293dd94c..d1cc0f7d68 100644
--- a/actionpack/test/controller/routing_test.rb
+++ b/actionpack/test/controller/routing_test.rb
@@ -29,7 +29,8 @@ class UriReservedCharactersRoutingTest < ActiveSupport::TestCase
def test_route_generation_escapes_unsafe_path_characters
assert_equal "/content/act#{@escaped}ion/var#{@escaped}iable/add#{@escaped}itional-1/add#{@escaped}itional-2",
- url_for(@set, controller: "content",
+ url_for(@set,
+ controller: "content",
action: "act#{@segment}ion",
variable: "var#{@segment}iable",
additional: ["add#{@segment}itional-1", "add#{@segment}itional-2"])
@@ -45,7 +46,8 @@ class UriReservedCharactersRoutingTest < ActiveSupport::TestCase
def test_route_generation_allows_passing_non_string_values_to_generated_helper
assert_equal "/content/action/variable/1/2",
- url_for(@set, controller: "content",
+ url_for(@set,
+ controller: "content",
action: "action",
variable: "variable",
additional: [1, 2])
@@ -89,7 +91,7 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
end
hash = ActiveSupport::JSON.decode get(URI("http://example.org/journey/faithfully-omg"))
- assert_equal({"artist"=>"journey", "song"=>"faithfully"}, hash)
+ assert_equal({ "artist"=>"journey", "song"=>"faithfully" }, hash)
end
def test_id_with_dash
@@ -101,7 +103,7 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
end
hash = ActiveSupport::JSON.decode get(URI("http://example.org/journey/faithfully-omg"))
- assert_equal({"id"=>"faithfully-omg"}, hash)
+ assert_equal({ "id"=>"faithfully-omg" }, hash)
end
def test_dash_with_custom_regexp
@@ -113,7 +115,7 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
end
hash = ActiveSupport::JSON.decode get(URI("http://example.org/journey/123-omg"))
- assert_equal({"artist"=>"journey", "song"=>"123"}, hash)
+ assert_equal({ "artist"=>"journey", "song"=>"123" }, hash)
assert_equal "Not Found", get(URI("http://example.org/journey/faithfully-omg"))
end
@@ -126,7 +128,7 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
end
hash = ActiveSupport::JSON.decode get(URI("http://example.org/journey/omg-faithfully"))
- assert_equal({"artist"=>"journey", "song"=>"faithfully"}, hash)
+ assert_equal({ "artist"=>"journey", "song"=>"faithfully" }, hash)
end
def test_pre_dash_with_custom_regexp
@@ -138,7 +140,7 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
end
hash = ActiveSupport::JSON.decode get(URI("http://example.org/journey/omg-123"))
- assert_equal({"artist"=>"journey", "song"=>"123"}, hash)
+ assert_equal({ "artist"=>"journey", "song"=>"123" }, hash)
assert_equal "Not Found", get(URI("http://example.org/journey/omg-faithfully"))
end
@@ -284,7 +286,7 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
}
end
assert_equal "foo", get(URI("http://example.org/posts/1/foo.js"))
- assert_equal({id: "1", filters: "foo", format: "js"}, params)
+ assert_equal({ id: "1", filters: "foo", format: "js" }, params)
end
def test_specific_controller_action_failure
@@ -299,11 +301,11 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
def test_default_setup
rs.draw { ActiveSupport::Deprecation.silence { get "/:controller(/:action(/:id))" } }
- assert_equal({controller: "content", action: "index"}, rs.recognize_path("/content"))
- assert_equal({controller: "content", action: "list"}, rs.recognize_path("/content/list"))
- assert_equal({controller: "content", action: "show", id: "10"}, rs.recognize_path("/content/show/10"))
+ assert_equal({ controller: "content", action: "index" }, rs.recognize_path("/content"))
+ assert_equal({ controller: "content", action: "list" }, rs.recognize_path("/content/list"))
+ assert_equal({ controller: "content", action: "show", id: "10" }, rs.recognize_path("/content/show/10"))
- assert_equal({controller: "admin/user", action: "show", id: "10"}, rs.recognize_path("/admin/user/show/10"))
+ assert_equal({ controller: "admin/user", action: "show", id: "10" }, rs.recognize_path("/admin/user/show/10"))
assert_equal "/admin/user/show/10", url_for(rs, controller: "admin/user", action: "show", id: 10)
@@ -328,7 +330,7 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
get ":url", controller: "content", action: "translate"
end
- assert_equal({controller: "content", action: "translate", url: "example"}, rs.recognize_path("/example"))
+ assert_equal({ controller: "content", action: "translate", url: "example" }, rs.recognize_path("/example"))
end
def test_route_with_regexp_for_action
@@ -349,9 +351,9 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
end
end
- assert_equal({controller: "admin/user", admintoken: "foo", action: "index"},
+ assert_equal({ controller: "admin/user", admintoken: "foo", action: "index" },
rs.recognize_path("/admin/user/foo"))
- assert_equal({controller: "content", action: "foo"},
+ assert_equal({ controller: "content", action: "foo" },
rs.recognize_path("/content/foo"))
assert_equal "/admin/user/foo", url_for(rs, controller: "admin/user", admintoken: "foo", action: "index")
@@ -364,8 +366,8 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
get "/:controller(/:action(/:id))", controller: /admin\/(accounts|users)/
end
end
- assert_equal({controller: "admin/accounts", action: "index"}, rs.recognize_path("/admin/accounts"))
- assert_equal({controller: "admin/users", action: "index"}, rs.recognize_path("/admin/users"))
+ assert_equal({ controller: "admin/accounts", action: "index" }, rs.recognize_path("/admin/accounts"))
+ assert_equal({ controller: "admin/users", action: "index" }, rs.recognize_path("/admin/users"))
assert_raise(ActionController::RoutingError) { rs.recognize_path("/admin/products") }
end
@@ -375,22 +377,22 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
get ":controller/:action/:file",
controller: /admin|user/,
action: /upload|download/,
- defaults: {file: nil},
- constraints: {file: %r{[^/]+(\.[^/]+)?}}
+ defaults: { file: nil },
+ constraints: { file: %r{[^/]+(\.[^/]+)?} }
end
end
# Without a file extension
assert_equal "/user/download/file",
url_for(rs, controller: "user", action: "download", file: "file")
- assert_equal({controller: "user", action: "download", file: "file"},
+ assert_equal({ controller: "user", action: "download", file: "file" },
rs.recognize_path("/user/download/file"))
# Now, let's try a file with an extension, really a dot (.)
assert_equal "/user/download/file.jpg",
url_for(rs, controller: "user", action: "download", file: "file.jpg")
- assert_equal({controller: "user", action: "download", file: "file.jpg"},
+ assert_equal({ controller: "user", action: "download", file: "file.jpg" },
rs.recognize_path("/user/download/file.jpg"))
end
@@ -601,7 +603,7 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
end
get URI("http://test.host/pages/boo")
- assert_equal({controller: "content", action: "show_file", path: "pages/boo"},
+ assert_equal({ controller: "content", action: "show_file", path: "pages/boo" },
controller.request.path_parameters)
assert_equal "/pages/boo",
@@ -636,9 +638,9 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
assert_equal "/page", url_for(rs, controller: "content", action: "show_page", id: "1")
assert_equal "/page/10", url_for(rs, controller: "content", action: "show_page", id: 10)
- assert_equal({controller: "content", action: "show_page", id: 1 }, rs.recognize_path("/page"))
- assert_equal({controller: "content", action: "show_page", id: "1"}, rs.recognize_path("/page/1"))
- assert_equal({controller: "content", action: "show_page", id: "10"}, rs.recognize_path("/page/10"))
+ assert_equal({ controller: "content", action: "show_page", id: 1 }, rs.recognize_path("/page"))
+ assert_equal({ controller: "content", action: "show_page", id: "1" }, rs.recognize_path("/page/1"))
+ assert_equal({ controller: "content", action: "show_page", id: "10" }, rs.recognize_path("/page/10"))
end
# For newer revision
@@ -670,7 +672,7 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
def test_requirement_should_prevent_optional_id
rs.draw do
- get "post/:id" => "post#show", :constraints => {id: /\d+/}, :as => "post"
+ get "post/:id" => "post#show", :constraints => { id: /\d+/ }, :as => "post"
end
assert_equal "/post/10", url_for(rs, controller: "post", action: "show", id: 10)
@@ -776,7 +778,8 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
end
end
- assert_equal "/journal", url_for(rs, controller: "content",
+ assert_equal "/journal", url_for(rs,
+ controller: "content",
action: "list_journal",
date: nil,
user_id: nil)
@@ -1108,8 +1111,8 @@ class RouteSetTest < ActiveSupport::TestCase
assert_equal "/users/show/10", url_for(set, controller: "users", action: "show", id: 10)
assert_equal "/users/index/10", url_for(set, controller: "users", id: 10)
- assert_equal({controller: "users", action: "index", id: "10"}, set.recognize_path("/users/index/10"))
- assert_equal({controller: "users", action: "index", id: "10"}, set.recognize_path("/users/index/10/"))
+ assert_equal({ controller: "users", action: "index", id: "10" }, set.recognize_path("/users/index/10"))
+ assert_equal({ controller: "users", action: "index", id: "10" }, set.recognize_path("/users/index/10/"))
end
def test_route_with_parameter_shell
@@ -1121,12 +1124,12 @@ class RouteSetTest < ActiveSupport::TestCase
end
end
- assert_equal({controller: "pages", action: "index"}, request_path_params("/pages"))
- assert_equal({controller: "pages", action: "index"}, request_path_params("/pages/index"))
- assert_equal({controller: "pages", action: "list"}, request_path_params("/pages/list"))
+ assert_equal({ controller: "pages", action: "index" }, request_path_params("/pages"))
+ assert_equal({ controller: "pages", action: "index" }, request_path_params("/pages/index"))
+ assert_equal({ controller: "pages", action: "list" }, request_path_params("/pages/list"))
- assert_equal({controller: "pages", action: "show", id: "10"}, request_path_params("/pages/show/10"))
- assert_equal({controller: "pages", action: "show", id: "10"}, request_path_params("/page/10"))
+ assert_equal({ controller: "pages", action: "show", id: "10" }, request_path_params("/pages/show/10"))
+ assert_equal({ controller: "pages", action: "show", id: "10" }, request_path_params("/page/10"))
end
def test_route_constraints_on_request_object_with_anchors_are_valid
@@ -1186,8 +1189,8 @@ class RouteSetTest < ActiveSupport::TestCase
get "page/:id" => "pages#show", :id => /[a-zA-Z0-9\+]+/
end
- assert_equal({controller: "pages", action: "show", id: "10"}, request_path_params("/page/10"))
- assert_equal({controller: "pages", action: "show", id: "hello+world"}, request_path_params("/page/hello+world"))
+ assert_equal({ controller: "pages", action: "show", id: "10" }, request_path_params("/page/10"))
+ assert_equal({ controller: "pages", action: "show", id: "hello+world" }, request_path_params("/page/hello+world"))
end
def test_recognize_with_http_methods
@@ -1497,7 +1500,7 @@ class RouteSetTest < ActiveSupport::TestCase
end
get URI("http://test.host/posts.xml")
- assert_equal({controller: "posts", action: "index", format: "xml"},
+ assert_equal({ controller: "posts", action: "index", format: "xml" },
controller.request.path_parameters)
assert_equal "/posts", controller.url_for(
@@ -1588,12 +1591,12 @@ class RouteSetTest < ActiveSupport::TestCase
def test_route_with_subdomain_and_constraints_must_receive_params
name_param = nil
set.draw do
- get "page/:name" => "pages#show", :constraints => lambda {|request|
+ get "page/:name" => "pages#show", :constraints => lambda { |request|
name_param = request.params[:name]
return true
}
end
- assert_equal({controller: "pages", action: "show", name: "mypage"},
+ assert_equal({ controller: "pages", action: "show", name: "mypage" },
set.recognize_path("http://subdomain.example.org/page/mypage"))
assert_equal(name_param, "mypage")
end
@@ -1601,19 +1604,19 @@ class RouteSetTest < ActiveSupport::TestCase
def test_route_requirement_recognize_with_ignore_case
set.draw do
get "page/:name" => "pages#show",
- :constraints => {name: /(david|jamis)/i}
+ :constraints => { name: /(david|jamis)/i }
end
- assert_equal({controller: "pages", action: "show", name: "jamis"}, set.recognize_path("/page/jamis"))
+ assert_equal({ controller: "pages", action: "show", name: "jamis" }, set.recognize_path("/page/jamis"))
assert_raise ActionController::RoutingError do
set.recognize_path("/page/davidjamis")
end
- assert_equal({controller: "pages", action: "show", name: "DAVID"}, set.recognize_path("/page/DAVID"))
+ assert_equal({ controller: "pages", action: "show", name: "DAVID" }, set.recognize_path("/page/DAVID"))
end
def test_route_requirement_generate_with_ignore_case
set.draw do
get "page/:name" => "pages#show",
- :constraints => {name: /(david|jamis)/i}
+ :constraints => { name: /(david|jamis)/i }
end
url = url_for(set, controller: "pages", action: "show", name: "david")
@@ -1628,15 +1631,15 @@ class RouteSetTest < ActiveSupport::TestCase
def test_route_requirement_recognize_with_extended_syntax
set.draw do
get "page/:name" => "pages#show",
- :constraints => {name: / # Desperately overcommented regexp
+ :constraints => { name: / # Desperately overcommented regexp
( #Either
david #The Creator
| #Or
jamis #The Deployer
- )/x}
+ )/x }
end
- assert_equal({controller: "pages", action: "show", name: "jamis"}, set.recognize_path("/page/jamis"))
- assert_equal({controller: "pages", action: "show", name: "david"}, set.recognize_path("/page/david"))
+ assert_equal({ controller: "pages", action: "show", name: "jamis" }, set.recognize_path("/page/jamis"))
+ assert_equal({ controller: "pages", action: "show", name: "david" }, set.recognize_path("/page/david"))
assert_raise ActionController::RoutingError do
set.recognize_path("/page/david #The Creator")
end
@@ -1648,15 +1651,15 @@ class RouteSetTest < ActiveSupport::TestCase
def test_route_requirement_with_xi_modifiers
set.draw do
get "page/:name" => "pages#show",
- :constraints => {name: / # Desperately overcommented regexp
+ :constraints => { name: / # Desperately overcommented regexp
( #Either
david #The Creator
| #Or
jamis #The Deployer
- )/xi}
+ )/xi }
end
- assert_equal({controller: "pages", action: "show", name: "JAMIS"},
+ assert_equal({ controller: "pages", action: "show", name: "JAMIS" },
set.recognize_path("/page/JAMIS"))
assert_equal "/page/JAMIS",
@@ -1668,8 +1671,8 @@ class RouteSetTest < ActiveSupport::TestCase
get "unnamed", controller: :pages, action: :show, name: :as_symbol
get "named" , controller: :pages, action: :show, name: :as_symbol, as: :named
end
- assert_equal({controller: "pages", action: "show", name: :as_symbol}, set.recognize_path("/unnamed"))
- assert_equal({controller: "pages", action: "show", name: :as_symbol}, set.recognize_path("/named"))
+ assert_equal({ controller: "pages", action: "show", name: :as_symbol }, set.recognize_path("/unnamed"))
+ assert_equal({ controller: "pages", action: "show", name: :as_symbol }, set.recognize_path("/named"))
end
def test_regexp_chunk_should_add_question_mark_for_optionals
@@ -1681,8 +1684,8 @@ class RouteSetTest < ActiveSupport::TestCase
assert_equal "/", url_for(set, controller: "foo")
assert_equal "/hello", url_for(set, controller: "bar")
- assert_equal({controller: "foo", action: "index"}, set.recognize_path("/"))
- assert_equal({controller: "bar", action: "index"}, set.recognize_path("/hello"))
+ assert_equal({ controller: "foo", action: "index" }, set.recognize_path("/"))
+ assert_equal({ controller: "bar", action: "index" }, set.recognize_path("/hello"))
end
def test_assign_route_options_with_anchor_chars
@@ -1694,7 +1697,7 @@ class RouteSetTest < ActiveSupport::TestCase
assert_equal "/cars/buy/1/2", url_for(set, controller: "cars", action: "buy", person: "1", car: "2")
- assert_equal({controller: "cars", action: "buy", person: "1", car: "2"}, set.recognize_path("/cars/buy/1/2"))
+ assert_equal({ controller: "cars", action: "buy", person: "1", car: "2" }, set.recognize_path("/cars/buy/1/2"))
end
def test_segmentation_of_dot_path
@@ -1706,7 +1709,7 @@ class RouteSetTest < ActiveSupport::TestCase
assert_equal "/books/list.rss", url_for(set, controller: "books", action: "list")
- assert_equal({controller: "books", action: "list"}, set.recognize_path("/books/list.rss"))
+ assert_equal({ controller: "books", action: "list" }, set.recognize_path("/books/list.rss"))
end
def test_segmentation_of_dynamic_dot_path
@@ -1721,10 +1724,10 @@ class RouteSetTest < ActiveSupport::TestCase
assert_equal "/books/list", url_for(set, controller: "books", action: "list")
assert_equal "/books", url_for(set, controller: "books", action: "index")
- assert_equal({controller: "books", action: "list", format: "rss"}, set.recognize_path("/books/list.rss"))
- assert_equal({controller: "books", action: "list", format: "xml"}, set.recognize_path("/books/list.xml"))
- assert_equal({controller: "books", action: "list"}, set.recognize_path("/books/list"))
- assert_equal({controller: "books", action: "index"}, set.recognize_path("/books"))
+ assert_equal({ controller: "books", action: "list", format: "rss" }, set.recognize_path("/books/list.rss"))
+ assert_equal({ controller: "books", action: "list", format: "xml" }, set.recognize_path("/books/list.xml"))
+ assert_equal({ controller: "books", action: "list" }, set.recognize_path("/books/list"))
+ assert_equal({ controller: "books", action: "index" }, set.recognize_path("/books"))
end
def test_slashes_are_implied
@@ -1734,14 +1737,14 @@ class RouteSetTest < ActiveSupport::TestCase
assert_equal "/content/list", url_for(set, controller: "content", action: "list")
assert_equal "/content/show/1", url_for(set, controller: "content", action: "show", id: "1")
- assert_equal({controller: "content", action: "index"}, set.recognize_path("/content"))
- assert_equal({controller: "content", action: "index"}, set.recognize_path("/content/index"))
- assert_equal({controller: "content", action: "list"}, set.recognize_path("/content/list"))
- assert_equal({controller: "content", action: "show", id: "1"}, set.recognize_path("/content/show/1"))
+ assert_equal({ controller: "content", action: "index" }, set.recognize_path("/content"))
+ assert_equal({ controller: "content", action: "index" }, set.recognize_path("/content/index"))
+ assert_equal({ controller: "content", action: "list" }, set.recognize_path("/content/list"))
+ assert_equal({ controller: "content", action: "show", id: "1" }, set.recognize_path("/content/show/1"))
end
def test_default_route_recognition
- expected = {controller: "pages", action: "show", id: "10"}
+ expected = { controller: "pages", action: "show", id: "10" }
assert_equal expected, default_route_set.recognize_path("/pages/show/10")
assert_equal expected, default_route_set.recognize_path("/pages/show/10/")
@@ -1857,19 +1860,19 @@ class RouteSetTest < ActiveSupport::TestCase
controller.request.path_parameters
}
- assert_equal({controller: "blog", action: "index"}, recognize_path.("/blog"))
- assert_equal({controller: "blog", action: "show", id: "123"}, recognize_path.("/blog/show/123"))
- assert_equal({controller: "blog", action: "show_date", year: "2004", day: nil, month: nil }, recognize_path.("/blog/2004"))
- assert_equal({controller: "blog", action: "show_date", year: "2004", month: "12", day: nil }, recognize_path.("/blog/2004/12"))
- assert_equal({controller: "blog", action: "show_date", year: "2004", month: "12", day: "25"}, recognize_path.("/blog/2004/12/25"))
- assert_equal({controller: "articles", action: "edit", id: "123"}, recognize_path.("/blog/articles/edit/123"))
- assert_equal({controller: "articles", action: "show_stats"}, recognize_path.("/blog/articles/show_stats"))
- assert_equal({controller: "blog", action: "unknown_request", anything: "blog/wibble"}, recognize_path.("/blog/wibble"))
- assert_equal({controller: "blog", action: "unknown_request", anything: "junk"}, recognize_path.("/junk"))
+ assert_equal({ controller: "blog", action: "index" }, recognize_path.("/blog"))
+ assert_equal({ controller: "blog", action: "show", id: "123" }, recognize_path.("/blog/show/123"))
+ assert_equal({ controller: "blog", action: "show_date", year: "2004", day: nil, month: nil }, recognize_path.("/blog/2004"))
+ assert_equal({ controller: "blog", action: "show_date", year: "2004", month: "12", day: nil }, recognize_path.("/blog/2004/12"))
+ assert_equal({ controller: "blog", action: "show_date", year: "2004", month: "12", day: "25" }, recognize_path.("/blog/2004/12/25"))
+ assert_equal({ controller: "articles", action: "edit", id: "123" }, recognize_path.("/blog/articles/edit/123"))
+ assert_equal({ controller: "articles", action: "show_stats" }, recognize_path.("/blog/articles/show_stats"))
+ assert_equal({ controller: "blog", action: "unknown_request", anything: "blog/wibble" }, recognize_path.("/blog/wibble"))
+ assert_equal({ controller: "blog", action: "unknown_request", anything: "junk" }, recognize_path.("/junk"))
get URI("http://example.org/blog/2006/07/28")
- assert_equal({controller: "blog", action: "show_date", year: "2006", month: "07", day: "28"}, controller.request.path_parameters)
+ assert_equal({ controller: "blog", action: "show_date", year: "2006", month: "07", day: "28" }, controller.request.path_parameters)
assert_equal("/blog/2006/07/25", controller.url_for(day: 25, only_path: true))
assert_equal("/blog/2005", controller.url_for(year: 2005, only_path: true))
assert_equal("/blog/show/123", controller.url_for(action: "show" , id: 123, only_path: true))
@@ -1963,76 +1966,76 @@ class RackMountIntegrationTests < ActiveSupport::TestCase
end
def test_recognize_path
- assert_equal({controller: "admin/users", action: "index"}, @routes.recognize_path("/admin/users", method: :get))
- assert_equal({controller: "admin/users", action: "create"}, @routes.recognize_path("/admin/users", method: :post))
- assert_equal({controller: "admin/users", action: "new"}, @routes.recognize_path("/admin/users/new", method: :get))
- assert_equal({controller: "admin/users", action: "show", id: "1"}, @routes.recognize_path("/admin/users/1", method: :get))
- assert_equal({controller: "admin/users", action: "update", id: "1"}, @routes.recognize_path("/admin/users/1", method: :put))
- assert_equal({controller: "admin/users", action: "destroy", id: "1"}, @routes.recognize_path("/admin/users/1", method: :delete))
- assert_equal({controller: "admin/users", action: "edit", id: "1"}, @routes.recognize_path("/admin/users/1/edit", method: :get))
-
- assert_equal({controller: "admin/posts", action: "index"}, @routes.recognize_path("/admin/posts", method: :get))
- assert_equal({controller: "admin/posts", action: "new"}, @routes.recognize_path("/admin/posts/new", method: :get))
-
- assert_equal({controller: "api/users", action: "index"}, @routes.recognize_path("/api", method: :get))
- assert_equal({controller: "api/users", action: "index"}, @routes.recognize_path("/api/", method: :get))
-
- assert_equal({controller: "posts", action: "show_date", year: "2009", month: nil, day: nil }, @routes.recognize_path("/blog/2009", method: :get))
- assert_equal({controller: "posts", action: "show_date", year: "2009", month: "01", day: nil }, @routes.recognize_path("/blog/2009/01", method: :get))
- assert_equal({controller: "posts", action: "show_date", year: "2009", month: "01", day: "01"}, @routes.recognize_path("/blog/2009/01/01", method: :get))
-
- assert_equal({controller: "archive", action: "index", year: "2010"}, @routes.recognize_path("/archive/2010"))
- assert_equal({controller: "archive", action: "index"}, @routes.recognize_path("/archive"))
-
- assert_equal({controller: "people", action: "index"}, @routes.recognize_path("/people", method: :get))
- assert_equal({controller: "people", action: "index", format: "xml"}, @routes.recognize_path("/people.xml", method: :get))
- assert_equal({controller: "people", action: "create"}, @routes.recognize_path("/people", method: :post))
- assert_equal({controller: "people", action: "new"}, @routes.recognize_path("/people/new", method: :get))
- assert_equal({controller: "people", action: "show", id: "1"}, @routes.recognize_path("/people/1", method: :get))
- assert_equal({controller: "people", action: "show", id: "1", format: "xml"}, @routes.recognize_path("/people/1.xml", method: :get))
- assert_equal({controller: "people", action: "update", id: "1"}, @routes.recognize_path("/people/1", method: :put))
- assert_equal({controller: "people", action: "destroy", id: "1"}, @routes.recognize_path("/people/1", method: :delete))
- assert_equal({controller: "people", action: "edit", id: "1"}, @routes.recognize_path("/people/1/edit", method: :get))
- assert_equal({controller: "people", action: "edit", id: "1", format: "xml"}, @routes.recognize_path("/people/1/edit.xml", method: :get))
-
- assert_equal({controller: "symbols", action: "show", name: :as_symbol}, @routes.recognize_path("/symbols"))
- assert_equal({controller: "foo", action: "id_default", id: "1"}, @routes.recognize_path("/id_default/1"))
- assert_equal({controller: "foo", action: "id_default", id: "2"}, @routes.recognize_path("/id_default/2"))
- assert_equal({controller: "foo", action: "id_default", id: 1 }, @routes.recognize_path("/id_default"))
- assert_equal({controller: "foo", action: "get_or_post"}, @routes.recognize_path("/get_or_post", method: :get))
- assert_equal({controller: "foo", action: "get_or_post"}, @routes.recognize_path("/get_or_post", method: :post))
+ assert_equal({ controller: "admin/users", action: "index" }, @routes.recognize_path("/admin/users", method: :get))
+ assert_equal({ controller: "admin/users", action: "create" }, @routes.recognize_path("/admin/users", method: :post))
+ assert_equal({ controller: "admin/users", action: "new" }, @routes.recognize_path("/admin/users/new", method: :get))
+ assert_equal({ controller: "admin/users", action: "show", id: "1" }, @routes.recognize_path("/admin/users/1", method: :get))
+ assert_equal({ controller: "admin/users", action: "update", id: "1" }, @routes.recognize_path("/admin/users/1", method: :put))
+ assert_equal({ controller: "admin/users", action: "destroy", id: "1" }, @routes.recognize_path("/admin/users/1", method: :delete))
+ assert_equal({ controller: "admin/users", action: "edit", id: "1" }, @routes.recognize_path("/admin/users/1/edit", method: :get))
+
+ assert_equal({ controller: "admin/posts", action: "index" }, @routes.recognize_path("/admin/posts", method: :get))
+ assert_equal({ controller: "admin/posts", action: "new" }, @routes.recognize_path("/admin/posts/new", method: :get))
+
+ assert_equal({ controller: "api/users", action: "index" }, @routes.recognize_path("/api", method: :get))
+ assert_equal({ controller: "api/users", action: "index" }, @routes.recognize_path("/api/", method: :get))
+
+ assert_equal({ controller: "posts", action: "show_date", year: "2009", month: nil, day: nil }, @routes.recognize_path("/blog/2009", method: :get))
+ assert_equal({ controller: "posts", action: "show_date", year: "2009", month: "01", day: nil }, @routes.recognize_path("/blog/2009/01", method: :get))
+ assert_equal({ controller: "posts", action: "show_date", year: "2009", month: "01", day: "01" }, @routes.recognize_path("/blog/2009/01/01", method: :get))
+
+ assert_equal({ controller: "archive", action: "index", year: "2010" }, @routes.recognize_path("/archive/2010"))
+ assert_equal({ controller: "archive", action: "index" }, @routes.recognize_path("/archive"))
+
+ assert_equal({ controller: "people", action: "index" }, @routes.recognize_path("/people", method: :get))
+ assert_equal({ controller: "people", action: "index", format: "xml" }, @routes.recognize_path("/people.xml", method: :get))
+ assert_equal({ controller: "people", action: "create" }, @routes.recognize_path("/people", method: :post))
+ assert_equal({ controller: "people", action: "new" }, @routes.recognize_path("/people/new", method: :get))
+ assert_equal({ controller: "people", action: "show", id: "1" }, @routes.recognize_path("/people/1", method: :get))
+ assert_equal({ controller: "people", action: "show", id: "1", format: "xml" }, @routes.recognize_path("/people/1.xml", method: :get))
+ assert_equal({ controller: "people", action: "update", id: "1" }, @routes.recognize_path("/people/1", method: :put))
+ assert_equal({ controller: "people", action: "destroy", id: "1" }, @routes.recognize_path("/people/1", method: :delete))
+ assert_equal({ controller: "people", action: "edit", id: "1" }, @routes.recognize_path("/people/1/edit", method: :get))
+ assert_equal({ controller: "people", action: "edit", id: "1", format: "xml" }, @routes.recognize_path("/people/1/edit.xml", method: :get))
+
+ assert_equal({ controller: "symbols", action: "show", name: :as_symbol }, @routes.recognize_path("/symbols"))
+ assert_equal({ controller: "foo", action: "id_default", id: "1" }, @routes.recognize_path("/id_default/1"))
+ assert_equal({ controller: "foo", action: "id_default", id: "2" }, @routes.recognize_path("/id_default/2"))
+ assert_equal({ controller: "foo", action: "id_default", id: 1 }, @routes.recognize_path("/id_default"))
+ assert_equal({ controller: "foo", action: "get_or_post" }, @routes.recognize_path("/get_or_post", method: :get))
+ assert_equal({ controller: "foo", action: "get_or_post" }, @routes.recognize_path("/get_or_post", method: :post))
assert_raise(ActionController::RoutingError) { @routes.recognize_path("/get_or_post", method: :put) }
assert_raise(ActionController::RoutingError) { @routes.recognize_path("/get_or_post", method: :delete) }
- assert_equal({controller: "posts", action: "index", optional: "bar"}, @routes.recognize_path("/optional/bar"))
+ assert_equal({ controller: "posts", action: "index", optional: "bar" }, @routes.recognize_path("/optional/bar"))
assert_raise(ActionController::RoutingError) { @routes.recognize_path("/optional") }
- assert_equal({controller: "posts", action: "show", id: "1", ws: true}, @routes.recognize_path("/ws/posts/show/1", method: :get))
- assert_equal({controller: "posts", action: "list", ws: true}, @routes.recognize_path("/ws/posts/list", method: :get))
- assert_equal({controller: "posts", action: "index", ws: true}, @routes.recognize_path("/ws/posts", method: :get))
+ assert_equal({ controller: "posts", action: "show", id: "1", ws: true }, @routes.recognize_path("/ws/posts/show/1", method: :get))
+ assert_equal({ controller: "posts", action: "list", ws: true }, @routes.recognize_path("/ws/posts/list", method: :get))
+ assert_equal({ controller: "posts", action: "index", ws: true }, @routes.recognize_path("/ws/posts", method: :get))
- assert_equal({controller: "account", action: "subscription"}, @routes.recognize_path("/account", method: :get))
- assert_equal({controller: "account", action: "subscription"}, @routes.recognize_path("/account/subscription", method: :get))
- assert_equal({controller: "account", action: "billing"}, @routes.recognize_path("/account/billing", method: :get))
+ assert_equal({ controller: "account", action: "subscription" }, @routes.recognize_path("/account", method: :get))
+ assert_equal({ controller: "account", action: "subscription" }, @routes.recognize_path("/account/subscription", method: :get))
+ assert_equal({ controller: "account", action: "billing" }, @routes.recognize_path("/account/billing", method: :get))
- assert_equal({page_id: "1", controller: "notes", action: "index"}, @routes.recognize_path("/pages/1/notes", method: :get))
- assert_equal({page_id: "1", controller: "notes", action: "list"}, @routes.recognize_path("/pages/1/notes/list", method: :get))
- assert_equal({page_id: "1", controller: "notes", action: "show", id: "2"}, @routes.recognize_path("/pages/1/notes/show/2", method: :get))
+ assert_equal({ page_id: "1", controller: "notes", action: "index" }, @routes.recognize_path("/pages/1/notes", method: :get))
+ assert_equal({ page_id: "1", controller: "notes", action: "list" }, @routes.recognize_path("/pages/1/notes/list", method: :get))
+ assert_equal({ page_id: "1", controller: "notes", action: "show", id: "2" }, @routes.recognize_path("/pages/1/notes/show/2", method: :get))
- assert_equal({controller: "posts", action: "ping"}, @routes.recognize_path("/posts/ping", method: :get))
- assert_equal({controller: "posts", action: "index"}, @routes.recognize_path("/posts", method: :get))
- assert_equal({controller: "posts", action: "index"}, @routes.recognize_path("/posts/index", method: :get))
- assert_equal({controller: "posts", action: "show"}, @routes.recognize_path("/posts/show", method: :get))
- assert_equal({controller: "posts", action: "show", id: "1"}, @routes.recognize_path("/posts/show/1", method: :get))
- assert_equal({controller: "posts", action: "create"}, @routes.recognize_path("/posts/create", method: :post))
+ assert_equal({ controller: "posts", action: "ping" }, @routes.recognize_path("/posts/ping", method: :get))
+ assert_equal({ controller: "posts", action: "index" }, @routes.recognize_path("/posts", method: :get))
+ assert_equal({ controller: "posts", action: "index" }, @routes.recognize_path("/posts/index", method: :get))
+ assert_equal({ controller: "posts", action: "show" }, @routes.recognize_path("/posts/show", method: :get))
+ assert_equal({ controller: "posts", action: "show", id: "1" }, @routes.recognize_path("/posts/show/1", method: :get))
+ assert_equal({ controller: "posts", action: "create" }, @routes.recognize_path("/posts/create", method: :post))
- assert_equal({controller: "geocode", action: "show", postalcode: "hx12-1az"}, @routes.recognize_path("/ignorecase/geocode/hx12-1az"))
- assert_equal({controller: "geocode", action: "show", postalcode: "hx12-1AZ"}, @routes.recognize_path("/ignorecase/geocode/hx12-1AZ"))
- assert_equal({controller: "geocode", action: "show", postalcode: "12345-1234"}, @routes.recognize_path("/extended/geocode/12345-1234"))
- assert_equal({controller: "geocode", action: "show", postalcode: "12345"}, @routes.recognize_path("/extended/geocode/12345"))
+ assert_equal({ controller: "geocode", action: "show", postalcode: "hx12-1az" }, @routes.recognize_path("/ignorecase/geocode/hx12-1az"))
+ assert_equal({ controller: "geocode", action: "show", postalcode: "hx12-1AZ" }, @routes.recognize_path("/ignorecase/geocode/hx12-1AZ"))
+ assert_equal({ controller: "geocode", action: "show", postalcode: "12345-1234" }, @routes.recognize_path("/extended/geocode/12345-1234"))
+ assert_equal({ controller: "geocode", action: "show", postalcode: "12345" }, @routes.recognize_path("/extended/geocode/12345"))
- assert_equal({controller: "news", action: "index" }, @routes.recognize_path("/", method: :get))
- assert_equal({controller: "news", action: "index", format: "rss"}, @routes.recognize_path("/news.rss", method: :get))
+ assert_equal({ controller: "news", action: "index" }, @routes.recognize_path("/", method: :get))
+ assert_equal({ controller: "news", action: "index", format: "rss" }, @routes.recognize_path("/news.rss", method: :get))
assert_raise(ActionController::RoutingError) { @routes.recognize_path("/none", method: :get) }
end
@@ -2056,25 +2059,25 @@ class RackMountIntegrationTests < ActiveSupport::TestCase
end
def test_extras
- params = {controller: "people"}
+ params = { controller: "people" }
assert_equal [], @routes.extra_keys(params)
- assert_equal({controller: "people", action: "index"}, params)
+ assert_equal({ controller: "people", action: "index" }, params)
- params = {controller: "people", foo: "bar"}
+ params = { controller: "people", foo: "bar" }
assert_equal [:foo], @routes.extra_keys(params)
- assert_equal({controller: "people", action: "index", foo: "bar"}, params)
+ assert_equal({ controller: "people", action: "index", foo: "bar" }, params)
- params = {controller: "people", action: "create", person: { name: "Josh"}}
+ params = { controller: "people", action: "create", person: { name: "Josh" } }
assert_equal [:person], @routes.extra_keys(params)
- assert_equal({controller: "people", action: "create", person: { name: "Josh"}}, params)
+ assert_equal({ controller: "people", action: "create", person: { name: "Josh" } }, params)
end
def test_unicode_path
- assert_equal({controller: "news", action: "index"}, @routes.recognize_path(URI.parser.escape("こんにちは/世界"), method: :get))
+ assert_equal({ controller: "news", action: "index" }, @routes.recognize_path(URI.parser.escape("こんにちは/世界"), method: :get))
end
def test_downcased_unicode_path
- assert_equal({controller: "news", action: "index"}, @routes.recognize_path(URI.parser.escape("こんにちは/世界").downcase, method: :get))
+ assert_equal({ controller: "news", action: "index" }, @routes.recognize_path(URI.parser.escape("こんにちは/世界").downcase, method: :get))
end
private
diff --git a/actionpack/test/controller/send_file_test.rb b/actionpack/test/controller/send_file_test.rb
index e78478b16c..25420ead3b 100644
--- a/actionpack/test/controller/send_file_test.rb
+++ b/actionpack/test/controller/send_file_test.rb
@@ -159,7 +159,6 @@ class SendFileTest < ActionController::TestCase
assert_equal "image/png", response.content_type
end
-
def test_send_file_headers_with_bad_symbol
error = assert_raise(ArgumentError) { get __method__ }
assert_equal "Unknown MIME type this_type_is_not_registered", error.message
@@ -193,7 +192,7 @@ class SendFileTest < ActionController::TestCase
end
def test_send_file_without_content_disposition_header
- @controller.options = {disposition: nil}
+ @controller.options = { disposition: nil }
process("data")
assert_nil @controller.headers["Content-Disposition"]
end
diff --git a/actionpack/test/controller/test_case_test.rb b/actionpack/test/controller/test_case_test.rb
index 45bc770e86..2d78fc71a9 100644
--- a/actionpack/test/controller/test_case_test.rb
+++ b/actionpack/test/controller/test_case_test.rb
@@ -239,7 +239,7 @@ XML
def test_document_body_and_params_with_post
post :test_params, params: { id: 1 }
- assert_equal({"id"=>"1", "controller"=>"test_case_test/test", "action"=>"test_params"}, ::JSON.parse(@response.body))
+ assert_equal({ "id"=>"1", "controller"=>"test_case_test/test", "action"=>"test_params" }, ::JSON.parse(@response.body))
end
def test_document_body_with_post
@@ -525,15 +525,15 @@ XML
end
def test_query_param_named_action
- get :test_query_parameters, params: {action: "foobar"}
+ get :test_query_parameters, params: { action: "foobar" }
parsed_params = JSON.parse(@response.body)
- assert_equal({"action" => "foobar"}, parsed_params)
+ assert_equal({ "action" => "foobar" }, parsed_params)
end
def test_request_param_named_action
- post :test_request_parameters, params: {action: "foobar"}
+ post :test_request_parameters, params: { action: "foobar" }
parsed_params = eval(@response.body)
- assert_equal({"action" => "foobar"}, parsed_params)
+ assert_equal({ "action" => "foobar" }, parsed_params)
end
def test_kwarg_params_passing_with_session_and_flash
@@ -548,8 +548,8 @@ XML
parsed_params = ::JSON.parse(@response.body)
assert_equal(
- {"controller" => "test_case_test/test", "action" => "test_params",
- "page" => {"name" => "Page name", "month" => "4", "year" => "2004", "day" => "6"}},
+ { "controller" => "test_case_test/test", "action" => "test_params",
+ "page" => { "name" => "Page name", "month" => "4", "year" => "2004", "day" => "6" } },
parsed_params
)
@@ -563,8 +563,8 @@ XML
}
parsed_params = ::JSON.parse(@response.body)
assert_equal(
- {"controller" => "test_case_test/test", "action" => "test_params",
- "page" => {"name" => "Page name", "month" => "4", "year" => "2004", "day" => "6"}},
+ { "controller" => "test_case_test/test", "action" => "test_params",
+ "page" => { "name" => "Page name", "month" => "4", "year" => "2004", "day" => "6" } },
parsed_params
)
end
@@ -573,7 +573,7 @@ XML
get :test_params, params: { format: "json", count: 999 }
parsed_params = ::JSON.parse(@response.body)
assert_equal(
- {"controller" => "test_case_test/test", "action" => "test_params",
+ { "controller" => "test_case_test/test", "action" => "test_params",
"format" => "json", "count" => "999" },
parsed_params
)
@@ -583,7 +583,7 @@ XML
get :test_params, params: { format: "json", id: 1 }
parsed_params = ::JSON.parse(@response.body)
assert_equal(
- {"controller" => "test_case_test/test", "action" => "test_params",
+ { "controller" => "test_case_test/test", "action" => "test_params",
"format" => "json", "id" => "1" },
parsed_params
)
@@ -593,7 +593,7 @@ XML
assert_deprecated { get :test_params, format: "json", id: 1 }
parsed_params = ::JSON.parse(@response.body)
assert_equal(
- {"controller" => "test_case_test/test", "action" => "test_params",
+ { "controller" => "test_case_test/test", "action" => "test_params",
"format" => "json", "id" => "1" },
parsed_params
)
@@ -607,8 +607,8 @@ XML
end
parsed_params = ::JSON.parse(@response.body)
assert_equal(
- {"controller" => "test_case_test/test", "action" => "test_params",
- "frozen" => "icy", "frozens" => ["icy"], "deepfreeze" => { "frozen" => "icy" }},
+ { "controller" => "test_case_test/test", "action" => "test_params",
+ "frozen" => "icy", "frozens" => ["icy"], "deepfreeze" => { "frozen" => "icy" } },
parsed_params
)
end
@@ -670,7 +670,7 @@ XML
end
def test_deprecared_id_converted_to_string
- assert_deprecated { get :test_params, id: 20, foo: Object.new}
+ assert_deprecated { get :test_params, id: 20, foo: Object.new }
assert_kind_of String, @request.path_parameters[:id]
end
@@ -731,13 +731,13 @@ XML
def test_deprecated_xhr_with_params
assert_deprecated { xhr :get, :test_params, params: { id: 1 } }
- assert_equal({"id"=>"1", "controller"=>"test_case_test/test", "action"=>"test_params"}, ::JSON.parse(@response.body))
+ assert_equal({ "id"=>"1", "controller"=>"test_case_test/test", "action"=>"test_params" }, ::JSON.parse(@response.body))
end
def test_xhr_with_params
get :test_params, params: { id: 1 }, xhr: true
- assert_equal({"id"=>"1", "controller"=>"test_case_test/test", "action"=>"test_params"}, ::JSON.parse(@response.body))
+ assert_equal({ "id"=>"1", "controller"=>"test_case_test/test", "action"=>"test_params" }, ::JSON.parse(@response.body))
end
def test_xhr_with_session
@@ -856,10 +856,10 @@ XML
def test_multiple_mixed_method_process_should_scrub_rack_input
post :test_params, params: { id: 1, foo: "an foo" }
- assert_equal({"id"=>"1", "foo" => "an foo", "controller"=>"test_case_test/test", "action"=>"test_params"}, ::JSON.parse(@response.body))
+ assert_equal({ "id"=>"1", "foo" => "an foo", "controller"=>"test_case_test/test", "action"=>"test_params" }, ::JSON.parse(@response.body))
get :test_params, params: { bar: "an bar" }
- assert_equal({"bar"=>"an bar", "controller"=>"test_case_test/test", "action"=>"test_params"}, ::JSON.parse(@response.body))
+ assert_equal({ "bar"=>"an bar", "controller"=>"test_case_test/test", "action"=>"test_params" }, ::JSON.parse(@response.body))
end
%w(controller response request).each do |variable|
@@ -1208,7 +1208,7 @@ class RoutingDefaultsTest < ActionController::TestCase
end
def test_route_option_can_be_passed_via_process
- get :post, params: { id: 1, bucket_type: "post"}
+ get :post, params: { id: 1, bucket_type: "post" }
assert_equal "/posts/1", @response.body
end
diff --git a/actionpack/test/controller/url_for_integration_test.rb b/actionpack/test/controller/url_for_integration_test.rb
index fc746add9b..c7ea6c5ef6 100644
--- a/actionpack/test/controller/url_for_integration_test.rb
+++ b/actionpack/test/controller/url_for_integration_test.rb
@@ -78,7 +78,7 @@ module ActionPack
["/admin/users",[ { controller: "admin/users", action: "index" }]],
["/admin/users",[ { action: "index" }, { controller: "admin/users", action: "index" }, "/admin/users"]],
["/admin/users",[ { controller: "users", action: "index" }, { controller: "admin/accounts", action: "show", id: "1" }, "/admin/accounts/show/1"]],
- ["/people",[ { controller: "/people", action: "index" }, {controller: "admin/accounts", action: "foo", id: "bar"}, "/admin/accounts/foo/bar"]],
+ ["/people",[ { controller: "/people", action: "index" }, { controller: "admin/accounts", action: "foo", id: "bar" }, "/admin/accounts/foo/bar"]],
["/admin/posts",[ { controller: "admin/posts" }]],
["/admin/posts/new",[ { controller: "admin/posts", action: "new" }]],
@@ -124,7 +124,7 @@ module ActionPack
["/project",[ { controller: "project", action: "index" }]],
["/projects/1",[ { controller: "project", action: "index", project_id: "1" }]],
- ["/projects/1",[ { controller: "project", action: "index"}, {project_id: "1", controller: "project", action: "index" }, "/projects/1"]],
+ ["/projects/1",[ { controller: "project", action: "index" }, { project_id: "1", controller: "project", action: "index" }, "/projects/1"]],
["/projects/1",[ { use_route: "project", controller: "project", action: "index", project_id: "1" }]],
["/projects/1",[ { use_route: "project", controller: "project", action: "index" }, { controller: "project", action: "index", project_id: "1" }, "/projects/1"]],
@@ -164,11 +164,11 @@ module ActionPack
["/posts/show/1",[ { controller: "posts", action: "show", id: "1", format: "" }]],
["/posts",[ { controller: "posts" }]],
["/posts",[ { controller: "posts", action: "index" }]],
- ["/posts/create",[ { action: "create" }, {day: nil, month: nil, controller: "posts", action: "show_date"}, "/blog"]],
+ ["/posts/create",[ { action: "create" }, { day: nil, month: nil, controller: "posts", action: "show_date" }, "/blog"]],
["/posts?foo=bar",[ { controller: "posts", foo: "bar" }]],
["/posts?foo%5B%5D=bar&foo%5B%5D=baz", [{ controller: "posts", foo: ["bar", "baz"] }]],
["/posts?page=2", [{ controller: "posts", page: 2 }]],
- ["/posts?q%5Bfoo%5D%5Ba%5D=b", [{ controller: "posts", q: { foo: { a: "b"}} }]],
+ ["/posts?q%5Bfoo%5D%5Ba%5D=b", [{ controller: "posts", q: { foo: { a: "b" } } }]],
["/news.rss", [{ controller: "news", action: "index", format: "rss" }]],
].each_with_index do |(url, params), i|
diff --git a/actionpack/test/controller/url_for_test.rb b/actionpack/test/controller/url_for_test.rb
index ad4acf3462..8d7190365d 100644
--- a/actionpack/test/controller/url_for_test.rb
+++ b/actionpack/test/controller/url_for_test.rb
@@ -222,19 +222,19 @@ module AbstractController
def test_trailing_slash
add_host!
- options = {controller: "foo", trailing_slash: true, action: "bar", id: "33"}
+ options = { controller: "foo", trailing_slash: true, action: "bar", id: "33" }
assert_equal("http://www.basecamphq.com/foo/bar/33/", W.new.url_for(options) )
end
def test_trailing_slash_with_protocol
add_host!
- options = { trailing_slash: true,protocol: "https", controller: "foo", action: "bar", id: "33"}
+ options = { trailing_slash: true,protocol: "https", controller: "foo", action: "bar", id: "33" }
assert_equal("https://www.basecamphq.com/foo/bar/33/", W.new.url_for(options) )
assert_equal "https://www.basecamphq.com/foo/bar/33/?query=string", W.new.url_for(options.merge(query: "string"))
end
def test_trailing_slash_with_only_path
- options = {controller: "foo", trailing_slash: true}
+ options = { controller: "foo", trailing_slash: true }
assert_equal "/foo/", W.new.url_for(options.merge(only_path: true))
options.update(action: "bar", id: "33")
assert_equal "/foo/bar/33/", W.new.url_for(options.merge(only_path: true))
@@ -242,7 +242,7 @@ module AbstractController
end
def test_trailing_slash_with_anchor
- options = {trailing_slash: true, controller: "foo", action: "bar", id: "33", only_path: true, anchor: "chapter7"}
+ options = { trailing_slash: true, controller: "foo", action: "bar", id: "33", only_path: true, anchor: "chapter7" }
assert_equal "/foo/bar/33/#chapter7", W.new.url_for(options)
assert_equal "/foo/bar/33/?query=string#chapter7", W.new.url_for(options.merge(query: "string"))
end
@@ -250,8 +250,8 @@ module AbstractController
def test_trailing_slash_with_params
url = W.new.url_for(trailing_slash: true, only_path: true, controller: "cont", action: "act", p1: "cafe", p2: "link")
params = extract_params(url)
- assert_equal({p1: "cafe"}.to_query, params[0])
- assert_equal({p2: "link"}.to_query, params[1])
+ assert_equal({ p1: "cafe" }.to_query, params[0])
+ assert_equal({ p2: "link" }.to_query, params[1])
end
def test_relative_url_root_is_respected
@@ -348,40 +348,40 @@ module AbstractController
def test_two_parameters
url = W.new.url_for(only_path: true, controller: "c", action: "a", p1: "X1", p2: "Y2")
params = extract_params(url)
- assert_equal({p1: "X1"}.to_query, params[0])
- assert_equal({p2: "Y2"}.to_query, params[1])
+ assert_equal({ p1: "X1" }.to_query, params[0])
+ assert_equal({ p2: "Y2" }.to_query, params[1])
end
def test_hash_parameter
- url = W.new.url_for(only_path: true, controller: "c", action: "a", query: {name: "Bob", category: "prof"})
+ url = W.new.url_for(only_path: true, controller: "c", action: "a", query: { name: "Bob", category: "prof" })
params = extract_params(url)
- assert_equal({"query[category]" => "prof"}.to_query, params[0])
- assert_equal({"query[name]" => "Bob"}.to_query, params[1])
+ assert_equal({ "query[category]" => "prof" }.to_query, params[0])
+ assert_equal({ "query[name]" => "Bob" }.to_query, params[1])
end
def test_array_parameter
url = W.new.url_for(only_path: true, controller: "c", action: "a", query: ["Bob", "prof"])
params = extract_params(url)
- assert_equal({"query[]" => "Bob"}.to_query, params[0])
- assert_equal({"query[]" => "prof"}.to_query, params[1])
+ assert_equal({ "query[]" => "Bob" }.to_query, params[0])
+ assert_equal({ "query[]" => "prof" }.to_query, params[1])
end
def test_hash_recursive_parameters
- url = W.new.url_for(only_path: true, controller: "c", action: "a", query: {person: {name: "Bob", position: "prof"}, hobby: "piercing"})
+ url = W.new.url_for(only_path: true, controller: "c", action: "a", query: { person: { name: "Bob", position: "prof" }, hobby: "piercing" })
params = extract_params(url)
- assert_equal({"query[hobby]" => "piercing"}.to_query, params[0])
- assert_equal({"query[person][name]" => "Bob" }.to_query, params[1])
- assert_equal({"query[person][position]" => "prof" }.to_query, params[2])
+ assert_equal({ "query[hobby]" => "piercing" }.to_query, params[0])
+ assert_equal({ "query[person][name]" => "Bob" }.to_query, params[1])
+ assert_equal({ "query[person][position]" => "prof" }.to_query, params[2])
end
def test_hash_recursive_and_array_parameters
- url = W.new.url_for(only_path: true, controller: "c", action: "a", id: 101, query: {person: {name: "Bob", position: ["prof", "art director"]}, hobby: "piercing"})
+ url = W.new.url_for(only_path: true, controller: "c", action: "a", id: 101, query: { person: { name: "Bob", position: ["prof", "art director"] }, hobby: "piercing" })
assert_match(%r(^/c/a/101), url)
params = extract_params(url)
- assert_equal({"query[hobby]" => "piercing" }.to_query, params[0])
- assert_equal({"query[person][name]" => "Bob" }.to_query, params[1])
- assert_equal({"query[person][position][]" => "art director"}.to_query, params[2])
- assert_equal({"query[person][position][]" => "prof" }.to_query, params[3])
+ assert_equal({ "query[hobby]" => "piercing" }.to_query, params[0])
+ assert_equal({ "query[person][name]" => "Bob" }.to_query, params[1])
+ assert_equal({ "query[person][position][]" => "art director" }.to_query, params[2])
+ assert_equal({ "query[person][position][]" => "prof" }.to_query, params[3])
end
def test_url_action_controller_parameters
@@ -407,7 +407,7 @@ module AbstractController
kls.default_url_options[:host] = "www.basecamphq.com"
controller = kls.new
- params = {action: :index, controller: :posts, format: :xml}
+ params = { action: :index, controller: :posts, format: :xml }
assert_equal("http://www.basecamphq.com/posts.xml", controller.send(:url_for, params))
params[:format] = nil
assert_equal("http://www.basecamphq.com/", controller.send(:url_for, params))
diff --git a/actionpack/test/controller/url_rewriter_test.rb b/actionpack/test/controller/url_rewriter_test.rb
index d64ff4d6ce..a055e6d177 100644
--- a/actionpack/test/controller/url_rewriter_test.rb
+++ b/actionpack/test/controller/url_rewriter_test.rb
@@ -79,7 +79,7 @@ class UrlRewriterTests < ActionController::TestCase
end
def test_trailing_slash
- options = {controller: "foo", action: "bar", id: "3", only_path: true}
+ options = { controller: "foo", action: "bar", id: "3", only_path: true }
assert_equal "/foo/bar/3", @rewriter.rewrite(@routes, options)
assert_equal "/foo/bar/3?query=string", @rewriter.rewrite(@routes, options.merge(query: "string"))
options.update(trailing_slash: true)
diff --git a/actionpack/test/dispatch/cookies_test.rb b/actionpack/test/dispatch/cookies_test.rb
index 06a54591b8..4d3d83f45a 100644
--- a/actionpack/test/dispatch/cookies_test.rb
+++ b/actionpack/test/dispatch/cookies_test.rb
@@ -210,12 +210,12 @@ class CookiesTest < ActionController::TestCase
end
def set_cookie_with_domain
- cookies[:user_name] = {value: "rizwanreza", domain: :all}
+ cookies[:user_name] = { value: "rizwanreza", domain: :all }
head :ok
end
def set_cookie_with_domain_all_as_string
- cookies[:user_name] = {value: "rizwanreza", domain: "all"}
+ cookies[:user_name] = { value: "rizwanreza", domain: "all" }
head :ok
end
@@ -230,7 +230,7 @@ class CookiesTest < ActionController::TestCase
end
def set_cookie_with_domain_and_tld
- cookies[:user_name] = {value: "rizwanreza", domain: :all, tld_length: 2}
+ cookies[:user_name] = { value: "rizwanreza", domain: :all, tld_length: 2 }
head :ok
end
@@ -240,7 +240,7 @@ class CookiesTest < ActionController::TestCase
end
def set_cookie_with_domains
- cookies[:user_name] = {value: "rizwanreza", domain: %w(example1.com example2.com .example3.com)}
+ cookies[:user_name] = { value: "rizwanreza", domain: %w(example1.com example2.com .example3.com) }
head :ok
end
@@ -293,7 +293,7 @@ class CookiesTest < ActionController::TestCase
def test_setting_cookie
get :authenticate
assert_cookie_header "user_name=david; path=/"
- assert_equal({"user_name" => "david"}, @response.cookies)
+ assert_equal({ "user_name" => "david" }, @response.cookies)
end
def test_setting_the_same_value_to_cookie
@@ -305,45 +305,45 @@ class CookiesTest < ActionController::TestCase
def test_setting_the_same_value_to_permanent_cookie
request.cookies[:user_name] = "Jamie"
get :set_permanent_cookie
- assert_equal({"user_name" => "Jamie"}, response.cookies)
+ assert_equal({ "user_name" => "Jamie" }, response.cookies)
end
def test_setting_with_escapable_characters
get :set_with_with_escapable_characters
assert_cookie_header "that+%26+guy=foo+%26+bar+%3D%3E+baz; path=/"
- assert_equal({"that & guy" => "foo & bar => baz"}, @response.cookies)
+ assert_equal({ "that & guy" => "foo & bar => baz" }, @response.cookies)
end
def test_setting_cookie_for_fourteen_days
get :authenticate_for_fourteen_days
assert_cookie_header "user_name=david; path=/; expires=Mon, 10 Oct 2005 05:00:00 -0000"
- assert_equal({"user_name" => "david"}, @response.cookies)
+ assert_equal({ "user_name" => "david" }, @response.cookies)
end
def test_setting_cookie_for_fourteen_days_with_symbols
get :authenticate_for_fourteen_days_with_symbols
assert_cookie_header "user_name=david; path=/; expires=Mon, 10 Oct 2005 05:00:00 -0000"
- assert_equal({"user_name" => "david"}, @response.cookies)
+ assert_equal({ "user_name" => "david" }, @response.cookies)
end
def test_setting_cookie_with_http_only
get :authenticate_with_http_only
assert_cookie_header "user_name=david; path=/; HttpOnly"
- assert_equal({"user_name" => "david"}, @response.cookies)
+ assert_equal({ "user_name" => "david" }, @response.cookies)
end
def test_setting_cookie_with_secure
@request.env["HTTPS"] = "on"
get :authenticate_with_secure
assert_cookie_header "user_name=david; path=/; secure"
- assert_equal({"user_name" => "david"}, @response.cookies)
+ assert_equal({ "user_name" => "david" }, @response.cookies)
end
def test_setting_cookie_with_secure_when_always_write_cookie_is_true
old_cookie, @request.cookie_jar.always_write_cookie = @request.cookie_jar.always_write_cookie, true
get :authenticate_with_secure
assert_cookie_header "user_name=david; path=/; secure"
- assert_equal({"user_name" => "david"}, @response.cookies)
+ assert_equal({ "user_name" => "david" }, @response.cookies)
ensure
@request.cookie_jar.always_write_cookie = old_cookie
end
@@ -351,14 +351,14 @@ class CookiesTest < ActionController::TestCase
def test_not_setting_cookie_with_secure
get :authenticate_with_secure
assert_not_cookie_header "user_name=david; path=/; secure"
- assert_not_equal({"user_name" => "david"}, @response.cookies)
+ assert_not_equal({ "user_name" => "david" }, @response.cookies)
end
def test_multiple_cookies
get :set_multiple_cookies
assert_equal 2, @response.cookies.size
assert_cookie_header "user_name=david; path=/; expires=Mon, 10 Oct 2005 05:00:00 -0000\nlogin=XJ-122; path=/"
- assert_equal({"login" => "XJ-122", "user_name" => "david"}, @response.cookies)
+ assert_equal({ "login" => "XJ-122", "user_name" => "david" }, @response.cookies)
end
def test_setting_test_cookie
@@ -369,7 +369,7 @@ class CookiesTest < ActionController::TestCase
request.cookies[:user_name] = "Joe"
get :logout
assert_cookie_header "user_name=; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 -0000"
- assert_equal({"user_name" => nil}, @response.cookies)
+ assert_equal({ "user_name" => nil }, @response.cookies)
end
def test_delete_cookie_with_path
@@ -656,7 +656,7 @@ class CookiesTest < ActionController::TestCase
request.cookies[:user_name] = "Joe"
get :delete_and_set_cookie
assert_cookie_header "user_name=david; path=/; expires=Mon, 10 Oct 2005 05:00:00 -0000"
- assert_equal({"user_name" => "david"}, @response.cookies)
+ assert_equal({ "user_name" => "david" }, @response.cookies)
end
def test_raise_data_overflow
diff --git a/actionpack/test/dispatch/debug_exceptions_test.rb b/actionpack/test/dispatch/debug_exceptions_test.rb
index b55bd9b204..2c5e09e283 100644
--- a/actionpack/test/dispatch/debug_exceptions_test.rb
+++ b/actionpack/test/dispatch/debug_exceptions_test.rb
@@ -156,7 +156,7 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
test "rescue with text error for xhr request" do
@app = DevelopmentApp
- xhr_request_env = {"action_dispatch.show_exceptions" => true, "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest"}
+ xhr_request_env = { "action_dispatch.show_exceptions" => true, "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest" }
get "/", headers: xhr_request_env
assert_response 500
@@ -399,9 +399,9 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
backtrace_cleaner = ActiveSupport::BacktraceCleaner.new
backtrace_cleaner.add_silencer { true }
- env = {"action_dispatch.show_exceptions" => true,
+ env = { "action_dispatch.show_exceptions" => true,
"action_dispatch.logger" => Logger.new(output),
- "action_dispatch.backtrace_cleaner" => backtrace_cleaner}
+ "action_dispatch.backtrace_cleaner" => backtrace_cleaner }
get "/", headers: env
assert_operator((output.rewind && output.read).lines.count, :>, 10)
diff --git a/actionpack/test/dispatch/header_test.rb b/actionpack/test/dispatch/header_test.rb
index 12f1c2712d..7a155d70cb 100644
--- a/actionpack/test/dispatch/header_test.rb
+++ b/actionpack/test/dispatch/header_test.rb
@@ -18,14 +18,14 @@ class HeaderTest < ActiveSupport::TestCase
"HTTP_REFERER" => "/some/page",
"Host" => "http://test.com")
- assert_equal({"Content-Type" => "application/json",
+ assert_equal({ "Content-Type" => "application/json",
"HTTP_REFERER" => "/some/page",
- "Host" => "http://test.com"}, headers.env)
+ "Host" => "http://test.com" }, headers.env)
end
test "#env returns the headers as env variables" do
- assert_equal({"CONTENT_TYPE" => "text/plain",
- "HTTP_REFERER" => "/some/page"}, @headers.env)
+ assert_equal({ "CONTENT_TYPE" => "text/plain",
+ "HTTP_REFERER" => "/some/page" }, @headers.env)
end
test "#each iterates through the env variables" do
@@ -105,28 +105,28 @@ class HeaderTest < ActiveSupport::TestCase
test "#merge! headers with mutation" do
@headers.merge!("Host" => "http://example.test",
"Content-Type" => "text/html")
- assert_equal({"HTTP_HOST" => "http://example.test",
+ assert_equal({ "HTTP_HOST" => "http://example.test",
"CONTENT_TYPE" => "text/html",
- "HTTP_REFERER" => "/some/page"}, @headers.env)
+ "HTTP_REFERER" => "/some/page" }, @headers.env)
end
test "#merge! env with mutation" do
@headers.merge!("HTTP_HOST" => "http://first.com",
"CONTENT_TYPE" => "text/html")
- assert_equal({"HTTP_HOST" => "http://first.com",
+ assert_equal({ "HTTP_HOST" => "http://first.com",
"CONTENT_TYPE" => "text/html",
- "HTTP_REFERER" => "/some/page"}, @headers.env)
+ "HTTP_REFERER" => "/some/page" }, @headers.env)
end
test "merge without mutation" do
combined = @headers.merge("HTTP_HOST" => "http://example.com",
"CONTENT_TYPE" => "text/html")
- assert_equal({"HTTP_HOST" => "http://example.com",
+ assert_equal({ "HTTP_HOST" => "http://example.com",
"CONTENT_TYPE" => "text/html",
- "HTTP_REFERER" => "/some/page"}, combined.env)
+ "HTTP_REFERER" => "/some/page" }, combined.env)
- assert_equal({"CONTENT_TYPE" => "text/plain",
- "HTTP_REFERER" => "/some/page"}, @headers.env)
+ assert_equal({ "CONTENT_TYPE" => "text/plain",
+ "HTTP_REFERER" => "/some/page" }, @headers.env)
end
test "env variables with . are not modified" do
@@ -151,11 +151,11 @@ class HeaderTest < ActiveSupport::TestCase
end
test "headers directly modifies the passed environment" do
- env = {"HTTP_REFERER" => "/"}
+ env = { "HTTP_REFERER" => "/" }
headers = make_headers(env)
headers["Referer"] = "http://example.com/"
headers.merge! "CONTENT_TYPE" => "text/plain"
- assert_equal({"HTTP_REFERER"=>"http://example.com/",
- "CONTENT_TYPE"=>"text/plain"}, env)
+ assert_equal({ "HTTP_REFERER"=>"http://example.com/",
+ "CONTENT_TYPE"=>"text/plain" }, env)
end
end
diff --git a/actionpack/test/dispatch/mapper_test.rb b/actionpack/test/dispatch/mapper_test.rb
index 8d2699fef6..1596d23b1e 100644
--- a/actionpack/test/dispatch/mapper_test.rb
+++ b/actionpack/test/dispatch/mapper_test.rb
@@ -58,7 +58,7 @@ module ActionDispatch
fakeset = FakeSet.new
mapper = Mapper.new fakeset
mapper.get "/foo", to: "posts#index", as: :main, format: true
- assert_equal({controller: "posts", action: "index"},
+ assert_equal({ controller: "posts", action: "index" },
fakeset.defaults.first)
assert_equal "/foo.:format", fakeset.asts.first.to_s
end
@@ -69,7 +69,7 @@ module ActionDispatch
mapper.scope(format: true) do
mapper.get "/foo", to: "posts#index", as: :main
end
- assert_equal({controller: "posts", action: "index"},
+ assert_equal({ controller: "posts", action: "index" },
fakeset.defaults.first)
assert_equal "/foo.:format", fakeset.asts.first.to_s
end
@@ -80,13 +80,13 @@ module ActionDispatch
mapper.scope(omg: :awesome) do
mapper.get "/", to: "posts#index", as: :main
end
- assert_equal({omg: :awesome, controller: "posts", action: "index"},
+ assert_equal({ omg: :awesome, controller: "posts", action: "index" },
fakeset.defaults.first)
assert_equal("GET", fakeset.routes.first.verb)
end
def test_mapping_requirements
- options = { }
+ options = {}
scope = Mapper::Scope.new({})
ast = Journey::Parser.parse "/store/:name(*rest)"
m = Mapper::Mapping.build(scope, FakeSet.new, ast, "foo", "bar", nil, [:get], nil, {}, true, options)
diff --git a/actionpack/test/dispatch/middleware_stack_test.rb b/actionpack/test/dispatch/middleware_stack_test.rb
index b00488edd5..27da5935b5 100644
--- a/actionpack/test/dispatch/middleware_stack_test.rb
+++ b/actionpack/test/dispatch/middleware_stack_test.rb
@@ -62,7 +62,7 @@ class MiddlewareStackTest < ActiveSupport::TestCase
@stack.use BazMiddleware, true, foo: "bar"
end
assert_equal BazMiddleware, @stack.last.klass
- assert_equal([true, {foo: "bar"}], @stack.last.args)
+ assert_equal([true, { foo: "bar" }], @stack.last.args)
end
test "use should push middleware class with block arguments onto the stack" do
diff --git a/actionpack/test/dispatch/mount_test.rb b/actionpack/test/dispatch/mount_test.rb
index 179b65b236..a7d5ba2345 100644
--- a/actionpack/test/dispatch/mount_test.rb
+++ b/actionpack/test/dispatch/mount_test.rb
@@ -15,13 +15,13 @@ class TestRoutingMount < ActionDispatch::IntegrationTest
def self.routes; Object.new; end
def self.call(env)
- [200, {"Content-Type" => "text/html"}, ["OK"]]
+ [200, { "Content-Type" => "text/html" }, ["OK"]]
end
end
Router.draw do
SprocketsApp = lambda { |env|
- [200, {"Content-Type" => "text/html"}, ["#{env["SCRIPT_NAME"]} -- #{env["PATH_INFO"]}"]]
+ [200, { "Content-Type" => "text/html" }, ["#{env["SCRIPT_NAME"]} -- #{env["PATH_INFO"]}"]]
}
mount SprocketsApp, at: "/sprockets"
diff --git a/actionpack/test/dispatch/prefix_generation_test.rb b/actionpack/test/dispatch/prefix_generation_test.rb
index ea11a943f2..bb2fc53add 100644
--- a/actionpack/test/dispatch/prefix_generation_test.rb
+++ b/actionpack/test/dispatch/prefix_generation_test.rb
@@ -238,7 +238,7 @@ module TestGenerationPrefix
end
test "[APP] generating engine's route includes default_url_options[:script_name]" do
- RailsApplication.routes.default_url_options = {script_name: "/something"}
+ RailsApplication.routes.default_url_options = { script_name: "/something" }
get "/generate"
assert_equal "/something/awesome/blog/posts/1", last_response.body
end
@@ -277,7 +277,7 @@ module TestGenerationPrefix
end
test "[OBJECT] generating engine's route includes default_url_options[:script_name]" do
- RailsApplication.routes.default_url_options = {script_name: "/something"}
+ RailsApplication.routes.default_url_options = { script_name: "/something" }
assert_equal "/something/pure-awesomeness/blog/posts/3", engine_object.post_path(id: 3, omg: "pure-awesomeness")
end
@@ -286,7 +286,7 @@ module TestGenerationPrefix
end
test "[OBJECT] generating application's route includes default_url_options[:script_name]" do
- RailsApplication.routes.default_url_options = {script_name: "/something"}
+ RailsApplication.routes.default_url_options = { script_name: "/something" }
assert_equal "/something/", app_object.root_path
end
diff --git a/actionpack/test/dispatch/reloader_test.rb b/actionpack/test/dispatch/reloader_test.rb
index 761237d5dc..e74b8e40fd 100644
--- a/actionpack/test/dispatch/reloader_test.rb
+++ b/actionpack/test/dispatch/reloader_test.rb
@@ -197,7 +197,7 @@ class ReloaderTest < ActiveSupport::TestCase
x.check = lambda { true }
@response ||= "response"
- @reloader ||= Reloader.new(block || proc {[200, {}, @response]}, x)
+ @reloader ||= Reloader.new(block || proc { [200, {}, @response] }, x)
@reloader.call("rack.input" => StringIO.new(""))[2]
end
end
diff --git a/actionpack/test/dispatch/request/json_params_parsing_test.rb b/actionpack/test/dispatch/request/json_params_parsing_test.rb
index e24b1e12e3..d0cd32a242 100644
--- a/actionpack/test/dispatch/request/json_params_parsing_test.rb
+++ b/actionpack/test/dispatch/request/json_params_parsing_test.rb
@@ -18,21 +18,21 @@ class JsonParamsParsingTest < ActionDispatch::IntegrationTest
test "parses json params for application json" do
assert_parses(
- {"person" => {"name" => "David"}},
+ { "person" => { "name" => "David" } },
"{\"person\": {\"name\": \"David\"}}", "CONTENT_TYPE" => "application/json"
)
end
test "parses boolean and number json params for application json" do
assert_parses(
- {"item" => {"enabled" => false, "count" => 10}},
+ { "item" => { "enabled" => false, "count" => 10 } },
"{\"item\": {\"enabled\": false, \"count\": 10}}", "CONTENT_TYPE" => "application/json"
)
end
test "parses json params for application jsonrequest" do
assert_parses(
- {"person" => {"name" => "David"}},
+ { "person" => { "name" => "David" } },
"{\"person\": {\"name\": \"David\"}}", "CONTENT_TYPE" => "application/jsonrequest"
)
end
@@ -46,15 +46,15 @@ class JsonParamsParsingTest < ActionDispatch::IntegrationTest
test "nils are stripped from collections" do
assert_parses(
- {"person" => []},
+ { "person" => [] },
"{\"person\":[null]}", "CONTENT_TYPE" => "application/json"
)
assert_parses(
- {"person" => ["foo"]},
+ { "person" => ["foo"] },
"{\"person\":[\"foo\",null]}", "CONTENT_TYPE" => "application/json"
)
assert_parses(
- {"person" => []},
+ { "person" => [] },
"{\"person\":[null, null]}", "CONTENT_TYPE" => "application/json"
)
end
@@ -133,21 +133,21 @@ class RootLessJSONParamsParsingTest < ActionDispatch::IntegrationTest
test "parses json params for application json" do
assert_parses(
- {"user" => {"username" => "sikachu"}, "username" => "sikachu"},
+ { "user" => { "username" => "sikachu" }, "username" => "sikachu" },
"{\"username\": \"sikachu\"}", "CONTENT_TYPE" => "application/json"
)
end
test "parses json params for application jsonrequest" do
assert_parses(
- {"user" => {"username" => "sikachu"}, "username" => "sikachu"},
+ { "user" => { "username" => "sikachu" }, "username" => "sikachu" },
"{\"username\": \"sikachu\"}", "CONTENT_TYPE" => "application/jsonrequest"
)
end
test "parses json with non-object JSON content" do
assert_parses(
- {"user" => {"_json" => "string content" }, "_json" => "string content" },
+ { "user" => { "_json" => "string content" }, "_json" => "string content" },
"\"string content\"", "CONTENT_TYPE" => "application/json"
)
end
@@ -157,7 +157,7 @@ class RootLessJSONParamsParsingTest < ActionDispatch::IntegrationTest
Mime::Type.unregister :json
Mime::Type.register "application/json", :json, %w(application/vnd.rails+json)
assert_parses(
- {"user" => {"username" => "meinac"}, "username" => "meinac"},
+ { "user" => { "username" => "meinac" }, "username" => "meinac" },
"{\"username\": \"meinac\"}", "CONTENT_TYPE" => "application/json"
)
ensure
@@ -171,7 +171,7 @@ class RootLessJSONParamsParsingTest < ActionDispatch::IntegrationTest
Mime::Type.unregister :json
Mime::Type.register "application/json", :json, %w(application/vnd.rails+json)
assert_parses(
- {"user" => {"username" => "meinac"}, "username" => "meinac"},
+ { "user" => { "username" => "meinac" }, "username" => "meinac" },
"{\"username\": \"meinac\"}", "CONTENT_TYPE" => "application/vnd.rails+json"
)
ensure
diff --git a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
index 2714b7f50b..e572c722a0 100644
--- a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
+++ b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb
@@ -32,11 +32,11 @@ class MultipartParamsParsingTest < ActionDispatch::IntegrationTest
end
test "parses bracketed parameters" do
- assert_equal({ "foo" => { "baz" => "bar"}}, parse_multipart("bracketed_param"))
+ assert_equal({ "foo" => { "baz" => "bar" } }, parse_multipart("bracketed_param"))
end
test "parse single utf8 parameter" do
- assert_equal({ "Iñtërnâtiônàlizætiøn_name" => "Iñtërnâtiônàlizætiøn_value"},
+ assert_equal({ "Iñtërnâtiônàlizætiøn_name" => "Iñtërnâtiônàlizætiøn_value" },
parse_multipart("single_utf8_param"), "request.request_parameters")
assert_equal(
"Iñtërnâtiônàlizætiøn_value",
@@ -45,10 +45,10 @@ class MultipartParamsParsingTest < ActionDispatch::IntegrationTest
test "parse bracketed utf8 parameter" do
assert_equal({ "Iñtërnâtiônàlizætiøn_name" => {
- "Iñtërnâtiônàlizætiøn_nested_name" => "Iñtërnâtiônàlizætiøn_value"} },
+ "Iñtërnâtiônàlizætiøn_nested_name" => "Iñtërnâtiônàlizætiøn_value" } },
parse_multipart("bracketed_utf8_param"), "request.request_parameters")
assert_equal(
- {"Iñtërnâtiônàlizætiøn_nested_name" => "Iñtërnâtiônàlizætiøn_value"},
+ { "Iñtërnâtiônàlizætiøn_nested_name" => "Iñtërnâtiônàlizætiøn_value" },
TestController.last_parameters["Iñtërnâtiônàlizætiøn_name"], "request.parameters")
end
diff --git a/actionpack/test/dispatch/request/query_string_parsing_test.rb b/actionpack/test/dispatch/request/query_string_parsing_test.rb
index 6763dbf243..5c992be216 100644
--- a/actionpack/test/dispatch/request/query_string_parsing_test.rb
+++ b/actionpack/test/dispatch/request/query_string_parsing_test.rb
@@ -29,92 +29,92 @@ class QueryStringParsingTest < ActionDispatch::IntegrationTest
test "query string" do
assert_parses(
- {"action" => "create_customer", "full_name" => "David Heinemeier Hansson", "customerId" => "1"},
+ { "action" => "create_customer", "full_name" => "David Heinemeier Hansson", "customerId" => "1" },
"action=create_customer&full_name=David%20Heinemeier%20Hansson&customerId=1"
)
end
test "deep query string" do
assert_parses(
- {"x" => {"y" => {"z" => "10"}}},
+ { "x" => { "y" => { "z" => "10" } } },
"x[y][z]=10"
)
end
test "deep query string with array" do
- assert_parses({"x" => {"y" => {"z" => ["10"]}}}, "x[y][z][]=10")
- assert_parses({"x" => {"y" => {"z" => ["10", "5"]}}}, "x[y][z][]=10&x[y][z][]=5")
+ assert_parses({ "x" => { "y" => { "z" => ["10"] } } }, "x[y][z][]=10")
+ assert_parses({ "x" => { "y" => { "z" => ["10", "5"] } } }, "x[y][z][]=10&x[y][z][]=5")
end
test "deep query string with array of hash" do
- assert_parses({"x" => {"y" => [{"z" => "10"}]}}, "x[y][][z]=10")
- assert_parses({"x" => {"y" => [{"z" => "10", "w" => "10"}]}}, "x[y][][z]=10&x[y][][w]=10")
- assert_parses({"x" => {"y" => [{"z" => "10", "v" => {"w" => "10"}}]}}, "x[y][][z]=10&x[y][][v][w]=10")
+ assert_parses({ "x" => { "y" => [{ "z" => "10" }] } }, "x[y][][z]=10")
+ assert_parses({ "x" => { "y" => [{ "z" => "10", "w" => "10" }] } }, "x[y][][z]=10&x[y][][w]=10")
+ assert_parses({ "x" => { "y" => [{ "z" => "10", "v" => { "w" => "10" } }] } }, "x[y][][z]=10&x[y][][v][w]=10")
end
test "deep query string with array of hashes with one pair" do
- assert_parses({"x" => {"y" => [{"z" => "10"}, {"z" => "20"}]}}, "x[y][][z]=10&x[y][][z]=20")
+ assert_parses({ "x" => { "y" => [{ "z" => "10" }, { "z" => "20" }] } }, "x[y][][z]=10&x[y][][z]=20")
end
test "deep query string with array of hashes with multiple pairs" do
assert_parses(
- {"x" => {"y" => [{"z" => "10", "w" => "a"}, {"z" => "20", "w" => "b"}]}},
+ { "x" => { "y" => [{ "z" => "10", "w" => "a" }, { "z" => "20", "w" => "b" }] } },
"x[y][][z]=10&x[y][][w]=a&x[y][][z]=20&x[y][][w]=b"
)
end
test "query string with nil" do
assert_parses(
- { "action" => "create_customer", "full_name" => ""},
+ { "action" => "create_customer", "full_name" => "" },
"action=create_customer&full_name="
)
end
test "query string with array" do
assert_parses(
- { "action" => "create_customer", "selected" => ["1", "2", "3"]},
+ { "action" => "create_customer", "selected" => ["1", "2", "3"] },
"action=create_customer&selected[]=1&selected[]=2&selected[]=3"
)
end
test "query string with amps" do
assert_parses(
- { "action" => "create_customer", "name" => "Don't & Does"},
+ { "action" => "create_customer", "name" => "Don't & Does" },
"action=create_customer&name=Don%27t+%26+Does"
)
end
test "query string with many equal" do
assert_parses(
- { "action" => "create_customer", "full_name" => "abc=def=ghi"},
+ { "action" => "create_customer", "full_name" => "abc=def=ghi" },
"action=create_customer&full_name=abc=def=ghi"
)
end
test "query string without equal" do
- assert_parses({"action" => nil}, "action")
- assert_parses({"action" => {"foo" => nil}}, "action[foo]")
- assert_parses({"action" => {"foo" => { "bar" => nil }}}, "action[foo][bar]")
- assert_parses({"action" => {"foo" => { "bar" => [] }}}, "action[foo][bar][]")
- assert_parses({"action" => {"foo" => [] }}, "action[foo][]")
- assert_parses({"action"=>{"foo"=>[{"bar"=>nil}]}}, "action[foo][][bar]")
+ assert_parses({ "action" => nil }, "action")
+ assert_parses({ "action" => { "foo" => nil } }, "action[foo]")
+ assert_parses({ "action" => { "foo" => { "bar" => nil } } }, "action[foo][bar]")
+ assert_parses({ "action" => { "foo" => { "bar" => [] } } }, "action[foo][bar][]")
+ assert_parses({ "action" => { "foo" => [] } }, "action[foo][]")
+ assert_parses({ "action"=>{ "foo"=>[{ "bar"=>nil }] } }, "action[foo][][bar]")
end
def test_array_parses_without_nil
- assert_parses({"action" => ["1"]}, "action[]=1&action[]")
+ assert_parses({ "action" => ["1"] }, "action[]=1&action[]")
end
test "perform_deep_munge" do
old_perform_deep_munge = ActionDispatch::Request::Utils.perform_deep_munge
ActionDispatch::Request::Utils.perform_deep_munge = false
begin
- assert_parses({"action" => nil}, "action")
- assert_parses({"action" => {"foo" => nil}}, "action[foo]")
- assert_parses({"action" => {"foo" => {"bar" => nil}}}, "action[foo][bar]")
- assert_parses({"action" => {"foo" => {"bar" => [nil]}}}, "action[foo][bar][]")
- assert_parses({"action" => {"foo" => [nil]}}, "action[foo][]")
- assert_parses({"action" => {"foo" => [{"bar" => nil}]}}, "action[foo][][bar]")
- assert_parses({"action" => ["1",nil]}, "action[]=1&action[]")
+ assert_parses({ "action" => nil }, "action")
+ assert_parses({ "action" => { "foo" => nil } }, "action[foo]")
+ assert_parses({ "action" => { "foo" => { "bar" => nil } } }, "action[foo][bar]")
+ assert_parses({ "action" => { "foo" => { "bar" => [nil] } } }, "action[foo][bar][]")
+ assert_parses({ "action" => { "foo" => [nil] } }, "action[foo][]")
+ assert_parses({ "action" => { "foo" => [{ "bar" => nil }] } }, "action[foo][][bar]")
+ assert_parses({ "action" => ["1",nil] }, "action[]=1&action[]")
ensure
ActionDispatch::Request::Utils.perform_deep_munge = old_perform_deep_munge
end
@@ -129,14 +129,14 @@ class QueryStringParsingTest < ActionDispatch::IntegrationTest
test "query string with many ampersands" do
assert_parses(
- { "action" => "create_customer", "full_name" => "David Heinemeier Hansson"},
+ { "action" => "create_customer", "full_name" => "David Heinemeier Hansson" },
"&action=create_customer&&&full_name=David%20Heinemeier%20Hansson"
)
end
test "unbalanced query string with array" do
assert_parses(
- {"location" => ["1", "2"], "age_group" => ["2"]},
+ { "location" => ["1", "2"], "age_group" => ["2"] },
"location[]=1&location[]=2&age_group[]=2"
)
end
diff --git a/actionpack/test/dispatch/request/session_test.rb b/actionpack/test/dispatch/request/session_test.rb
index cc3c4d48f3..311b80ea0a 100644
--- a/actionpack/test/dispatch/request/session_test.rb
+++ b/actionpack/test/dispatch/request/session_test.rb
@@ -19,7 +19,7 @@ module ActionDispatch
s = Session.create(store, req, {})
s["foo"] = "bar"
assert_equal "bar", s["foo"]
- assert_equal({"foo" => "bar"}, s.to_hash)
+ assert_equal({ "foo" => "bar" }, s.to_hash)
end
def test_create_merges_old
@@ -98,7 +98,7 @@ module ActionDispatch
assert_equal "2", session.fetch(:two, "2")
assert_nil session.fetch(:two, nil)
- assert_equal "three", session.fetch(:three) {|el| el.to_s }
+ assert_equal "three", session.fetch(:three) { |el| el.to_s }
assert_raise KeyError do
session.fetch(:three)
diff --git a/actionpack/test/dispatch/request_id_test.rb b/actionpack/test/dispatch/request_id_test.rb
index 793ce67db4..4fcd45acf5 100644
--- a/actionpack/test/dispatch/request_id_test.rb
+++ b/actionpack/test/dispatch/request_id_test.rb
@@ -50,7 +50,6 @@ class RequestIdResponseTest < ActionDispatch::IntegrationTest
end
end
-
private
def with_test_route_set
diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb
index 0cac971daa..13a87b8976 100644
--- a/actionpack/test/dispatch/request_test.rb
+++ b/actionpack/test/dispatch/request_test.rb
@@ -22,7 +22,7 @@ class BaseRequestTest < ActiveSupport::TestCase
def stub_request(env = {})
ip_spoofing_check = env.key?(:ip_spoofing_check) ? env.delete(:ip_spoofing_check) : true
@trusted_proxies ||= nil
- ip_app = ActionDispatch::RemoteIp.new(Proc.new { }, ip_spoofing_check, @trusted_proxies)
+ ip_app = ActionDispatch::RemoteIp.new(Proc.new {}, ip_spoofing_check, @trusted_proxies)
ActionDispatch::Http::URL.tld_length = env.delete(:tld_length) if env.key?(:tld_length)
ip_app.call(env)
@@ -596,7 +596,7 @@ class RequestParamsParsing < BaseRequestTest
"rack.input" => StringIO.new("flamenco=love")
)
- assert_equal({"flamenco"=> "love"}, request.request_parameters)
+ assert_equal({ "flamenco"=> "love" }, request.request_parameters)
end
test "doesnt interpret request uri as query string when missing" do
@@ -784,21 +784,21 @@ end
class RequestFormat < BaseRequestTest
test "xml format" do
request = stub_request
- assert_called(request, :parameters, times: 2, returns: {format: :xml}) do
+ assert_called(request, :parameters, times: 2, returns: { format: :xml }) do
assert_equal Mime[:xml], request.format
end
end
test "xhtml format" do
request = stub_request
- assert_called(request, :parameters, times: 2, returns: {format: :xhtml}) do
+ assert_called(request, :parameters, times: 2, returns: { format: :xhtml }) do
assert_equal Mime[:html], request.format
end
end
test "txt format" do
request = stub_request
- assert_called(request, :parameters, times: 2, returns: {format: :txt}) do
+ assert_called(request, :parameters, times: 2, returns: { format: :txt }) do
assert_equal Mime[:text], request.format
end
end
@@ -817,14 +817,14 @@ class RequestFormat < BaseRequestTest
test "can override format with parameter negative" do
request = stub_request
- assert_called(request, :parameters, times: 2, returns: {format: :txt}) do
+ assert_called(request, :parameters, times: 2, returns: { format: :txt }) do
assert !request.format.xml?
end
end
test "can override format with parameter positive" do
request = stub_request
- assert_called(request, :parameters, times: 2, returns: {format: :xml}) do
+ assert_called(request, :parameters, times: 2, returns: { format: :xml }) do
assert request.format.xml?
end
end
@@ -852,21 +852,21 @@ class RequestFormat < BaseRequestTest
test "formats format:text with accept header" do
request = stub_request
- assert_called(request, :parameters, times: 2, returns: {format: :txt}) do
+ assert_called(request, :parameters, times: 2, returns: { format: :txt }) do
assert_equal [Mime[:text]], request.formats
end
end
test "formats format:unknown with accept header" do
request = stub_request
- assert_called(request, :parameters, times: 2, returns: {format: :unknown}) do
+ assert_called(request, :parameters, times: 2, returns: { format: :unknown }) do
assert_instance_of Mime::NullType, request.format
end
end
test "format is not nil with unknown format" do
request = stub_request
- assert_called(request, :parameters, times: 2, returns: {format: :hello}) do
+ assert_called(request, :parameters, times: 2, returns: { format: :hello }) do
assert request.format.nil?
assert_not request.format.html?
assert_not request.format.xml?
@@ -921,7 +921,7 @@ class RequestFormat < BaseRequestTest
request = stub_request "HTTP_ACCEPT" => "application/xml",
"HTTP_X_REQUESTED_WITH" => "XMLHttpRequest"
- assert_called(request, :parameters, times: 2, returns: {format: :json}) do
+ assert_called(request, :parameters, times: 2, returns: { format: :json }) do
assert_equal [ Mime[:json] ], request.formats
end
ensure
@@ -997,11 +997,11 @@ class RequestParameters < BaseRequestTest
test "parameters" do
request = stub_request
- assert_called(request, :request_parameters, times: 2, returns: {"foo" => 1}) do
- assert_called(request, :query_parameters, times: 2, returns: {"bar" => 2}) do
- assert_equal({"foo" => 1, "bar" => 2}, request.parameters)
- assert_equal({"foo" => 1}, request.request_parameters)
- assert_equal({"bar" => 2}, request.query_parameters)
+ assert_called(request, :request_parameters, times: 2, returns: { "foo" => 1 }) do
+ assert_called(request, :query_parameters, times: 2, returns: { "bar" => 2 }) do
+ assert_equal({ "foo" => 1, "bar" => 2 }, request.parameters)
+ assert_equal({ "foo" => 1 }, request.request_parameters)
+ assert_equal({ "bar" => 2 }, request.query_parameters)
end
end
end
@@ -1069,18 +1069,17 @@ class RequestParameters < BaseRequestTest
end
end
-
class RequestParameterFilter < BaseRequestTest
test "process parameter filter" do
test_hashes = [
- [{"foo"=>"bar"},{"foo"=>"bar"},%w'food'],
- [{"foo"=>"bar"},{"foo"=>"[FILTERED]"},%w'foo'],
- [{"foo"=>"bar", "bar"=>"foo"},{"foo"=>"[FILTERED]", "bar"=>"foo"},%w'foo baz'],
- [{"foo"=>"bar", "baz"=>"foo"},{"foo"=>"[FILTERED]", "baz"=>"[FILTERED]"},%w'foo baz'],
- [{"bar"=>{"foo"=>"bar","bar"=>"foo"}},{"bar"=>{"foo"=>"[FILTERED]","bar"=>"foo"}},%w'fo'],
- [{"foo"=>{"foo"=>"bar","bar"=>"foo"}},{"foo"=>"[FILTERED]"},%w'f banana'],
- [{"deep"=>{"cc"=>{"code"=>"bar","bar"=>"foo"},"ss"=>{"code"=>"bar"}}},{"deep"=>{"cc"=>{"code"=>"[FILTERED]","bar"=>"foo"},"ss"=>{"code"=>"bar"}}},%w'deep.cc.code'],
- [{"baz"=>[{"foo"=>"baz"}, "1"]}, {"baz"=>[{"foo"=>"[FILTERED]"}, "1"]}, [/foo/]]]
+ [{ "foo"=>"bar" },{ "foo"=>"bar" },%w'food'],
+ [{ "foo"=>"bar" },{ "foo"=>"[FILTERED]" },%w'foo'],
+ [{ "foo"=>"bar", "bar"=>"foo" },{ "foo"=>"[FILTERED]", "bar"=>"foo" },%w'foo baz'],
+ [{ "foo"=>"bar", "baz"=>"foo" },{ "foo"=>"[FILTERED]", "baz"=>"[FILTERED]" },%w'foo baz'],
+ [{ "bar"=>{ "foo"=>"bar","bar"=>"foo" } },{ "bar"=>{ "foo"=>"[FILTERED]","bar"=>"foo" } },%w'fo'],
+ [{ "foo"=>{ "foo"=>"bar","bar"=>"foo" } },{ "foo"=>"[FILTERED]" },%w'f banana'],
+ [{ "deep"=>{ "cc"=>{ "code"=>"bar","bar"=>"foo" },"ss"=>{ "code"=>"bar" } } },{ "deep"=>{ "cc"=>{ "code"=>"[FILTERED]","bar"=>"foo" },"ss"=>{ "code"=>"bar" } } },%w'deep.cc.code'],
+ [{ "baz"=>[{ "foo"=>"baz" }, "1"] }, { "baz"=>[{ "foo"=>"[FILTERED]" }, "1"] }, [/foo/]]]
test_hashes.each do |before_filter, after_filter, filter_words|
parameter_filter = ActionDispatch::Http::ParameterFilter.new(filter_words)
@@ -1092,8 +1091,8 @@ class RequestParameterFilter < BaseRequestTest
}
parameter_filter = ActionDispatch::Http::ParameterFilter.new(filter_words)
- before_filter["barg"] = {:bargain=>"gain", "blah"=>"bar", "bar"=>{"bargain"=>{"blah"=>"foo"}}}
- after_filter["barg"] = {:bargain=>"niag", "blah"=>"[FILTERED]", "bar"=>{"bargain"=>{"blah"=>"[FILTERED]"}}}
+ before_filter["barg"] = { :bargain=>"gain", "blah"=>"bar", "bar"=>{ "bargain"=>{ "blah"=>"foo" } } }
+ after_filter["barg"] = { :bargain=>"niag", "blah"=>"[FILTERED]", "bar"=>{ "bargain"=>{ "blah"=>"[FILTERED]" } } }
assert_equal after_filter, parameter_filter.filter(before_filter)
end
diff --git a/actionpack/test/dispatch/response_test.rb b/actionpack/test/dispatch/response_test.rb
index d539092244..4e547ab7d5 100644
--- a/actionpack/test/dispatch/response_test.rb
+++ b/actionpack/test/dispatch/response_test.rb
@@ -40,7 +40,7 @@ class ResponseTest < ActiveSupport::TestCase
def test_each_isnt_called_if_str_body_is_written
# Controller writes and reads response body
each_counter = 0
- @response.body = Object.new.tap {|o| o.singleton_class.send(:define_method, :each) { |&block| each_counter += 1; block.call "foo" } }
+ @response.body = Object.new.tap { |o| o.singleton_class.send(:define_method, :each) { |&block| each_counter += 1; block.call "foo" } }
@response["X-Foo"] = @response.body
assert_equal 1, each_counter, "#each was not called once"
@@ -224,7 +224,7 @@ class ResponseTest < ActiveSupport::TestCase
@response.set_cookie("user_name", value: "david", path: "/")
_status, headers, _body = @response.to_a
assert_equal "user_name=david; path=/", headers["Set-Cookie"]
- assert_equal({"user_name" => "david"}, @response.cookies)
+ assert_equal({ "user_name" => "david" }, @response.cookies)
end
test "multiple cookies" do
@@ -232,14 +232,14 @@ class ResponseTest < ActiveSupport::TestCase
@response.set_cookie("login", value: "foo&bar", path: "/", expires: Time.utc(2005, 10, 10,5))
_status, headers, _body = @response.to_a
assert_equal "user_name=david; path=/\nlogin=foo%26bar; path=/; expires=Mon, 10 Oct 2005 05:00:00 -0000", headers["Set-Cookie"]
- assert_equal({"login" => "foo&bar", "user_name" => "david"}, @response.cookies)
+ assert_equal({ "login" => "foo&bar", "user_name" => "david" }, @response.cookies)
end
test "delete cookies" do
@response.set_cookie("user_name", value: "david", path: "/")
@response.set_cookie("login", value: "foo&bar", path: "/", expires: Time.utc(2005, 10, 10,5))
@response.delete_cookie("login")
- assert_equal({"user_name" => "david", "login" => nil}, @response.cookies)
+ assert_equal({ "user_name" => "david", "login" => nil }, @response.cookies)
end
test "read ETag and Cache-Control" do
@@ -254,7 +254,7 @@ class ResponseTest < ActiveSupport::TestCase
assert resp.weak_etag?
assert_not resp.strong_etag?
assert_equal('W/"202cb962ac59075b964b07152d234b70"', resp.etag)
- assert_equal({public: true}, resp.cache_control)
+ assert_equal({ public: true }, resp.cache_control)
assert_equal("public", resp.headers["Cache-Control"])
assert_equal('W/"202cb962ac59075b964b07152d234b70"', resp.headers["ETag"])
@@ -461,14 +461,14 @@ class ResponseIntegrationTest < ActionDispatch::IntegrationTest
assert_equal('W/"202cb962ac59075b964b07152d234b70"', @response.headers["ETag"])
assert_equal('W/"202cb962ac59075b964b07152d234b70"', @response.etag)
- assert_equal({public: true}, @response.cache_control)
+ assert_equal({ public: true }, @response.cache_control)
end
test "response cache control from rackish app" do
@app = lambda { |env|
[200,
- {"ETag" => 'W/"202cb962ac59075b964b07152d234b70"',
- "Cache-Control" => "public"}, ["Hello"]]
+ { "ETag" => 'W/"202cb962ac59075b964b07152d234b70"',
+ "Cache-Control" => "public" }, ["Hello"]]
}
get "/"
@@ -478,7 +478,7 @@ class ResponseIntegrationTest < ActionDispatch::IntegrationTest
assert_equal('W/"202cb962ac59075b964b07152d234b70"', @response.headers["ETag"])
assert_equal('W/"202cb962ac59075b964b07152d234b70"', @response.etag)
- assert_equal({public: true}, @response.cache_control)
+ assert_equal({ public: true }, @response.cache_control)
end
test "response charset and content type from railsish app" do
@@ -503,7 +503,7 @@ class ResponseIntegrationTest < ActionDispatch::IntegrationTest
test "response charset and content type from rackish app" do
@app = lambda { |env|
[200,
- {"Content-Type" => "application/xml; charset=utf-16"},
+ { "Content-Type" => "application/xml; charset=utf-16" },
["Hello"]]
}
diff --git a/actionpack/test/dispatch/routing/inspector_test.rb b/actionpack/test/dispatch/routing/inspector_test.rb
index 115770b7cd..a4babf8554 100644
--- a/actionpack/test/dispatch/routing/inspector_test.rb
+++ b/actionpack/test/dispatch/routing/inspector_test.rb
@@ -172,7 +172,7 @@ module ActionDispatch
def test_rails_routes_shows_route_with_defaults
output = draw do
- get "photos/:id" => "photos#show", :defaults => {format: "jpg"}
+ get "photos/:id" => "photos#show", :defaults => { format: "jpg" }
end
assert_equal [
@@ -291,7 +291,7 @@ module ActionDispatch
output = draw do
get "/foo" => redirect("/foo/bar"), :constraints => { subdomain: "admin" }
get "/bar" => redirect(path: "/foo/bar", status: 307)
- get "/foobar" => redirect{ "/foo/bar" }
+ get "/foobar" => redirect { "/foo/bar" }
end
assert_equal [
@@ -338,7 +338,6 @@ module ActionDispatch
" DELETE /admin/posts/:id(.:format) admin/posts#destroy"], output
end
-
def test_regression_route_with_controller_regexp
output = draw do
ActiveSupport::Deprecation.silence do
diff --git a/actionpack/test/dispatch/routing_assertions_test.rb b/actionpack/test/dispatch/routing_assertions_test.rb
index 56ab4e883f..917ce7e668 100644
--- a/actionpack/test/dispatch/routing_assertions_test.rb
+++ b/actionpack/test/dispatch/routing_assertions_test.rb
@@ -98,7 +98,7 @@ class RoutingAssertionsTest < ActionController::TestCase
end
def test_assert_routing_with_extras
- assert_routing("/articles", { controller: "articles", action: "index", page: "1" }, { }, page: "1")
+ assert_routing("/articles", { controller: "articles", action: "index", page: "1" }, {}, page: "1")
end
def test_assert_routing_with_hash_constraint
diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb
index e64dedf817..56be08f54f 100644
--- a/actionpack/test/dispatch/routing_test.rb
+++ b/actionpack/test/dispatch/routing_test.rb
@@ -4,7 +4,7 @@ require "controller/fake_controllers"
class TestRoutingMapper < ActionDispatch::IntegrationTest
SprocketsApp = lambda { |env|
- [200, {"Content-Type" => "text/html"}, ["javascripts"]]
+ [200, { "Content-Type" => "text/html" }, ["javascripts"]]
}
class IpRestrictor
@@ -245,7 +245,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
def test_redirect_proc
draw do
- get "account/proc/:name", to: redirect {|params, req| "/#{params[:name].pluralize}" }
+ get "account/proc/:name", to: redirect { |params, req| "/#{params[:name].pluralize}" }
end
get "/account/proc/person"
@@ -254,7 +254,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
def test_redirect_proc_with_request
draw do
- get "account/proc_req" => redirect {|params, req| "/#{req.method}" }
+ get "account/proc_req" => redirect { |params, req| "/#{req.method}" }
end
get "/account/proc_req"
@@ -480,7 +480,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
# without dup, additional (and possibly unwanted) values will be present in the options (eg. :host)
- original_options = {controller: "projects", action: "status"}
+ original_options = { controller: "projects", action: "status" }
options = original_options.dup
url_for options
@@ -495,7 +495,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
controller = "/projects"
- options = {controller: controller, action: "status", only_path: true}
+ options = { controller: controller, action: "status", only_path: true }
url = url_for(options)
assert_equal "/projects/status", url
@@ -958,15 +958,15 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
end
def test_resource_does_not_modify_passed_options
- options = {id: /.+?/, format: /json|xml/}
+ options = { id: /.+?/, format: /json|xml/ }
draw { resource :user, options }
- assert_equal({id: /.+?/, format: /json|xml/}, options)
+ assert_equal({ id: /.+?/, format: /json|xml/ }, options)
end
def test_resources_does_not_modify_passed_options
- options = {id: /.+?/, format: /json|xml/}
+ options = { id: /.+?/, format: /json|xml/ }
draw { resources :users, options }
- assert_equal({id: /.+?/, format: /json|xml/}, options)
+ assert_equal({ id: /.+?/, format: /json|xml/ }, options)
end
def test_path_names
@@ -2557,7 +2557,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
get "/movies/00001"
assert_equal "Not Found", @response.body
- assert_raises(ActionController::UrlGenerationError){ movie_path(id: "00001") }
+ assert_raises(ActionController::UrlGenerationError) { movie_path(id: "00001") }
get "/movies/0001/reviews"
assert_equal "reviews#index", @response.body
@@ -2565,7 +2565,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
get "/movies/00001/reviews"
assert_equal "Not Found", @response.body
- assert_raises(ActionController::UrlGenerationError){ movie_reviews_path(movie_id: "00001") }
+ assert_raises(ActionController::UrlGenerationError) { movie_reviews_path(movie_id: "00001") }
get "/movies/0001/reviews/0001"
assert_equal "reviews#show", @response.body
@@ -2573,7 +2573,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
get "/movies/00001/reviews/0001"
assert_equal "Not Found", @response.body
- assert_raises(ActionController::UrlGenerationError){ movie_path(movie_id: "00001", id: "00001") }
+ assert_raises(ActionController::UrlGenerationError) { movie_path(movie_id: "00001", id: "00001") }
get "/movies/0001/trailer"
assert_equal "trailers#show", @response.body
@@ -2581,7 +2581,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
get "/movies/00001/trailer"
assert_equal "Not Found", @response.body
- assert_raises(ActionController::UrlGenerationError){ movie_trailer_path(movie_id: "00001") }
+ assert_raises(ActionController::UrlGenerationError) { movie_trailer_path(movie_id: "00001") }
end
def test_only_should_be_read_from_scope
@@ -3009,7 +3009,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
get "/cities", to: "countries#cities"
end
- get "/countries/:country/(*other)", to: redirect{ |params, req| params[:other] ? "/countries/all/#{params[:other]}" : "/countries/all" }
+ get "/countries/:country/(*other)", to: redirect { |params, req| params[:other] ? "/countries/all/#{params[:other]}" : "/countries/all" }
end
get "/countries/France"
@@ -3030,7 +3030,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
scope "/italians" do
get "/writers", to: "italians#writers", constraints: ::TestRoutingMapper::IpRestrictor
get "/sculptors", to: "italians#sculptors"
- get "/painters/:painter", to: "italians#painters", constraints: {painter: /michelangelo/}
+ get "/painters/:painter", to: "italians#painters", constraints: { painter: /michelangelo/ }
end
end
@@ -3120,7 +3120,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
get "/lists/2/todos/1"
assert_equal "Not Found", @response.body
- assert_raises(ActionController::UrlGenerationError){ list_todo_path(list_id: "2", id: "1") }
+ assert_raises(ActionController::UrlGenerationError) { list_todo_path(list_id: "2", id: "1") }
end
def test_redirect_argument_error
@@ -3720,13 +3720,13 @@ class TestAltApp < ActionDispatch::IntegrationTest
class XHeader
def call(env)
- [200, {"Content-Type" => "text/html"}, ["XHeader"]]
+ [200, { "Content-Type" => "text/html" }, ["XHeader"]]
end
end
class AltApp
def call(env)
- [200, {"Content-Type" => "text/html"}, ["Alternative App"]]
+ [200, { "Content-Type" => "text/html" }, ["Alternative App"]]
end
end
@@ -3736,7 +3736,7 @@ class TestAltApp < ActionDispatch::IntegrationTest
end
}.new
AltRoutes.draw do
- get "/" => TestAltApp::XHeader.new, :constraints => {x_header: /HEADER/}
+ get "/" => TestAltApp::XHeader.new, :constraints => { x_header: /HEADER/ }
get "/" => TestAltApp::AltApp.new
end
@@ -3903,7 +3903,7 @@ class TestDefaultScope < ActionDispatch::IntegrationTest
end
DefaultScopeRoutes = ActionDispatch::Routing::RouteSet.new
- DefaultScopeRoutes.default_scope = {module: :blog}
+ DefaultScopeRoutes.default_scope = { module: :blog }
DefaultScopeRoutes.draw do
resources :posts
end
@@ -4144,7 +4144,7 @@ class TestGlobRoutingMapper < ActionDispatch::IntegrationTest
app.draw do
ok = lambda { |env| [200, { "Content-Type" => "text/plain" }, []] }
- get "/*id" => redirect("/not_cars"), :constraints => {id: /dummy/}
+ get "/*id" => redirect("/not_cars"), :constraints => { id: /dummy/ }
get "/cars" => ok
end
end
@@ -4629,24 +4629,24 @@ class TestUrlGenerationErrors < ActionDispatch::IntegrationTest
message = "No route matches #{url.inspect} missing required keys: #{missing.inspect}"
# Optimized url helper
- error = assert_raises(ActionController::UrlGenerationError){ product_path(nil) }
+ error = assert_raises(ActionController::UrlGenerationError) { product_path(nil) }
assert_equal message, error.message
# Non-optimized url helper
- error = assert_raises(ActionController::UrlGenerationError, message){ product_path(id: nil) }
+ error = assert_raises(ActionController::UrlGenerationError, message) { product_path(id: nil) }
assert_equal message, error.message
end
test "url helpers raise message with mixed parameters when generation fails " do
- url, missing = { action: "show", controller: "products", id: nil, "id"=>"url-tested"}, [:id]
+ url, missing = { action: "show", controller: "products", id: nil, "id"=>"url-tested" }, [:id]
message = "No route matches #{url.inspect} missing required keys: #{missing.inspect}"
# Optimized url helper
- error = assert_raises(ActionController::UrlGenerationError){ product_path(nil, "id"=>"url-tested") }
+ error = assert_raises(ActionController::UrlGenerationError) { product_path(nil, "id"=>"url-tested") }
assert_equal message, error.message
# Non-optimized url helper
- error = assert_raises(ActionController::UrlGenerationError, message){ product_path(id: nil, "id"=>"url-tested") }
+ error = assert_raises(ActionController::UrlGenerationError, message) { product_path(id: nil, "id"=>"url-tested") }
assert_equal message, error.message
end
end
diff --git a/actionpack/test/dispatch/session/cache_store_test.rb b/actionpack/test/dispatch/session/cache_store_test.rb
index 5252d93850..a60629a7ee 100644
--- a/actionpack/test/dispatch/session/cache_store_test.rb
+++ b/actionpack/test/dispatch/session/cache_store_test.rb
@@ -156,7 +156,7 @@ class CacheStoreTest < ActionDispatch::IntegrationTest
assert_response :success
assert_not_equal "0xhax", cookies["_session_id"]
assert_equal nil, @cache.read("_session_id:0xhax")
- assert_equal({"foo" => "bar"}, @cache.read("_session_id:#{cookies['_session_id']}"))
+ assert_equal({ "foo" => "bar" }, @cache.read("_session_id:#{cookies['_session_id']}"))
end
end
diff --git a/actionpack/test/dispatch/static_test.rb b/actionpack/test/dispatch/static_test.rb
index 404cc00cd1..f72823a80e 100644
--- a/actionpack/test/dispatch/static_test.rb
+++ b/actionpack/test/dispatch/static_test.rb
@@ -3,7 +3,7 @@ require "zlib"
module StaticTests
DummyApp = lambda { |env|
- [200, {"Content-Type" => "text/plain"}, ["Hello, World!"]]
+ [200, { "Content-Type" => "text/plain" }, ["Hello, World!"]]
}
def setup
@@ -82,7 +82,6 @@ module StaticTests
assert_html "means hello in Japanese\n", get("/foo/#{Rack::Utils.escape("こんにちは.html")}")
end
-
def test_serves_static_file_with_exclamation_mark_in_filename
with_static_file "/foo/foo!bar.html" do |file|
assert_html file, get("/foo/foo%21bar.html")
@@ -169,7 +168,7 @@ module StaticTests
def test_does_not_modify_path_info
file_name = "/gzip/application-a71b3024f80aea3181c09774ca17e712.js"
- env = {"PATH_INFO" => file_name, "HTTP_ACCEPT_ENCODING" => "gzip", "REQUEST_METHOD" => "POST"}
+ env = { "PATH_INFO" => file_name, "HTTP_ACCEPT_ENCODING" => "gzip", "REQUEST_METHOD" => "POST" }
@app.call(env)
assert_equal file_name, env["PATH_INFO"]
end
@@ -267,7 +266,7 @@ class StaticTest < ActiveSupport::TestCase
def setup
super
@root = "#{FIXTURE_LOAD_PATH}/public"
- @app = ActionDispatch::Static.new(DummyApp, @root, headers: {"Cache-Control" => "public, max-age=60"})
+ @app = ActionDispatch::Static.new(DummyApp, @root, headers: { "Cache-Control" => "public, max-age=60" })
end
def public_path
@@ -309,7 +308,7 @@ class StaticEncodingTest < StaticTest
def setup
super
@root = "#{FIXTURE_LOAD_PATH}/公共"
- @app = ActionDispatch::Static.new(DummyApp, @root, headers: {"Cache-Control" => "public, max-age=60"})
+ @app = ActionDispatch::Static.new(DummyApp, @root, headers: { "Cache-Control" => "public, max-age=60" })
end
def public_path
diff --git a/actionpack/test/dispatch/test_request_test.rb b/actionpack/test/dispatch/test_request_test.rb
index 9beab1ee07..35af3076ba 100644
--- a/actionpack/test/dispatch/test_request_test.rb
+++ b/actionpack/test/dispatch/test_request_test.rb
@@ -33,24 +33,24 @@ class TestRequestTest < ActiveSupport::TestCase
assert_equal nil, req.env["HTTP_COOKIE"]
req.cookie_jar["user_name"] = "david"
- assert_cookies({"user_name" => "david"}, req.cookie_jar)
+ assert_cookies({ "user_name" => "david" }, req.cookie_jar)
req.cookie_jar["login"] = "XJ-122"
- assert_cookies({"user_name" => "david", "login" => "XJ-122"}, req.cookie_jar)
+ assert_cookies({ "user_name" => "david", "login" => "XJ-122" }, req.cookie_jar)
assert_nothing_raised do
req.cookie_jar["login"] = nil
- assert_cookies({"user_name" => "david", "login" => nil}, req.cookie_jar)
+ assert_cookies({ "user_name" => "david", "login" => nil }, req.cookie_jar)
end
req.cookie_jar.delete(:login)
- assert_cookies({"user_name" => "david"}, req.cookie_jar)
+ assert_cookies({ "user_name" => "david" }, req.cookie_jar)
req.cookie_jar.clear
assert_cookies({}, req.cookie_jar)
req.cookie_jar.update(user_name: "david")
- assert_cookies({"user_name" => "david"}, req.cookie_jar)
+ assert_cookies({ "user_name" => "david" }, req.cookie_jar)
end
test "does not complain when there is no application config" do
diff --git a/actionpack/test/fixtures/load_me.rb b/actionpack/test/fixtures/load_me.rb
new file mode 100644
index 0000000000..e516512a4e
--- /dev/null
+++ b/actionpack/test/fixtures/load_me.rb
@@ -0,0 +1,2 @@
+class LoadMe
+end
diff --git a/actionpack/test/journey/gtg/transition_table_test.rb b/actionpack/test/journey/gtg/transition_table_test.rb
index 23b05cc5f6..4c8b5032eb 100644
--- a/actionpack/test/journey/gtg/transition_table_test.rb
+++ b/actionpack/test/journey/gtg/transition_table_test.rb
@@ -95,7 +95,7 @@ module ActionDispatch
parser = Journey::Parser.new
paths.map { |x|
ast = parser.parse x
- ast.each { |n| n.memo = ast}
+ ast.each { |n| n.memo = ast }
ast
}
end
diff --git a/actionpack/test/journey/nfa/simulator_test.rb b/actionpack/test/journey/nfa/simulator_test.rb
index 918b971fec..183c892a53 100644
--- a/actionpack/test/journey/nfa/simulator_test.rb
+++ b/actionpack/test/journey/nfa/simulator_test.rb
@@ -49,7 +49,7 @@ module ActionDispatch
parser = Journey::Parser.new
asts = paths.map { |x|
ast = parser.parse x
- ast.each { |n| n.memo = ast}
+ ast.each { |n| n.memo = ast }
ast
}
diff --git a/actionpack/test/journey/path/pattern_test.rb b/actionpack/test/journey/path/pattern_test.rb
index 224ab689fc..d61a8c023a 100644
--- a/actionpack/test/journey/path/pattern_test.rb
+++ b/actionpack/test/journey/path/pattern_test.rb
@@ -194,7 +194,7 @@ module ActionDispatch
end
def test_to_regexp_with_strexp
- path = Pattern.build("/:controller", { }, SEPARATORS, true)
+ path = Pattern.build("/:controller", {}, SEPARATORS, true)
x = %r{\A/([^/.?]+)\Z}
assert_equal(x.source, path.source)
diff --git a/actionpack/test/journey/route_test.rb b/actionpack/test/journey/route_test.rb
index cce5c2ae37..b6414fd101 100644
--- a/actionpack/test/journey/route_test.rb
+++ b/actionpack/test/journey/route_test.rb
@@ -34,7 +34,7 @@ module ActionDispatch
def test_ip_address
path = Path::Pattern.from_string "/messages/:id(.:format)"
- route = Route.build("name", nil, path, {ip: "192.168.1.1"}, [],
+ route = Route.build("name", nil, path, { ip: "192.168.1.1" }, [],
controller: "foo", action: "bar")
assert_equal "192.168.1.1", route.ip
end
@@ -50,43 +50,45 @@ module ActionDispatch
path = Path::Pattern.from_string "/:controller/*extra"
route = Route.build("name", nil, path, {}, [],
controller: "foo", action: "bar")
- assert_equal "/foo/himom", route.format( controller: "foo",
+ assert_equal "/foo/himom", route.format(
+ controller: "foo",
extra: "himom")
end
def test_connects_all_match
path = Path::Pattern.from_string "/:controller(/:action(/:id(.:format)))"
- route = Route.build("name", nil, path, {action: "bar"}, [], controller: "foo")
+ route = Route.build("name", nil, path, { action: "bar" }, [], controller: "foo")
- assert_equal "/foo/bar/10", route.format( controller: "foo",
+ assert_equal "/foo/bar/10", route.format(
+ controller: "foo",
action: "bar",
id: 10)
end
def test_extras_are_not_included_if_optional
path = Path::Pattern.from_string "/page/:id(/:action)"
- route = Route.build("name", nil, path, { }, [], action: "show")
+ route = Route.build("name", nil, path, {}, [], action: "show")
assert_equal "/page/10", route.format(id: 10)
end
def test_extras_are_not_included_if_optional_with_parameter
path = Path::Pattern.from_string "(/sections/:section)/pages/:id"
- route = Route.build("name", nil, path, { }, [], action: "show")
+ route = Route.build("name", nil, path, {}, [], action: "show")
assert_equal "/pages/10", route.format(id: 10)
end
def test_extras_are_not_included_if_optional_parameter_is_nil
path = Path::Pattern.from_string "(/sections/:section)/pages/:id"
- route = Route.build("name", nil, path, { }, [], action: "show")
+ route = Route.build("name", nil, path, {}, [], action: "show")
assert_equal "/pages/10", route.format(id: 10, section: nil)
end
def test_score
constraints = {}
- defaults = {controller: "pages", action: "show"}
+ defaults = { controller: "pages", action: "show" }
path = Path::Pattern.from_string "/page/:id(/:action)(.:format)"
specific = Route.build "name", nil, path, constraints, [:controller, :action], defaults
@@ -94,7 +96,7 @@ module ActionDispatch
path = Path::Pattern.from_string "/:controller(/:action(/:id))(.:format)"
generic = Route.build "name", nil, path, constraints, [], {}
- knowledge = {id: 20, controller: "pages", action: "show"}
+ knowledge = { id: 20, controller: "pages", action: "show" }
routes = [specific, generic]
diff --git a/actionpack/test/journey/router_test.rb b/actionpack/test/journey/router_test.rb
index c75475bffb..2b99637f56 100644
--- a/actionpack/test/journey/router_test.rb
+++ b/actionpack/test/journey/router_test.rb
@@ -58,31 +58,31 @@ module ActionDispatch
get "/foo/:id", id: /\d/, anchor: false, to: "foo#bar"
assert_raises(ActionController::UrlGenerationError) do
- @formatter.generate(nil, { controller: "foo", action: "bar", id: "10" }, { })
+ @formatter.generate(nil, { controller: "foo", action: "bar", id: "10" }, {})
end
end
def test_required_parts_are_verified_when_building
get "/foo/:id", id: /\d+/, anchor: false, to: "foo#bar"
- path, _ = @formatter.generate(nil, { controller: "foo", action: "bar", id: "10" }, { })
+ path, _ = @formatter.generate(nil, { controller: "foo", action: "bar", id: "10" }, {})
assert_equal "/foo/10", path
assert_raises(ActionController::UrlGenerationError) do
- @formatter.generate(nil, { id: "aa" }, { })
+ @formatter.generate(nil, { id: "aa" }, {})
end
end
def test_only_required_parts_are_verified
get "/foo(/:id)", id: /\d/, to: "foo#bar"
- path, _ = @formatter.generate(nil, { controller: "foo", action: "bar", id: "10" }, { })
+ path, _ = @formatter.generate(nil, { controller: "foo", action: "bar", id: "10" }, {})
assert_equal "/foo/10", path
- path, _ = @formatter.generate(nil, { controller: "foo", action: "bar" }, { })
+ path, _ = @formatter.generate(nil, { controller: "foo", action: "bar" }, {})
assert_equal "/foo", path
- path, _ = @formatter.generate(nil, { controller: "foo", action: "bar", id: "aa" }, { })
+ path, _ = @formatter.generate(nil, { controller: "foo", action: "bar", id: "aa" }, {})
assert_equal "/foo/aa", path
end
@@ -91,7 +91,7 @@ module ActionDispatch
get "/foo/:id", as: route_name, id: /\d+/, to: "foo#bar"
error = assert_raises(ActionController::UrlGenerationError) do
- @formatter.generate(route_name, { }, { })
+ @formatter.generate(route_name, {}, {})
end
assert_match(/missing required keys: \[:id\]/, error.message)
@@ -101,7 +101,7 @@ module ActionDispatch
route_name = "gorby_thunderhorse"
error = assert_raises(ActionController::UrlGenerationError) do
- @formatter.generate(route_name, { }, { })
+ @formatter.generate(route_name, {}, {})
end
assert_no_match(/missing required keys: \[\]/, error.message)
@@ -130,12 +130,12 @@ module ActionDispatch
env = rails_env "PATH_INFO" => "/foo/10"
router.recognize(env) do |r, params|
- assert_equal({id: "10", controller: "foo", action: "bar"}, params)
+ assert_equal({ id: "10", controller: "foo", action: "bar" }, params)
end
env = rails_env "PATH_INFO" => "/foo"
router.recognize(env) do |r, params|
- assert_equal({id: nil, controller: "foo", action: "bar"}, params)
+ assert_equal({ id: nil, controller: "foo", action: "bar" }, params)
end
end
@@ -242,9 +242,9 @@ module ActionDispatch
get "/:controller(/:action)", to: "foo#bar"
path, params = @formatter.generate(
- nil, {id: 1, controller: "tasks", action: "show"}, {})
+ nil, { id: 1, controller: "tasks", action: "show" }, {})
assert_equal "/tasks/show", path
- assert_equal({id: 1}, params)
+ assert_equal({ id: 1 }, params)
end
def test_generate_escapes
@@ -277,7 +277,7 @@ module ActionDispatch
relative_url_root: nil
}, {})
assert_equal "/tasks/show", path
- assert_equal({id: 1, relative_url_root: nil}, params)
+ assert_equal({ id: 1, relative_url_root: nil }, params)
end
def test_generate_missing_keys_no_matches_different_format_keys
@@ -297,7 +297,7 @@ module ActionDispatch
}
request_parameters = primarty_parameters.merge(redirection_parameters).merge(missing_parameters)
- message = "No route matches #{Hash[request_parameters.sort_by{|k,v|k.to_s}].inspect} missing required keys: #{[missing_key.to_sym].inspect}"
+ message = "No route matches #{Hash[request_parameters.sort_by { |k,v|k.to_s }].inspect} missing required keys: #{[missing_key.to_sym].inspect}"
error = assert_raises(ActionController::UrlGenerationError) do
@formatter.generate(
@@ -311,7 +311,7 @@ module ActionDispatch
path, params = @formatter.generate(
nil,
- {controller: "tasks", id: 10},
+ { controller: "tasks", id: 10 },
action: "index")
assert_equal "/tasks/index/10", path
assert_equal({}, params)
@@ -322,7 +322,7 @@ module ActionDispatch
path, params = @formatter.generate(
"tasks",
- {controller: "tasks"},
+ { controller: "tasks" },
controller: "tasks", action: "index")
assert_equal "/tasks", path
assert_equal({}, params)
diff --git a/actionview/CHANGELOG.md b/actionview/CHANGELOG.md
index 7754bd8dd9..8bd4e1e56c 100644
--- a/actionview/CHANGELOG.md
+++ b/actionview/CHANGELOG.md
@@ -1,3 +1,27 @@
+* Show cache hits and misses when rendering partials.
+
+ Partials using the `cache` helper will show whether a render hit or missed
+ the cache:
+
+ ```
+ Rendered messages/_message.html.erb in 1.2 ms [cache hit]
+ Rendered recordings/threads/_thread.html.erb in 1.5 ms [cache miss]
+ ```
+
+ This removes the need for the old fragment cache logging:
+
+ ```
+ Read fragment views/v1/2914079/v1/2914079/recordings/70182313-20160225015037000000/d0bdf2974e1ef6d31685c3b392ad0b74 (0.6ms)
+ Rendered messages/_message.html.erb in 1.2 ms [cache hit]
+ Write fragment views/v1/2914079/v1/2914079/recordings/70182313-20160225015037000000/3b4e249ac9d168c617e32e84b99218b5 (1.1ms)
+ Rendered recordings/threads/_thread.html.erb in 1.5 ms [cache miss]
+ ```
+
+ Though that full output can be reenabled with
+ `config.action_controller.enable_fragment_cache_logging = true`.
+
+ *Stan Lo*
+
* Changed partial rendering with a collection to allow collections which
implement `to_a`.
@@ -37,7 +61,7 @@
* Change `datetime_field` and `datetime_field_tag` to generate `datetime-local` fields.
As a new specification of the HTML 5 the text field type `datetime` will no longer exist
- and it is recomended to use `datetime-local`.
+ and it is recommended to use `datetime-local`.
Ref: https://html.spec.whatwg.org/multipage/forms.html#local-date-and-time-state-(type=datetime-local)
*Herminio Torres*
diff --git a/actionview/bin/test b/actionview/bin/test
index 404cabba51..84a05bba08 100755
--- a/actionview/bin/test
+++ b/actionview/bin/test
@@ -1,4 +1,6 @@
#!/usr/bin/env ruby
-COMPONENT_ROOT = File.expand_path("../../", __FILE__)
+
+COMPONENT_ROOT = File.expand_path("..", __dir__)
require File.expand_path("../tools/test", COMPONENT_ROOT)
+
exit Minitest.run(ARGV)
diff --git a/actionview/lib/action_view/base.rb b/actionview/lib/action_view/base.rb
index d9a9d3d8ce..b7c05fdb88 100644
--- a/actionview/lib/action_view/base.rb
+++ b/actionview/lib/action_view/base.rb
@@ -141,7 +141,7 @@ module ActionView #:nodoc:
# Specify the proc used to decorate input tags that refer to attributes with errors.
cattr_accessor :field_error_proc
- @@field_error_proc = Proc.new{ |html_tag, instance| "<div class=\"field_with_errors\">#{html_tag}</div>".html_safe }
+ @@field_error_proc = Proc.new { |html_tag, instance| "<div class=\"field_with_errors\">#{html_tag}</div>".html_safe }
# How to complete the streaming when an exception occurs.
# This is our best guess: first try to close the attribute, then the tag.
diff --git a/actionview/lib/action_view/dependency_tracker.rb b/actionview/lib/action_view/dependency_tracker.rb
index 67d98e9721..451eeec9d6 100644
--- a/actionview/lib/action_view/dependency_tracker.rb
+++ b/actionview/lib/action_view/dependency_tracker.rb
@@ -105,7 +105,6 @@ module ActionView
attr_reader :name, :template
private :name, :template
-
private
def source
template.source
diff --git a/actionview/lib/action_view/helpers/asset_url_helper.rb b/actionview/lib/action_view/helpers/asset_url_helper.rb
index 7bd3027880..76a4893f2e 100644
--- a/actionview/lib/action_view/helpers/asset_url_helper.rb
+++ b/actionview/lib/action_view/helpers/asset_url_helper.rb
@@ -254,7 +254,7 @@ module ActionView
# javascript_path "http://www.example.com/js/xmlhr" # => http://www.example.com/js/xmlhr
# javascript_path "http://www.example.com/js/xmlhr.js" # => http://www.example.com/js/xmlhr.js
def javascript_path(source, options = {})
- path_to_asset(source, {type: :javascript}.merge!(options))
+ path_to_asset(source, { type: :javascript }.merge!(options))
end
alias_method :path_to_javascript, :javascript_path # aliased to avoid conflicts with a javascript_path named route
@@ -266,7 +266,7 @@ module ActionView
# javascript_url "js/xmlhr.js", host: "http://stage.example.com" # => http://stage.example.com/assets/dir/xmlhr.js
#
def javascript_url(source, options = {})
- url_to_asset(source, {type: :javascript}.merge!(options))
+ url_to_asset(source, { type: :javascript }.merge!(options))
end
alias_method :url_to_javascript, :javascript_url # aliased to avoid conflicts with a javascript_url named route
@@ -281,7 +281,7 @@ module ActionView
# stylesheet_path "http://www.example.com/css/style" # => http://www.example.com/css/style
# stylesheet_path "http://www.example.com/css/style.css" # => http://www.example.com/css/style.css
def stylesheet_path(source, options = {})
- path_to_asset(source, {type: :stylesheet}.merge!(options))
+ path_to_asset(source, { type: :stylesheet }.merge!(options))
end
alias_method :path_to_stylesheet, :stylesheet_path # aliased to avoid conflicts with a stylesheet_path named route
@@ -293,7 +293,7 @@ module ActionView
# stylesheet_url "css/style.css", host: "http://stage.example.com" # => http://stage.example.com/css/style.css
#
def stylesheet_url(source, options = {})
- url_to_asset(source, {type: :stylesheet}.merge!(options))
+ url_to_asset(source, { type: :stylesheet }.merge!(options))
end
alias_method :url_to_stylesheet, :stylesheet_url # aliased to avoid conflicts with a stylesheet_url named route
@@ -311,7 +311,7 @@ module ActionView
# The alias +path_to_image+ is provided to avoid that. Rails uses the alias internally, and
# plugin authors are encouraged to do so.
def image_path(source, options = {})
- path_to_asset(source, {type: :image}.merge!(options))
+ path_to_asset(source, { type: :image }.merge!(options))
end
alias_method :path_to_image, :image_path # aliased to avoid conflicts with an image_path named route
@@ -323,7 +323,7 @@ module ActionView
# image_url "edit.png", host: "http://stage.example.com" # => http://stage.example.com/edit.png
#
def image_url(source, options = {})
- url_to_asset(source, {type: :image}.merge!(options))
+ url_to_asset(source, { type: :image }.merge!(options))
end
alias_method :url_to_image, :image_url # aliased to avoid conflicts with an image_url named route
@@ -337,7 +337,7 @@ module ActionView
# video_path("/trailers/hd.avi") # => /trailers/hd.avi
# video_path("http://www.example.com/vid/hd.avi") # => http://www.example.com/vid/hd.avi
def video_path(source, options = {})
- path_to_asset(source, {type: :video}.merge!(options))
+ path_to_asset(source, { type: :video }.merge!(options))
end
alias_method :path_to_video, :video_path # aliased to avoid conflicts with a video_path named route
@@ -349,7 +349,7 @@ module ActionView
# video_url "hd.avi", host: "http://stage.example.com" # => http://stage.example.com/hd.avi
#
def video_url(source, options = {})
- url_to_asset(source, {type: :video}.merge!(options))
+ url_to_asset(source, { type: :video }.merge!(options))
end
alias_method :url_to_video, :video_url # aliased to avoid conflicts with an video_url named route
@@ -363,7 +363,7 @@ module ActionView
# audio_path("/sounds/horse.wav") # => /sounds/horse.wav
# audio_path("http://www.example.com/sounds/horse.wav") # => http://www.example.com/sounds/horse.wav
def audio_path(source, options = {})
- path_to_asset(source, {type: :audio}.merge!(options))
+ path_to_asset(source, { type: :audio }.merge!(options))
end
alias_method :path_to_audio, :audio_path # aliased to avoid conflicts with an audio_path named route
@@ -375,7 +375,7 @@ module ActionView
# audio_url "horse.wav", host: "http://stage.example.com" # => http://stage.example.com/horse.wav
#
def audio_url(source, options = {})
- url_to_asset(source, {type: :audio}.merge!(options))
+ url_to_asset(source, { type: :audio }.merge!(options))
end
alias_method :url_to_audio, :audio_url # aliased to avoid conflicts with an audio_url named route
@@ -388,7 +388,7 @@ module ActionView
# font_path("/dir/font.ttf") # => /dir/font.ttf
# font_path("http://www.example.com/dir/font.ttf") # => http://www.example.com/dir/font.ttf
def font_path(source, options = {})
- path_to_asset(source, {type: :font}.merge!(options))
+ path_to_asset(source, { type: :font }.merge!(options))
end
alias_method :path_to_font, :font_path # aliased to avoid conflicts with an font_path named route
@@ -400,7 +400,7 @@ module ActionView
# font_url "font.ttf", host: "http://stage.example.com" # => http://stage.example.com/font.ttf
#
def font_url(source, options = {})
- url_to_asset(source, {type: :font}.merge!(options))
+ url_to_asset(source, { type: :font }.merge!(options))
end
alias_method :url_to_font, :font_url # aliased to avoid conflicts with an font_url named route
end
diff --git a/actionview/lib/action_view/helpers/atom_feed_helper.rb b/actionview/lib/action_view/helpers/atom_feed_helper.rb
index e5d063e03c..09d243c46d 100644
--- a/actionview/lib/action_view/helpers/atom_feed_helper.rb
+++ b/actionview/lib/action_view/helpers/atom_feed_helper.rb
@@ -112,8 +112,8 @@ module ActionView
end
end
- feed_opts = {"xml:lang" => options[:language] || "en-US", "xmlns" => "http://www.w3.org/2005/Atom"}
- feed_opts.merge!(options).reject!{|k,v| !k.to_s.match(/^xml/)}
+ feed_opts = { "xml:lang" => options[:language] || "en-US", "xmlns" => "http://www.w3.org/2005/Atom" }
+ feed_opts.merge!(options).reject! { |k,v| !k.to_s.match(/^xml/) }
xml.feed(feed_opts) do
xml.id(options[:id] || "tag:#{request.host},#{options[:schema_date]}:#{request.fullpath.split(".")[0]}")
diff --git a/actionview/lib/action_view/helpers/cache_helper.rb b/actionview/lib/action_view/helpers/cache_helper.rb
index 6c3092cc46..b598469d01 100644
--- a/actionview/lib/action_view/helpers/cache_helper.rb
+++ b/actionview/lib/action_view/helpers/cache_helper.rb
@@ -226,7 +226,13 @@ module ActionView
# TODO: Create an object that has caching read/write on it
def fragment_for(name = {}, options = nil, &block) #:nodoc:
- read_fragment_for(name, options) || write_fragment_for(name, options, &block)
+ if content = read_fragment_for(name, options)
+ @log_payload_for_partial_render[:cache_hit] = true if defined?(@log_payload_for_partial_render)
+ content
+ else
+ @log_payload_for_partial_render[:cache_hit] = false if defined?(@log_payload_for_partial_render)
+ write_fragment_for(name, options, &block)
+ end
end
def read_fragment_for(name, options) #:nodoc:
diff --git a/actionview/lib/action_view/helpers/date_helper.rb b/actionview/lib/action_view/helpers/date_helper.rb
index 99db209d63..74c6f0ab1c 100644
--- a/actionview/lib/action_view/helpers/date_helper.rb
+++ b/actionview/lib/action_view/helpers/date_helper.rb
@@ -135,7 +135,7 @@ module ActionView
fyear += 1 if from_time.month >= 3
tyear = to_time.year
tyear -= 1 if to_time.month < 3
- leap_years = (fyear > tyear) ? 0 : (fyear..tyear).count{|x| Date.leap?(x)}
+ leap_years = (fyear > tyear) ? 0 : (fyear..tyear).count { |x| Date.leap?(x) }
minute_offset_for_leap_year = leap_years * 1440
# Discount the leap year days when calculating year distance.
# e.g. if there are 20 leap year days between 2 dates having the same day
@@ -918,7 +918,7 @@ module ActionView
elsif @options[:add_month_numbers]
"#{number} - #{month_names[number]}"
elsif format_string = @options[:month_format_string]
- format_string % {number: number, name: month_names[number]}
+ format_string % { number: number, name: month_names[number] }
else
month_names[number]
end
@@ -1027,7 +1027,7 @@ module ActionView
def prompt_option_tag(type, options)
prompt = case options
when Hash
- default_options = {year: false, month: false, day: false, hour: false, minute: false, second: false}
+ default_options = { year: false, month: false, day: false, hour: false, minute: false, second: false }
default_options.merge!(options)[type.to_sym]
when String
options
diff --git a/actionview/lib/action_view/helpers/form_helper.rb b/actionview/lib/action_view/helpers/form_helper.rb
index f470375988..7d574f0a14 100644
--- a/actionview/lib/action_view/helpers/form_helper.rb
+++ b/actionview/lib/action_view/helpers/form_helper.rb
@@ -468,9 +468,9 @@ module ActionView
options[:url] ||= if options.key?(:format)
polymorphic_path(record, format: options.delete(:format))
- else
- polymorphic_path(record, {})
- end
+ else
+ polymorphic_path(record, {})
+ end
end
private :apply_form_for_options!
@@ -1574,12 +1574,12 @@ module ActionView
record_name = if index
"#{object_name}[#{index}][#{record_name}]"
- elsif record_name.to_s.end_with?("[]")
- record_name = record_name.to_s.sub(/(.*)\[\]$/, "[\\1][#{record_object.id}]")
- "#{object_name}#{record_name}"
- else
- "#{object_name}[#{record_name}]"
- end
+ elsif record_name.to_s.end_with?("[]")
+ record_name = record_name.to_s.sub(/(.*)\[\]$/, "[\\1][#{record_object.id}]")
+ "#{object_name}#{record_name}"
+ else
+ "#{object_name}[#{record_name}]"
+ end
fields_options[:child_index] = index
@template.fields_for(record_name, record_object, fields_options, &block)
diff --git a/actionview/lib/action_view/helpers/javascript_helper.rb b/actionview/lib/action_view/helpers/javascript_helper.rb
index 8f7be4905d..22e1e74ad6 100644
--- a/actionview/lib/action_view/helpers/javascript_helper.rb
+++ b/actionview/lib/action_view/helpers/javascript_helper.rb
@@ -24,7 +24,7 @@ module ActionView
# $('some_element').replaceWith('<%= j render 'some/element_template' %>');
def escape_javascript(javascript)
if javascript
- result = javascript.gsub(/(\\|<\/|\r\n|\342\200\250|\342\200\251|[\n\r"'])/u) {|match| JS_ESCAPE_MAP[match] }
+ result = javascript.gsub(/(\\|<\/|\r\n|\342\200\250|\342\200\251|[\n\r"'])/u) { |match| JS_ESCAPE_MAP[match] }
javascript.html_safe? ? result.html_safe : result
else
""
diff --git a/actionview/lib/action_view/helpers/tag_helper.rb b/actionview/lib/action_view/helpers/tag_helper.rb
index 030d07845b..4950f272a4 100644
--- a/actionview/lib/action_view/helpers/tag_helper.rb
+++ b/actionview/lib/action_view/helpers/tag_helper.rb
@@ -88,9 +88,9 @@ module ActionView
if value.is_a?(Array)
value = escape ? safe_join(value, " ") : value.join(" ")
else
- value = escape ? ERB::Util.unwrapped_html_escape(value) : value
+ value = escape ? ERB::Util.unwrapped_html_escape(value) : value.to_s
end
- %(#{key}="#{value}")
+ %(#{key}="#{value.gsub(/"/, '&quot;'.freeze)}")
end
private
diff --git a/actionview/lib/action_view/helpers/tags/base.rb b/actionview/lib/action_view/helpers/tags/base.rb
index 43335023ce..e3e3c8b109 100644
--- a/actionview/lib/action_view/helpers/tags/base.rb
+++ b/actionview/lib/action_view/helpers/tags/base.rb
@@ -80,8 +80,8 @@ module ActionView
def add_default_name_and_id(options)
index = name_and_id_index(options)
- options["name"] = options.fetch("name"){ tag_name(options["multiple"], index) }
- options["id"] = options.fetch("id"){ tag_id(index) }
+ options["name"] = options.fetch("name") { tag_name(options["multiple"], index) }
+ options["id"] = options.fetch("id") { tag_id(index) }
if namespace = options.delete("namespace")
options["id"] = options["id"] ? "#{namespace}_#{options['id']}" : namespace
end
diff --git a/actionview/lib/action_view/helpers/tags/password_field.rb b/actionview/lib/action_view/helpers/tags/password_field.rb
index 274c27df82..444ef65074 100644
--- a/actionview/lib/action_view/helpers/tags/password_field.rb
+++ b/actionview/lib/action_view/helpers/tags/password_field.rb
@@ -3,7 +3,7 @@ module ActionView
module Tags # :nodoc:
class PasswordField < TextField # :nodoc:
def render
- @options = {value: nil}.merge!(@options)
+ @options = { value: nil }.merge!(@options)
super
end
end
diff --git a/actionview/lib/action_view/helpers/url_helper.rb b/actionview/lib/action_view/helpers/url_helper.rb
index 82aeeedad9..dad0e9dac3 100644
--- a/actionview/lib/action_view/helpers/url_helper.rb
+++ b/actionview/lib/action_view/helpers/url_helper.rb
@@ -570,7 +570,7 @@ module ActionView
html_options
else
- link_to_remote_options?(options) ? {"data-remote" => "true".freeze} : {}
+ link_to_remote_options?(options) ? { "data-remote" => "true".freeze } : {}
end
end
diff --git a/actionview/lib/action_view/layouts.rb b/actionview/lib/action_view/layouts.rb
index b2fcd823d2..b6bf6b9374 100644
--- a/actionview/lib/action_view/layouts.rb
+++ b/actionview/lib/action_view/layouts.rb
@@ -266,7 +266,7 @@ module ActionView
def layout(layout, conditions = {})
include LayoutConditions unless conditions.empty?
- conditions.each {|k, v| conditions[k] = Array(v).map(&:to_s) }
+ conditions.each { |k, v| conditions[k] = Array(v).map(&:to_s) }
self._layout_conditions = conditions
self._layout = layout
diff --git a/actionview/lib/action_view/log_subscriber.rb b/actionview/lib/action_view/log_subscriber.rb
index 34e1a35dc2..c9f308c2a2 100644
--- a/actionview/lib/action_view/log_subscriber.rb
+++ b/actionview/lib/action_view/log_subscriber.rb
@@ -19,7 +19,16 @@ module ActionView
message << " (#{event.duration.round(1)}ms)"
end
end
- alias :render_partial :render_template
+
+ def render_partial(event)
+ info do
+ message = " Rendered #{from_rails_root(event.payload[:identifier])}"
+ message << " within #{from_rails_root(event.payload[:layout])}" if event.payload[:layout]
+ message << " (#{event.duration.round(1)}ms)"
+ message << " #{cache_message(event.payload)}" if event.payload.key?(:cache_hit)
+ message
+ end
+ end
def render_collection(event)
identifier = event.payload[:identifier] || "templates"
@@ -63,6 +72,14 @@ module ActionView
end
end
+ def cache_message(payload)
+ if payload[:cache_hit]
+ "[cache hit]"
+ else
+ "[cache miss]"
+ end
+ end
+
private
def log_rendering_start(payload)
diff --git a/actionview/lib/action_view/lookup_context.rb b/actionview/lib/action_view/lookup_context.rb
index 969bc48bdc..9d6c762cc4 100644
--- a/actionview/lib/action_view/lookup_context.rb
+++ b/actionview/lib/action_view/lookup_context.rb
@@ -21,7 +21,7 @@ module ActionView
self.registered_details = []
def self.register_detail(name, &block)
- self.registered_details << name
+ registered_details << name
Accessors::DEFAULT_PROCS[name] = block
Accessors.send :define_method, :"default_#{name}", &block
diff --git a/actionview/lib/action_view/renderer/partial_renderer.rb b/actionview/lib/action_view/renderer/partial_renderer.rb
index 1509726a37..4314e1ff71 100644
--- a/actionview/lib/action_view/renderer/partial_renderer.rb
+++ b/actionview/lib/action_view/renderer/partial_renderer.rb
@@ -308,9 +308,7 @@ module ActionView
if @collection
render_collection
else
- instrument(:partial) do
- render_partial
- end
+ render_partial
end
end
@@ -331,22 +329,26 @@ module ActionView
end
def render_partial
- view, locals, block = @view, @locals, @block
- object, as = @object, @variable
+ instrument(:partial) do |payload|
+ view, locals, block = @view, @locals, @block
+ object, as = @object, @variable
- if !block && (layout = @options[:layout])
- layout = find_template(layout.to_s, @template_keys)
- end
+ view.instance_variable_set(:@log_payload_for_partial_render, payload)
- object = locals[as] if object.nil? # Respect object when object is false
- locals[as] = object if @has_object
+ if !block && (layout = @options[:layout])
+ layout = find_template(layout.to_s, @template_keys)
+ end
- content = @template.render(view, locals) do |*name|
- view._layout_for(*name, &block)
- end
+ object = locals[as] if object.nil? # Respect object when object is false
+ locals[as] = object if @has_object
- content = layout.render(view, locals){ content } if layout
- content
+ content = @template.render(view, locals) do |*name|
+ view._layout_for(*name, &block)
+ end
+
+ content = layout.render(view, locals) { content } if layout
+ content
+ end
end
# Sets up instance variables needed for rendering a partial. This method
diff --git a/actionview/lib/action_view/renderer/template_renderer.rb b/actionview/lib/action_view/renderer/template_renderer.rb
index 0151653b73..331a5ea228 100644
--- a/actionview/lib/action_view/renderer/template_renderer.rb
+++ b/actionview/lib/action_view/renderer/template_renderer.rb
@@ -63,7 +63,7 @@ module ActionView
if layout
view = @view
view.view_flow.set(:layout, content)
- layout.render(view, locals){ |*name| view._layout_for(*name) }
+ layout.render(view, locals) { |*name| view._layout_for(*name) }
else
content
end
diff --git a/actionview/lib/action_view/template.rb b/actionview/lib/action_view/template.rb
index 1f90cae75b..5480501988 100644
--- a/actionview/lib/action_view/template.rb
+++ b/actionview/lib/action_view/template.rb
@@ -65,8 +65,7 @@ module ActionView
# If you want to provide an alternate mechanism for
# specifying encodings (like ERB does via <%# encoding: ... %>),
# you may indicate that you will handle encodings yourself
- # by implementing <tt>self.handles_encoding?</tt>
- # on your handler.
+ # by implementing <tt>handles_encoding?</tt> on your handler.
#
# If you do, Rails will not try to encode the String
# into the default_internal, passing you the unaltered
diff --git a/actionview/lib/action_view/template/resolver.rb b/actionview/lib/action_view/template/resolver.rb
index 33d60be144..20c2d5c782 100644
--- a/actionview/lib/action_view/template/resolver.rb
+++ b/actionview/lib/action_view/template/resolver.rb
@@ -42,10 +42,10 @@ module ActionView
end
# preallocate all the default blocks for performance/memory consumption reasons
- PARTIAL_BLOCK = lambda {|cache, partial| cache[partial] = SmallCache.new}
- PREFIX_BLOCK = lambda {|cache, prefix| cache[prefix] = SmallCache.new(&PARTIAL_BLOCK)}
- NAME_BLOCK = lambda {|cache, name| cache[name] = SmallCache.new(&PREFIX_BLOCK)}
- KEY_BLOCK = lambda {|cache, key| cache[key] = SmallCache.new(&NAME_BLOCK)}
+ PARTIAL_BLOCK = lambda { |cache, partial| cache[partial] = SmallCache.new }
+ PREFIX_BLOCK = lambda { |cache, prefix| cache[prefix] = SmallCache.new(&PARTIAL_BLOCK) }
+ NAME_BLOCK = lambda { |cache, name| cache[name] = SmallCache.new(&PREFIX_BLOCK) }
+ KEY_BLOCK = lambda { |cache, key| cache[key] = SmallCache.new(&NAME_BLOCK) }
# usually a majority of template look ups return nothing, use this canonical preallocated array to save memory
NO_TEMPLATES = [].freeze
diff --git a/actionview/lib/action_view/test_case.rb b/actionview/lib/action_view/test_case.rb
index 42fa17d1e0..2805cfe612 100644
--- a/actionview/lib/action_view/test_case.rb
+++ b/actionview/lib/action_view/test_case.rb
@@ -24,7 +24,7 @@ module ActionView
def initialize
super
self.class.controller_path = ""
- @request = ActionController::TestRequest.create
+ @request = ActionController::TestRequest.create(self.class)
@response = ActionDispatch::TestResponse.new
@request.env.delete("PATH_INFO")
@@ -145,7 +145,7 @@ module ActionView
def view_rendered?(view, expected_locals)
locals_for(view).any? do |actual_locals|
- expected_locals.all? {|key, value| value == actual_locals[key] }
+ expected_locals.all? { |key, value| value == actual_locals[key] }
end
end
end
diff --git a/actionview/lib/action_view/testing/resolvers.rb b/actionview/lib/action_view/testing/resolvers.rb
index 1a92dd71b1..5cb9f66529 100644
--- a/actionview/lib/action_view/testing/resolvers.rb
+++ b/actionview/lib/action_view/testing/resolvers.rb
@@ -23,7 +23,7 @@ module ActionView #:nodoc:
def query(path, exts, formats, _)
query = ""
EXTENSIONS.each_key do |ext|
- query << "(" << exts[ext].map {|e| e && Regexp.escape(".#{e}") }.join("|") << "|)"
+ query << "(" << exts[ext].map { |e| e && Regexp.escape(".#{e}") }.join("|") << "|)"
end
query = /^(#{Regexp.escape(path)})#{query}$/
@@ -40,7 +40,7 @@ module ActionView #:nodoc:
)
end
- templates.sort_by {|t| -t.identifier.match(/^#{query}$/).captures.reject(&:blank?).size }
+ templates.sort_by { |t| -t.identifier.match(/^#{query}$/).captures.reject(&:blank?).size }
end
end
diff --git a/actionview/lib/action_view/view_paths.rb b/actionview/lib/action_view/view_paths.rb
index 6b6cbcf06a..2ed62ca88f 100644
--- a/actionview/lib/action_view/view_paths.rb
+++ b/actionview/lib/action_view/view_paths.rb
@@ -43,7 +43,7 @@ module ActionView
end
def details_for_lookup
- { }
+ {}
end
def append_view_path(path)
diff --git a/actionview/test/abstract_unit.rb b/actionview/test/abstract_unit.rb
index 1d1e938557..3bb8d21e86 100644
--- a/actionview/test/abstract_unit.rb
+++ b/actionview/test/abstract_unit.rb
@@ -169,7 +169,7 @@ class ActionDispatch::IntegrationTest < ActiveSupport::TestCase
end
def dispatch(controller, action, env)
- [200, {"Content-Type" => "text/html"}, ["#{controller}##{action}"]]
+ [200, { "Content-Type" => "text/html" }, ["#{controller}##{action}"]]
end
end
@@ -204,7 +204,7 @@ class ActionDispatch::IntegrationTest < ActiveSupport::TestCase
ActiveSupport::Dependencies.autoload_paths << path
yield
ensure
- ActiveSupport::Dependencies.autoload_paths.reject! {|p| p == path}
+ ActiveSupport::Dependencies.autoload_paths.reject! { |p| p == path }
ActiveSupport::Dependencies.clear
end
end
diff --git a/actionview/test/actionpack/abstract/abstract_controller_test.rb b/actionview/test/actionpack/abstract/abstract_controller_test.rb
index c92467c15f..863efd15fa 100644
--- a/actionview/test/actionpack/abstract/abstract_controller_test.rb
+++ b/actionview/test/actionpack/abstract/abstract_controller_test.rb
@@ -37,7 +37,7 @@ module AbstractController
def render(options = {})
if options.is_a?(String)
- options = {_template_name: options}
+ options = { _template_name: options }
end
super
end
@@ -189,10 +189,10 @@ module AbstractController
private
def self.layout(formats)
- find_template(name.underscore, {formats: formats}, _prefixes: ["layouts"])
+ find_template(name.underscore, { formats: formats }, _prefixes: ["layouts"])
rescue ActionView::MissingTemplate
begin
- find_template("application", {formats: formats}, _prefixes: ["layouts"])
+ find_template("application", { formats: formats }, _prefixes: ["layouts"])
rescue ActionView::MissingTemplate
end
end
@@ -275,7 +275,7 @@ module AbstractController
end
class Me6 < AbstractController::Base
- self.action_methods
+ action_methods
def index
end
diff --git a/actionview/test/actionpack/controller/render_test.rb b/actionview/test/actionpack/controller/render_test.rb
index 453c2e75d6..cd89dceb45 100644
--- a/actionview/test/actionpack/controller/render_test.rb
+++ b/actionview/test/actionpack/controller/render_test.rb
@@ -186,12 +186,12 @@ class TestController < ApplicationController
def render_file_with_locals
path = File.join(File.dirname(__FILE__), "../../fixtures/test/render_file_with_locals")
- render file: path, locals: {secret: "in the sauce"}
+ render file: path, locals: { secret: "in the sauce" }
end
def render_file_as_string_with_locals
path = File.expand_path(File.join(File.dirname(__FILE__), "../../fixtures/test/render_file_with_locals"))
- render file: path, locals: {secret: "in the sauce"}
+ render file: path, locals: { secret: "in the sauce" }
end
def accessing_request_in_template
@@ -249,7 +249,7 @@ class TestController < ApplicationController
end
def render_line_offset
- render inline: "<% raise %>", locals: {foo: "bar"}
+ render inline: "<% raise %>", locals: { foo: "bar" }
end
def heading
@@ -593,7 +593,7 @@ class TestController < ApplicationController
end
def partial_with_hash_object
- render partial: "hash_object", object: {first_name: "Sam"}
+ render partial: "hash_object", object: { first_name: "Sam" }
end
def partial_with_nested_object
@@ -605,11 +605,11 @@ class TestController < ApplicationController
end
def partial_hash_collection
- render partial: "hash_object", collection: [ {first_name: "Pratik"}, {first_name: "Amy"} ]
+ render partial: "hash_object", collection: [ { first_name: "Pratik" }, { first_name: "Amy" } ]
end
def partial_hash_collection_with_locals
- render partial: "hash_greeting", collection: [ {first_name: "Pratik"}, {first_name: "Amy"} ], locals: { greeting: "Hola" }
+ render partial: "hash_greeting", collection: [ { first_name: "Pratik" }, { first_name: "Amy" } ], locals: { greeting: "Hola" }
end
def partial_with_implicit_local_assignment
diff --git a/actionview/test/actionpack/controller/view_paths_test.rb b/actionview/test/actionpack/controller/view_paths_test.rb
index e676a2ecd4..4c58b959a9 100644
--- a/actionview/test/actionpack/controller/view_paths_test.rb
+++ b/actionview/test/actionpack/controller/view_paths_test.rb
@@ -23,9 +23,9 @@ class ViewLoadPathsTest < ActionController::TestCase
end
def setup
- @request = ActionController::TestRequest.create
- @response = ActionDispatch::TestResponse.new
@controller = TestController.new
+ @request = ActionController::TestRequest.create(@controller.class)
+ @response = ActionDispatch::TestResponse.new
@paths = TestController.view_paths
end
@@ -34,7 +34,7 @@ class ViewLoadPathsTest < ActionController::TestCase
end
def expand(array)
- array.map {|x| File.expand_path(x.to_s)}
+ array.map { |x| File.expand_path(x.to_s) }
end
def assert_paths(*paths)
@@ -131,7 +131,7 @@ class ViewLoadPathsTest < ActionController::TestCase
"Decorated body",
template.identifier,
template.handler,
- virtual_path: template.virtual_path,
+ virtual_path: template.virtual_path,
format: template.formats
)
end
diff --git a/actionview/test/active_record_unit.rb b/actionview/test/active_record_unit.rb
index c757c3392e..7f94b7ebb4 100644
--- a/actionview/test/active_record_unit.rb
+++ b/actionview/test/active_record_unit.rb
@@ -24,12 +24,11 @@ unless defined?(ActiveRecord) && defined?(FixtureSet)
end
$stderr.flush
-
# Define the rest of the connector
class ActiveRecordTestConnector
class << self
def setup
- unless self.connected || !self.able_to_connect
+ unless connected || !able_to_connect
setup_connection
load_schema
require_fixture_models
@@ -65,7 +64,7 @@ class ActiveRecordTestConnector
end
def require_fixture_models
- Dir.glob(File.dirname(__FILE__) + "/fixtures/*.rb").each {|f| require f}
+ Dir.glob(File.dirname(__FILE__) + "/fixtures/*.rb").each { |f| require f }
end
end
end
diff --git a/actionview/test/activerecord/debug_helper_test.rb b/actionview/test/activerecord/debug_helper_test.rb
index 69f9d5d6d6..06ae555a03 100644
--- a/actionview/test/activerecord/debug_helper_test.rb
+++ b/actionview/test/activerecord/debug_helper_test.rb
@@ -11,7 +11,7 @@ class DebugHelperTest < ActionView::TestCase
end
def test_debug_with_marshal_error
- obj = -> { }
+ obj = -> {}
assert_match obj.inspect, Nokogiri.XML(debug(obj)).content
end
end
diff --git a/actionview/test/activerecord/relation_cache_test.rb b/actionview/test/activerecord/relation_cache_test.rb
index 15ddcdd5f6..880e80a8dc 100644
--- a/actionview/test/activerecord/relation_cache_test.rb
+++ b/actionview/test/activerecord/relation_cache_test.rb
@@ -9,7 +9,7 @@ class RelationCacheTest < ActionView::TestCase
end
def test_cache_relation_other
- cache(Project.all){ concat("Hello World") }
+ cache(Project.all) { concat("Hello World") }
assert_equal "Hello World", controller.cache_store.read("views/projects-#{Project.count}/")
end
diff --git a/actionview/test/template/asset_tag_helper_test.rb b/actionview/test/template/asset_tag_helper_test.rb
index 135c3b5fab..3bdab42f7a 100644
--- a/actionview/test/template/asset_tag_helper_test.rb
+++ b/actionview/test/template/asset_tag_helper_test.rb
@@ -470,9 +470,9 @@ class AssetTagHelperTest < ActionView::TestCase
end
def test_image_tag_does_not_modify_options
- options = {size: "16x10"}
+ options = { size: "16x10" }
image_tag("icon", options)
- assert_equal({size: "16x10"}, options)
+ assert_equal({ size: "16x10" }, options)
end
def test_image_tag_raises_an_error_for_competing_size_arguments
@@ -532,11 +532,11 @@ class AssetTagHelperTest < ActionView::TestCase
end
def test_video_audio_tag_does_not_modify_options
- options = {autoplay: true}
+ options = { autoplay: true }
video_tag("video", options)
- assert_equal({autoplay: true}, options)
+ assert_equal({ autoplay: true }, options)
audio_tag("audio", options)
- assert_equal({autoplay: true}, options)
+ assert_equal({ autoplay: true }, options)
end
def test_image_tag_interpreting_email_cid_correctly
diff --git a/actionview/test/template/capture_helper_test.rb b/actionview/test/template/capture_helper_test.rb
index 84f5b721b0..54bf9b4c33 100644
--- a/actionview/test/template/capture_helper_test.rb
+++ b/actionview/test/template/capture_helper_test.rb
@@ -42,7 +42,7 @@ class CaptureHelperTest < ActionView::TestCase
content_for :foo, "foo"
assert_equal "foo", content_for(:foo)
- content_for(:bar){ "bar" }
+ content_for(:bar) { "bar" }
assert_equal "bar", content_for(:bar)
end
diff --git a/actionview/test/template/controller_helper_test.rb b/actionview/test/template/controller_helper_test.rb
index c8ea8bd453..8dd0cedb75 100644
--- a/actionview/test/template/controller_helper_test.rb
+++ b/actionview/test/template/controller_helper_test.rb
@@ -9,13 +9,13 @@ class ControllerHelperTest < ActionView::TestCase
@controller = OpenStruct.new(default_form_builder: SpecializedFormBuilder)
assign_controller(@controller)
- assert_equal SpecializedFormBuilder, self.default_form_builder
+ assert_equal SpecializedFormBuilder, default_form_builder
end
def test_assign_controller_skips_default_form_builder
@controller = OpenStruct.new
assign_controller(@controller)
- assert_nil self.default_form_builder
+ assert_nil default_form_builder
end
end
diff --git a/actionview/test/template/date_helper_i18n_test.rb b/actionview/test/template/date_helper_i18n_test.rb
index a6559bd54f..207c8a683e 100644
--- a/actionview/test/template/date_helper_i18n_test.rb
+++ b/actionview/test/template/date_helper_i18n_test.rb
@@ -112,8 +112,8 @@ class DateHelperSelectTagsI18nTests < ActiveSupport::TestCase
end
def test_date_or_time_select_translates_prompts
- prompt_defaults = {year: "Year", month: "Month", day: "Day", hour: "Hour", minute: "Minute", second: "Seconds"}
- defaults = {[:'date.order', locale: "en", default: []] => %w(year month day)}
+ prompt_defaults = { year: "Year", month: "Month", day: "Day", hour: "Hour", minute: "Minute", second: "Seconds" }
+ defaults = { [:'date.order', locale: "en", default: []] => %w(year month day) }
prompt_defaults.each do |key, prompt|
defaults[[("datetime.prompts." + key.to_s).to_sym, locale: "en"]] = prompt
@@ -143,7 +143,7 @@ class DateHelperSelectTagsI18nTests < ActiveSupport::TestCase
end
def test_date_or_time_select_given_no_order_options_translates_order
- assert_called_with(I18n, :translate, [ [:'date.order', locale: "en", default: []], [:"date.month_names", {locale: "en"}] ], returns: %w(year month day)) do
+ assert_called_with(I18n, :translate, [ [:'date.order', locale: "en", default: []], [:"date.month_names", { locale: "en" }] ], returns: %w(year month day)) do
datetime_select("post", "updated_at", locale: "en")
end
end
@@ -157,7 +157,7 @@ class DateHelperSelectTagsI18nTests < ActiveSupport::TestCase
end
def test_date_or_time_select_given_symbol_keys
- assert_called_with(I18n, :translate, [ [:'date.order', locale: "en", default: []], [:"date.month_names", {locale: "en"}] ], returns: [:year, :month, :day]) do
+ assert_called_with(I18n, :translate, [ [:'date.order', locale: "en", default: []], [:"date.month_names", { locale: "en" }] ], returns: [:year, :month, :day]) do
datetime_select("post", "updated_at", locale: "en")
end
end
diff --git a/actionview/test/template/date_helper_test.rb b/actionview/test/template/date_helper_test.rb
index a40bc1c131..44e5a8c346 100644
--- a/actionview/test/template/date_helper_test.rb
+++ b/actionview/test/template/date_helper_test.rb
@@ -500,7 +500,7 @@ class DateHelperTest < ActionView::TestCase
expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
expected << "</select>\n"
- assert_dom_equal expected, select_year(Time.mktime(2003, 8, 16), {start_year: 2003, end_year: 2005}, class: "selector", accesskey: "M")
+ assert_dom_equal expected, select_year(Time.mktime(2003, 8, 16), { start_year: 2003, end_year: 2005 }, class: "selector", accesskey: "M")
end
def test_select_year_with_default_prompt
@@ -1046,7 +1046,7 @@ class DateHelperTest < ActionView::TestCase
expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n)
expected << "</select>\n"
- assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), {start_year: 2003, end_year: 2005, prefix: "date[first]"}, class: "selector")
+ assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { start_year: 2003, end_year: 2005, prefix: "date[first]" }, class: "selector")
end
def test_select_date_with_separator
@@ -1150,7 +1150,7 @@ class DateHelperTest < ActionView::TestCase
expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n)
expected << "</select>\n"
- assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), {start_year: 2003, end_year: 2005, prefix: "date[first]", with_css_classes: true}, class: "datetime optional")
+ assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { start_year: 2003, end_year: 2005, prefix: "date[first]", with_css_classes: true }, class: "datetime optional")
end
def test_select_date_with_custom_with_css_classes_and_html_class_option
@@ -1166,7 +1166,7 @@ class DateHelperTest < ActionView::TestCase
expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n)
expected << "</select>\n"
- assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), {start_year: 2003, end_year: 2005, with_css_classes: { year: "my-year", month: "my-month", day: "my-day" }}, class: "date optional")
+ assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { start_year: 2003, end_year: 2005, with_css_classes: { year: "my-year", month: "my-month", day: "my-day" } }, class: "date optional")
end
def test_select_date_with_partial_with_css_classes_and_html_class_option
@@ -1182,7 +1182,7 @@ class DateHelperTest < ActionView::TestCase
expected << %(<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16" selected="selected">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n)
expected << "</select>\n"
- assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), {start_year: 2003, end_year: 2005, with_css_classes: { month: "my-month custom-grid" }}, class: "date optional")
+ assert_dom_equal expected, select_date(Time.mktime(2003, 8, 16), { start_year: 2003, end_year: 2005, with_css_classes: { month: "my-month custom-grid" } }, class: "date optional")
end
def test_select_date_with_html_class_option
@@ -1318,7 +1318,6 @@ class DateHelperTest < ActionView::TestCase
expected << %(<option value="2003" selected="selected">2003</option>\n<option value="2004">2004</option>\n<option value="2005">2005</option>\n)
expected << "</select>\n"
-
expected << %(<select id="date_first_month" name="date[first][month]" class="selector">\n)
expected << %(<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option value="6">June</option>\n<option value="7">July</option>\n<option value="8" selected="selected">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n)
expected << "</select>\n"
@@ -1339,7 +1338,7 @@ class DateHelperTest < ActionView::TestCase
expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n<option value="32">32</option>\n<option value="33">33</option>\n<option value="34">34</option>\n<option value="35">35</option>\n<option value="36">36</option>\n<option value="37">37</option>\n<option value="38">38</option>\n<option value="39">39</option>\n<option value="40">40</option>\n<option value="41">41</option>\n<option value="42">42</option>\n<option value="43">43</option>\n<option value="44">44</option>\n<option value="45">45</option>\n<option value="46">46</option>\n<option value="47">47</option>\n<option value="48">48</option>\n<option value="49">49</option>\n<option value="50">50</option>\n<option value="51">51</option>\n<option value="52">52</option>\n<option value="53">53</option>\n<option value="54">54</option>\n<option value="55">55</option>\n<option value="56">56</option>\n<option value="57">57</option>\n<option value="58">58</option>\n<option value="59">59</option>\n)
expected << "</select>\n"
- assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), {start_year: 2003, end_year: 2005, prefix: "date[first]"}, class: "selector")
+ assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), { start_year: 2003, end_year: 2005, prefix: "date[first]" }, class: "selector")
end
def test_select_datetime_with_all_separators
@@ -1371,7 +1370,7 @@ class DateHelperTest < ActionView::TestCase
expected << %(<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04" selected="selected">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n<option value="32">32</option>\n<option value="33">33</option>\n<option value="34">34</option>\n<option value="35">35</option>\n<option value="36">36</option>\n<option value="37">37</option>\n<option value="38">38</option>\n<option value="39">39</option>\n<option value="40">40</option>\n<option value="41">41</option>\n<option value="42">42</option>\n<option value="43">43</option>\n<option value="44">44</option>\n<option value="45">45</option>\n<option value="46">46</option>\n<option value="47">47</option>\n<option value="48">48</option>\n<option value="49">49</option>\n<option value="50">50</option>\n<option value="51">51</option>\n<option value="52">52</option>\n<option value="53">53</option>\n<option value="54">54</option>\n<option value="55">55</option>\n<option value="56">56</option>\n<option value="57">57</option>\n<option value="58">58</option>\n<option value="59">59</option>\n)
expected << "</select>\n"
- assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), { datetime_separator: "&mdash;", date_separator: "/", time_separator: ":", start_year: 2003, end_year: 2005, prefix: "date[first]"}, class: "selector")
+ assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), { datetime_separator: "&mdash;", date_separator: "/", time_separator: ":", start_year: 2003, end_year: 2005, prefix: "date[first]" }, class: "selector")
end
def test_select_datetime_should_work_with_date
@@ -1434,7 +1433,7 @@ class DateHelperTest < ActionView::TestCase
expected << "</select>\n"
assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), start_year: 2003, end_year: 2005, prefix: "date[first]",
- prompt: {day: "Choose day", month: "Choose month", year: "Choose year", hour: "Choose hour", minute: "Choose minute"})
+ prompt: { day: "Choose day", month: "Choose month", year: "Choose year", hour: "Choose hour", minute: "Choose minute" })
end
def test_select_datetime_with_generic_with_css_classes
@@ -1519,7 +1518,7 @@ class DateHelperTest < ActionView::TestCase
expected << "</select>\n"
assert_dom_equal expected, select_datetime(Time.mktime(2003, 8, 16, 8, 4, 18), start_year: 2003, end_year: 2005, start_hour: 1, end_hour: 9, prefix: "date[first]",
- prompt: {day: "Choose day", month: "Choose month", year: "Choose year", hour: "Choose hour", minute: "Choose minute"})
+ prompt: { day: "Choose day", month: "Choose month", year: "Choose year", hour: "Choose hour", minute: "Choose minute" })
end
def test_select_datetime_with_hidden
@@ -1653,7 +1652,7 @@ class DateHelperTest < ActionView::TestCase
expected << "</select>\n"
assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), {}, class: "selector")
- assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), {include_seconds: false}, class: "selector")
+ assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), { include_seconds: false }, class: "selector")
end
def test_select_time_should_work_with_date
@@ -1706,7 +1705,7 @@ class DateHelperTest < ActionView::TestCase
expected << "</select>\n"
assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), include_seconds: true,
- prompt: {hour: "Choose hour", minute: "Choose minute", second: "Choose seconds"})
+ prompt: { hour: "Choose hour", minute: "Choose minute", second: "Choose seconds" })
end
def test_select_time_with_generic_with_css_classes
@@ -1825,7 +1824,7 @@ class DateHelperTest < ActionView::TestCase
expected << "</select>\n"
- assert_dom_equal expected, date_select("post", "written_on", selected: {day: 10, month: 07, year: 2004})
+ assert_dom_equal expected, date_select("post", "written_on", selected: { day: 10, month: 07, year: 2004 })
end
def test_date_select_with_selected_nil
@@ -1953,7 +1952,6 @@ class DateHelperTest < ActionView::TestCase
concat f.date_select(:written_on)
end
-
expected = %{<select id="post_#{id}_written_on_1i" name="post[#{id}][written_on(1i)]">\n<option value="1999">1999</option>\n<option value="2000">2000</option>\n<option value="2001">2001</option>\n<option value="2002">2002</option>\n<option value="2003">2003</option>\n<option selected="selected" value="2004">2004</option>\n<option value="2005">2005</option>\n<option value="2006">2006</option>\n<option value="2007">2007</option>\n<option value="2008">2008</option>\n<option value="2009">2009</option>\n</select>\n}
expected << %{<select id="post_#{id}_written_on_2i" name="post[#{id}][written_on(2i)]">\n<option value="1">January</option>\n<option value="2">February</option>\n<option value="3">March</option>\n<option value="4">April</option>\n<option value="5">May</option>\n<option selected="selected" value="6">June</option>\n<option value="7">July</option>\n<option value="8">August</option>\n<option value="9">September</option>\n<option value="10">October</option>\n<option value="11">November</option>\n<option value="12">December</option>\n</select>\n}
expected << %{<select id="post_#{id}_written_on_3i" name="post[#{id}][written_on(3i)]">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="4">4</option>\n<option value="5">5</option>\n<option value="6">6</option>\n<option value="7">7</option>\n<option value="8">8</option>\n<option value="9">9</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option selected="selected" value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n</select>\n}
@@ -2282,7 +2280,7 @@ class DateHelperTest < ActionView::TestCase
expected << "</select>\n"
- assert_dom_equal expected, date_select("post", "written_on", prompt: {year: "Choose year", month: "Choose month", day: "Choose day"})
+ assert_dom_equal expected, date_select("post", "written_on", prompt: { year: "Choose year", month: "Choose month", day: "Choose day" })
end
def test_date_select_with_generic_with_css_classes
@@ -2528,7 +2526,7 @@ class DateHelperTest < ActionView::TestCase
0.upto(59) { |i| expected << %(<option value="#{sprintf("%02d", i)}"#{' selected="selected"' if i == 16}>#{sprintf("%02d", i)}</option>\n) }
expected << "</select>\n"
- assert_dom_equal expected, time_select("post", "written_on", prompt: {hour: "Choose hour", minute: "Choose minute"})
+ assert_dom_equal expected, time_select("post", "written_on", prompt: { hour: "Choose hour", minute: "Choose minute" })
end
def test_time_select_with_generic_with_css_classes
@@ -2843,7 +2841,7 @@ class DateHelperTest < ActionView::TestCase
expected << %{<option value="">Choose minute</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n<option value="32">32</option>\n<option value="33">33</option>\n<option value="34">34</option>\n<option value="35">35</option>\n<option value="36">36</option>\n<option value="37">37</option>\n<option value="38">38</option>\n<option value="39">39</option>\n<option value="40">40</option>\n<option value="41">41</option>\n<option value="42">42</option>\n<option value="43">43</option>\n<option value="44">44</option>\n<option value="45">45</option>\n<option value="46">46</option>\n<option value="47">47</option>\n<option value="48">48</option>\n<option value="49">49</option>\n<option value="50">50</option>\n<option value="51">51</option>\n<option value="52">52</option>\n<option value="53">53</option>\n<option value="54">54</option>\n<option value="55">55</option>\n<option value="56">56</option>\n<option value="57">57</option>\n<option value="58">58</option>\n<option value="59">59</option>\n}
expected << "</select>\n"
- assert_dom_equal expected, datetime_select("post", "updated_at", start_year: 1999, end_year: 2009, prompt: {year: "Choose year", month: "Choose month", day: "Choose day", hour: "Choose hour", minute: "Choose minute"})
+ assert_dom_equal expected, datetime_select("post", "updated_at", start_year: 1999, end_year: 2009, prompt: { year: "Choose year", month: "Choose month", day: "Choose day", hour: "Choose hour", minute: "Choose minute" })
end
def test_datetime_select_with_generic_with_css_classes
@@ -3614,7 +3612,7 @@ class DateHelperTest < ActionView::TestCase
end
def test_time_tag_with_given_block
- assert_match(/<time.*><span>Right now<\/span><\/time>/, time_tag(Time.now){ raw("<span>Right now</span>") })
+ assert_match(/<time.*><span>Right now<\/span><\/time>/, time_tag(Time.now) { raw("<span>Right now</span>") })
end
def test_time_tag_with_different_format
diff --git a/actionview/test/template/dependency_tracker_test.rb b/actionview/test/template/dependency_tracker_test.rb
index a077d4c448..89917035ff 100644
--- a/actionview/test/template/dependency_tracker_test.rb
+++ b/actionview/test/template/dependency_tracker_test.rb
@@ -15,8 +15,8 @@ class FakeTemplate
end
end
-Neckbeard = lambda {|template| template.source }
-Bowtie = lambda {|template| template.source }
+Neckbeard = lambda { |template| template.source }
+Bowtie = lambda { |template| template.source }
class DependencyTrackerTest < ActionView::TestCase
def tracker
diff --git a/actionview/test/template/digestor_test.rb b/actionview/test/template/digestor_test.rb
index dec75268aa..093ff28c14 100644
--- a/actionview/test/template/digestor_test.rb
+++ b/actionview/test/template/digestor_test.rb
@@ -139,7 +139,7 @@ class TemplateDigestorTest < ActionView::TestCase
end
def test_getting_of_doubly_nested_dependencies
- doubly_nested = [{"comments/comments"=>["comments/comment"]}, "messages/message"]
+ doubly_nested = [{ "comments/comments"=>["comments/comment"] }, "messages/message"]
assert_equal doubly_nested, nested_dependencies("messages/peek")
end
@@ -150,13 +150,13 @@ class TemplateDigestorTest < ActionView::TestCase
end
def test_nested_template_deps
- nested_deps = ["messages/header", {"comments/comments"=>["comments/comment"]}, "messages/actions/move", "events/event", "messages/something_missing", "messages/something_missing_1", "messages/message", "messages/form"]
+ nested_deps = ["messages/header", { "comments/comments"=>["comments/comment"] }, "messages/actions/move", "events/event", "messages/something_missing", "messages/something_missing_1", "messages/message", "messages/form"]
assert_equal nested_deps, nested_dependencies("messages/show")
end
def test_nested_template_deps_with_non_default_rendered_format
finder.rendered_format = nil
- nested_deps = [{"comments/comments"=>["comments/comment"]}]
+ nested_deps = [{ "comments/comments"=>["comments/comment"] }]
assert_equal nested_deps, nested_dependencies("messages/thread")
end
diff --git a/actionview/test/template/form_collections_helper_test.rb b/actionview/test/template/form_collections_helper_test.rb
index 9eb4d8f58f..3774dcf872 100644
--- a/actionview/test/template/form_collections_helper_test.rb
+++ b/actionview/test/template/form_collections_helper_test.rb
@@ -94,7 +94,7 @@ class FormCollectionsHelperTest < ActionView::TestCase
end
test "collection radio accepts html options as the last element of array" do
- collection = [[1, true, {class: "foo"}], [0, false, {class: "bar"}]]
+ collection = [[1, true, { class: "foo" }], [0, false, { class: "bar" }]]
with_collection_radio_buttons :user, :active, collection, :second, :first
assert_select "input[type=radio][value=true].foo#user_active_true"
@@ -102,7 +102,7 @@ class FormCollectionsHelperTest < ActionView::TestCase
end
test "collection radio sets the label class defined inside the block" do
- collection = [[1, true, {class: "foo"}], [0, false, {class: "bar"}]]
+ collection = [[1, true, { class: "foo" }], [0, false, { class: "bar" }]]
with_collection_radio_buttons :user, :active, collection, :second, :first do |b|
b.label(class: "collection_radio_buttons")
end
@@ -112,7 +112,7 @@ class FormCollectionsHelperTest < ActionView::TestCase
end
test "collection radio does not include the input class in the respective label" do
- collection = [[1, true, {class: "foo"}], [0, false, {class: "bar"}]]
+ collection = [[1, true, { class: "foo" }], [0, false, { class: "bar" }]]
with_collection_radio_buttons :user, :active, collection, :second, :first
assert_no_select "label.foo[for=user_active_true]"
@@ -299,7 +299,7 @@ class FormCollectionsHelperTest < ActionView::TestCase
end
test "collection check boxes accepts html options as the last element of array" do
- collection = [[1, "Category 1", {class: "foo"}], [2, "Category 2", {class: "bar"}]]
+ collection = [[1, "Category 1", { class: "foo" }], [2, "Category 2", { class: "bar" }]]
with_collection_check_boxes :user, :active, collection, :first, :second
assert_select 'input[type=checkbox][value="1"].foo'
@@ -307,7 +307,7 @@ class FormCollectionsHelperTest < ActionView::TestCase
end
test "collection check boxes propagates input id to the label for attribute" do
- collection = [[1, "Category 1", {id: "foo"}], [2, "Category 2", {id: "bar"}]]
+ collection = [[1, "Category 1", { id: "foo" }], [2, "Category 2", { id: "bar" }]]
with_collection_check_boxes :user, :active, collection, :first, :second
assert_select 'input[type=checkbox][value="1"]#foo'
@@ -318,7 +318,7 @@ class FormCollectionsHelperTest < ActionView::TestCase
end
test "collection check boxes sets the label class defined inside the block" do
- collection = [[1, "Category 1", {class: "foo"}], [2, "Category 2", {class: "bar"}]]
+ collection = [[1, "Category 1", { class: "foo" }], [2, "Category 2", { class: "bar" }]]
with_collection_check_boxes :user, :active, collection, :second, :first do |b|
b.label(class: "collection_check_boxes")
end
@@ -328,7 +328,7 @@ class FormCollectionsHelperTest < ActionView::TestCase
end
test "collection check boxes does not include the input class in the respective label" do
- collection = [[1, "Category 1", {class: "foo"}], [2, "Category 2", {class: "bar"}]]
+ collection = [[1, "Category 1", { class: "foo" }], [2, "Category 2", { class: "bar" }]]
with_collection_check_boxes :user, :active, collection, :second, :first
assert_no_select "label.foo[for=user_active_category_1]"
@@ -336,7 +336,7 @@ class FormCollectionsHelperTest < ActionView::TestCase
end
test "collection check boxes accepts selected values as :checked option" do
- collection = (1..3).map{|i| [i, "Category #{i}"] }
+ collection = (1..3).map { |i| [i, "Category #{i}"] }
with_collection_check_boxes :user, :category_ids, collection, :first, :last, checked: [1, 3]
assert_select 'input[type=checkbox][value="1"][checked=checked]'
@@ -345,7 +345,7 @@ class FormCollectionsHelperTest < ActionView::TestCase
end
test "collection check boxes accepts selected string values as :checked option" do
- collection = (1..3).map{|i| [i, "Category #{i}"] }
+ collection = (1..3).map { |i| [i, "Category #{i}"] }
with_collection_check_boxes :user, :category_ids, collection, :first, :last, checked: ["1", "3"]
assert_select 'input[type=checkbox][value="1"][checked=checked]'
@@ -354,7 +354,7 @@ class FormCollectionsHelperTest < ActionView::TestCase
end
test "collection check boxes accepts a single checked value" do
- collection = (1..3).map{|i| [i, "Category #{i}"] }
+ collection = (1..3).map { |i| [i, "Category #{i}"] }
with_collection_check_boxes :user, :category_ids, collection, :first, :last, checked: 3
assert_select 'input[type=checkbox][value="3"][checked=checked]'
@@ -364,7 +364,7 @@ class FormCollectionsHelperTest < ActionView::TestCase
test "collection check boxes accepts selected values as :checked option and override the model values" do
user = Struct.new(:category_ids).new(2)
- collection = (1..3).map{|i| [i, "Category #{i}"] }
+ collection = (1..3).map { |i| [i, "Category #{i}"] }
@output_buffer = fields_for(:user, user) do |p|
p.collection_check_boxes :category_ids, collection, :first, :last, checked: [1, 3]
@@ -376,7 +376,7 @@ class FormCollectionsHelperTest < ActionView::TestCase
end
test "collection check boxes accepts multiple disabled items" do
- collection = (1..3).map{|i| [i, "Category #{i}"] }
+ collection = (1..3).map { |i| [i, "Category #{i}"] }
with_collection_check_boxes :user, :category_ids, collection, :first, :last, disabled: [1, 3]
assert_select 'input[type=checkbox][value="1"][disabled=disabled]'
@@ -385,7 +385,7 @@ class FormCollectionsHelperTest < ActionView::TestCase
end
test "collection check boxes accepts single disabled item" do
- collection = (1..3).map{|i| [i, "Category #{i}"] }
+ collection = (1..3).map { |i| [i, "Category #{i}"] }
with_collection_check_boxes :user, :category_ids, collection, :first, :last, disabled: 1
assert_select 'input[type=checkbox][value="1"][disabled=disabled]'
@@ -394,7 +394,7 @@ class FormCollectionsHelperTest < ActionView::TestCase
end
test "collection check boxes accepts a proc to disabled items" do
- collection = (1..3).map{|i| [i, "Category #{i}"] }
+ collection = (1..3).map { |i| [i, "Category #{i}"] }
with_collection_check_boxes :user, :category_ids, collection, :first, :last, disabled: proc { |i| i.first == 1 }
assert_select 'input[type=checkbox][value="1"][disabled=disabled]'
@@ -403,7 +403,7 @@ class FormCollectionsHelperTest < ActionView::TestCase
end
test "collection check boxes accepts multiple readonly items" do
- collection = (1..3).map{|i| [i, "Category #{i}"] }
+ collection = (1..3).map { |i| [i, "Category #{i}"] }
with_collection_check_boxes :user, :category_ids, collection, :first, :last, readonly: [1, 3]
assert_select 'input[type=checkbox][value="1"][readonly=readonly]'
@@ -412,7 +412,7 @@ class FormCollectionsHelperTest < ActionView::TestCase
end
test "collection check boxes accepts single readonly item" do
- collection = (1..3).map{|i| [i, "Category #{i}"] }
+ collection = (1..3).map { |i| [i, "Category #{i}"] }
with_collection_check_boxes :user, :category_ids, collection, :first, :last, readonly: 1
assert_select 'input[type=checkbox][value="1"][readonly=readonly]'
@@ -421,7 +421,7 @@ class FormCollectionsHelperTest < ActionView::TestCase
end
test "collection check boxes accepts a proc to readonly items" do
- collection = (1..3).map{|i| [i, "Category #{i}"] }
+ collection = (1..3).map { |i| [i, "Category #{i}"] }
with_collection_check_boxes :user, :category_ids, collection, :first, :last, readonly: proc { |i| i.first == 1 }
assert_select 'input[type=checkbox][value="1"][readonly=readonly]'
diff --git a/actionview/test/template/form_helper_test.rb b/actionview/test/template/form_helper_test.rb
index ed58818602..e82905175a 100644
--- a/actionview/test/template/form_helper_test.rb
+++ b/actionview/test/template/form_helper_test.rb
@@ -16,7 +16,8 @@ class FormHelperTest < ActionView::TestCase
setup do
# Create "label" locale for testing I18n label helpers
- I18n.backend.store_translations "label", activemodel: {
+ I18n.backend.store_translations "label",
+ activemodel: {
attributes: {
post: {
cost: "Total cost"
@@ -47,7 +48,8 @@ class FormHelperTest < ActionView::TestCase
}
# Create "submit" locale for testing I18n submit helpers
- I18n.backend.store_translations "submit", helpers: {
+ I18n.backend.store_translations "submit",
+ helpers: {
submit: {
create: "Create %{model}",
update: "Confirm %{model} changes",
@@ -58,7 +60,8 @@ class FormHelperTest < ActionView::TestCase
}
}
- I18n.backend.store_translations "placeholder", activemodel: {
+ I18n.backend.store_translations "placeholder",
+ activemodel: {
attributes: {
post: {
cost: "Total cost"
@@ -2257,7 +2260,6 @@ class FormHelperTest < ActionView::TestCase
assert_dom_equal expected, output_buffer
end
-
def test_nested_fields_for_with_nested_collections
form_for(@post, as: "post[]") do |f|
concat f.text_field(:title)
@@ -3437,7 +3439,7 @@ class FormHelperTest < ActionView::TestCase
end
end
- form_for(@post, builder: builder_class) { }
+ form_for(@post, builder: builder_class) {}
assert_equal 1, initialization_count, "form builder instantiated more than once"
end
diff --git a/actionview/test/template/form_options_helper_test.rb b/actionview/test/template/form_options_helper_test.rb
index 84c322e522..477d4f9eca 100644
--- a/actionview/test/template/form_options_helper_test.rb
+++ b/actionview/test/template/form_options_helper_test.rb
@@ -57,7 +57,6 @@ class FormOptionsHelperTest < ActionView::TestCase
)
end
-
def test_collection_options_with_preselected_value
assert_dom_equal(
"<option value=\"&lt;Abe&gt;\">&lt;Abe&gt; went home</option>\n<option value=\"Babe\" selected=\"selected\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>",
@@ -75,7 +74,7 @@ class FormOptionsHelperTest < ActionView::TestCase
def test_collection_options_with_proc_for_selected
assert_dom_equal(
"<option value=\"&lt;Abe&gt;\">&lt;Abe&gt; went home</option>\n<option value=\"Babe\" selected=\"selected\">Babe went home</option>\n<option value=\"Cabe\">Cabe went home</option>",
- options_from_collection_for_select(dummy_posts, "author_name", "title", lambda{|p| p.author_name == "Babe" })
+ options_from_collection_for_select(dummy_posts, "author_name", "title", lambda { |p| p.author_name == "Babe" })
)
end
@@ -103,7 +102,7 @@ class FormOptionsHelperTest < ActionView::TestCase
def test_collection_options_with_proc_for_disabled
assert_dom_equal(
"<option value=\"&lt;Abe&gt;\">&lt;Abe&gt; went home</option>\n<option value=\"Babe\" disabled=\"disabled\">Babe went home</option>\n<option value=\"Cabe\" disabled=\"disabled\">Cabe went home</option>",
- options_from_collection_for_select(dummy_posts, "author_name", "title", disabled: lambda {|p| %w(Babe Cabe).include?(p.author_name)})
+ options_from_collection_for_select(dummy_posts, "author_name", "title", disabled: lambda { |p| %w(Babe Cabe).include?(p.author_name) })
)
end
@@ -637,7 +636,7 @@ class FormOptionsHelperTest < ActionView::TestCase
end
def test_select_with_multiple_and_without_hidden_input
- output_buffer = select(:post, :category, "", {include_hidden: false}, multiple: true)
+ output_buffer = select(:post, :category, "", { include_hidden: false }, multiple: true)
assert_dom_equal(
"<select multiple=\"multiple\" id=\"post_category\" name=\"post[category][]\"></select>",
output_buffer
@@ -645,7 +644,7 @@ class FormOptionsHelperTest < ActionView::TestCase
end
def test_select_with_multiple_and_with_explicit_name_ending_with_brackets
- output_buffer = select(:post, :category, [], {include_hidden: false}, multiple: true, name: "post[category][]")
+ output_buffer = select(:post, :category, [], { include_hidden: false }, multiple: true, name: "post[category][]")
assert_dom_equal(
"<select multiple=\"multiple\" id=\"post_category\" name=\"post[category][]\"></select>",
output_buffer
@@ -1314,21 +1313,21 @@ class FormOptionsHelperTest < ActionView::TestCase
def test_option_html_attributes_with_single_element_hash
assert_equal(
- {class: "fancy"},
+ { class: "fancy" },
option_html_attributes([ "foo", "bar", { class: "fancy" } ])
)
end
def test_option_html_attributes_with_multiple_element_hash
assert_equal(
- {:class => "fancy", "onclick" => "alert('Hello World');"},
+ { :class => "fancy", "onclick" => "alert('Hello World');" },
option_html_attributes([ "foo", "bar", { :class => "fancy", "onclick" => "alert('Hello World');" } ])
)
end
def test_option_html_attributes_with_multiple_hashes
assert_equal(
- {:class => "fancy", "onclick" => "alert('Hello World');"},
+ { :class => "fancy", "onclick" => "alert('Hello World');" },
option_html_attributes([ "foo", "bar", { class: "fancy" }, { "onclick" => "alert('Hello World');" } ])
)
end
diff --git a/actionview/test/template/form_tag_helper_test.rb b/actionview/test/template/form_tag_helper_test.rb
index 52f32e9f0e..da929cac8f 100644
--- a/actionview/test/template/form_tag_helper_test.rb
+++ b/actionview/test/template/form_tag_helper_test.rb
@@ -183,7 +183,7 @@ class FormTagHelperTest < ActionView::TestCase
end
def test_multiple_field_tags_with_same_options
- options = {class: "important"}
+ options = { class: "important" }
assert_dom_equal %(<input name="title" type="file" id="title" class="important"/>), file_field_tag("title", options)
assert_dom_equal %(<input type="password" name="title" id="title" value="Hello!" class="important" />), password_field_tag("title", "Hello!", options)
assert_dom_equal %(<input type="text" name="title" id="title" value="Hello!" class="important" />), text_field_tag("title", "Hello!", options)
@@ -517,7 +517,6 @@ class FormTagHelperTest < ActionView::TestCase
)
end
-
def test_button_tag
assert_dom_equal(
%(<button name="button" type="submit">Button</button>),
diff --git a/actionview/test/template/log_subscriber_test.rb b/actionview/test/template/log_subscriber_test.rb
index 565eee6628..ece059484c 100644
--- a/actionview/test/template/log_subscriber_test.rb
+++ b/actionview/test/template/log_subscriber_test.rb
@@ -30,6 +30,18 @@ class AVLogSubscriberTest < ActiveSupport::TestCase
ActionView::Base.logger = logger
end
+ def set_cache_controller
+ controller = ActionController::Base.new
+ controller.perform_caching = true
+ controller.cache_store = ActiveSupport::Cache::MemoryStore.new
+ @view.controller = controller
+ end
+
+ def set_view_cache_dependencies
+ def @view.view_cache_dependencies; []; end
+ def @view.fragment_cache_key(*); "ahoy `controller` dependency"; end
+ end
+
def test_render_file_template
Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do
@view.render(file: "test/hello_world")
@@ -63,23 +75,60 @@ class AVLogSubscriberTest < ActiveSupport::TestCase
end
end
- def test_render_partial_template
+ def test_render_partial_with_implicit_path
Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do
- @view.render(partial: "test/customer")
+ @view.render(Customer.new("david"), greeting: "hi")
wait
assert_equal 1, @logger.logged(:info).size
- assert_match(/Rendered test\/_customer.erb/, @logger.logged(:info).last)
+ assert_match(/Rendered customers\/_customer\.html\.erb/, @logger.logged(:info).last)
end
end
- def test_render_partial_with_implicit_path
+ def test_render_partial_with_cache_missed
Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do
- @view.render(Customer.new("david"), greeting: "hi")
+ set_view_cache_dependencies
+ set_cache_controller
+
+ @view.render(partial: "test/cached_customer", locals: { cached_customer: Customer.new("david") })
wait
assert_equal 1, @logger.logged(:info).size
- assert_match(/Rendered customers\/_customer\.html\.erb/, @logger.logged(:info).last)
+ assert_match(/Rendered test\/_cached_customer\.erb (.*) \[cache miss\]/, @logger.logged(:info).last)
+ end
+ end
+
+ def test_render_partial_with_cache_hitted
+ Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do
+ set_view_cache_dependencies
+ set_cache_controller
+
+ @view.render(partial: "test/cached_customer", locals: { cached_customer: Customer.new("david") })
+ # Second render should hit cache.
+ @view.render(partial: "test/cached_customer", locals: { cached_customer: Customer.new("david") })
+ wait
+
+ assert_equal 2, @logger.logged(:info).size
+ assert_match(/Rendered test\/_cached_customer\.erb (.*) \[cache hit\]/, @logger.logged(:info).last)
+ end
+ end
+
+ def test_render_partial_with_cache_hitted_and_missed
+ Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do
+ set_view_cache_dependencies
+ set_cache_controller
+
+ @view.render(partial: "test/cached_customer", locals: { cached_customer: Customer.new("david") })
+ wait
+ assert_match(/Rendered test\/_cached_customer\.erb (.*) \[cache miss\]/, @logger.logged(:info).last)
+
+ @view.render(partial: "test/cached_customer", locals: { cached_customer: Customer.new("david") })
+ wait
+ assert_match(/Rendered test\/_cached_customer\.erb (.*) \[cache hit\]/, @logger.logged(:info).last)
+
+ @view.render(partial: "test/cached_customer", locals: { cached_customer: Customer.new("Stan") })
+ wait
+ assert_match(/Rendered test\/_cached_customer\.erb (.*) \[cache miss\]/, @logger.logged(:info).last)
end
end
@@ -115,8 +164,7 @@ class AVLogSubscriberTest < ActiveSupport::TestCase
def test_render_collection_with_cached_set
Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do
- def @view.view_cache_dependencies; []; end
- def @view.fragment_cache_key(*); "ahoy `controller` dependency"; end
+ set_view_cache_dependencies
@view.render(partial: "customers/customer", collection: [ Customer.new("david"), Customer.new("mary") ], cached: true,
locals: { greeting: "hi" })
diff --git a/actionview/test/template/lookup_context_test.rb b/actionview/test/template/lookup_context_test.rb
index 77fab5652f..40d8d6f3b8 100644
--- a/actionview/test/template/lookup_context_test.rb
+++ b/actionview/test/template/lookup_context_test.rb
@@ -279,7 +279,7 @@ class TestMissingTemplate < ActiveSupport::TestCase
test "if a single prefix is passed as a string and the lookup fails, MissingTemplate accepts it" do
e = assert_raise ActionView::MissingTemplate do
- details = {handlers: [], formats: [], variants: [], locale: []}
+ details = { handlers: [], formats: [], variants: [], locale: [] }
@lookup_context.view_paths.find("foo", "parent", true, details)
end
assert_match %r{Missing partial parent/_foo with .* Searched in:\n \* "/Path/to/views"\n}, e.message
diff --git a/actionview/test/template/number_helper_test.rb b/actionview/test/template/number_helper_test.rb
index d55651bd4a..2a2ada2b36 100644
--- a/actionview/test/template/number_helper_test.rb
+++ b/actionview/test/template/number_helper_test.rb
@@ -80,7 +80,7 @@ class NumberHelperTest < ActionView::TestCase
#Including fractionals
distance = { mili: "<b>mm</b>", centi: "<b>cm</b>", deci: "<b>dm</b>", unit: "<b>m</b>",
ten: "<b>dam</b>", hundred: "<b>hm</b>", thousand: "<b>km</b>",
- micro: "<b>um</b>", nano: "<b>nm</b>", pico: "<b>pm</b>", femto: "<b>fm</b>"}
+ micro: "<b>um</b>", nano: "<b>nm</b>", pico: "<b>pm</b>", femto: "<b>fm</b>" }
assert_equal "1.23 &lt;b&gt;mm&lt;/b&gt;", number_to_human(0.00123, units: distance)
assert_equal "1.23 &lt;b&gt;cm&lt;/b&gt;", number_to_human(0.0123, units: distance)
assert_equal "1.23 &lt;b&gt;dm&lt;/b&gt;", number_to_human(0.123, units: distance)
@@ -117,7 +117,7 @@ class NumberHelperTest < ActionView::TestCase
def test_number_to_human_with_custom_translation_scope
I18n.backend.store_translations "ts",
- custom_units_for_number_to_human: {mili: "mm", centi: "cm", deci: "dm", unit: "m", ten: "dam", hundred: "hm", thousand: "km"}
+ custom_units_for_number_to_human: { mili: "mm", centi: "cm", deci: "dm", unit: "m", ten: "dam", hundred: "hm", thousand: "km" }
assert_equal "1.01 cm", number_to_human(0.0101, locale: "ts", units: :custom_units_for_number_to_human)
ensure
I18n.reload!
diff --git a/actionview/test/template/render_test.rb b/actionview/test/template/render_test.rb
index 173c2c4cec..7c8a6aae47 100644
--- a/actionview/test/template/render_test.rb
+++ b/actionview/test/template/render_test.rb
@@ -362,12 +362,12 @@ module RenderTestCases
def test_render_partial_with_object_uses_render_partial_path
assert_equal "Hello: lifo",
- @controller_view.render(partial: Customer.new("lifo"), locals: {greeting: "Hello"})
+ @controller_view.render(partial: Customer.new("lifo"), locals: { greeting: "Hello" })
end
def test_render_partial_with_object_and_format_uses_render_partial_path
assert_equal "<greeting>Hello</greeting><name>lifo</name>",
- @controller_view.render(partial: Customer.new("lifo"), formats: :xml, locals: {greeting: "Hello"})
+ @controller_view.render(partial: Customer.new("lifo"), formats: :xml, locals: { greeting: "Hello" })
end
def test_render_partial_using_object
@@ -520,12 +520,12 @@ module RenderTestCases
def test_render_partial_and_layout_without_block_with_locals
assert_equal %(Before (Foo!)\npartial html\nAfter),
- @view.render(partial: "test/partial", layout: "test/layout_for_partial", locals: { name: "Foo!"})
+ @view.render(partial: "test/partial", layout: "test/layout_for_partial", locals: { name: "Foo!" })
end
def test_render_partial_and_layout_without_block_with_locals_and_rendering_another_partial
assert_equal %(Before (Foo!)\npartial html\npartial with partial\n\nAfter),
- @view.render(partial: "test/partial_with_partial", layout: "test/layout_for_partial", locals: { name: "Foo!"})
+ @view.render(partial: "test/partial_with_partial", layout: "test/layout_for_partial", locals: { name: "Foo!" })
end
def test_render_partial_shortcut_with_block_content
@@ -535,17 +535,17 @@ module RenderTestCases
def test_render_layout_with_a_nested_render_layout_call
assert_equal %(Before (Foo!)\nBefore (Bar!)\npartial html\nAfter\npartial with layout\n\nAfter),
- @view.render(partial: "test/partial_with_layout", layout: "test/layout_for_partial", locals: { name: "Foo!"})
+ @view.render(partial: "test/partial_with_layout", layout: "test/layout_for_partial", locals: { name: "Foo!" })
end
def test_render_layout_with_a_nested_render_layout_call_using_block_with_render_partial
assert_equal %(Before (Foo!)\nBefore (Bar!)\n\n partial html\n\nAfterpartial with layout\n\nAfter),
- @view.render(partial: "test/partial_with_layout_block_partial", layout: "test/layout_for_partial", locals: { name: "Foo!"})
+ @view.render(partial: "test/partial_with_layout_block_partial", layout: "test/layout_for_partial", locals: { name: "Foo!" })
end
def test_render_layout_with_a_nested_render_layout_call_using_block_with_render_content
assert_equal %(Before (Foo!)\nBefore (Bar!)\n\n Content from inside layout!\n\nAfterpartial with layout\n\nAfter),
- @view.render(partial: "test/partial_with_layout_block_content", layout: "test/layout_for_partial", locals: { name: "Foo!"})
+ @view.render(partial: "test/partial_with_layout_block_content", layout: "test/layout_for_partial", locals: { name: "Foo!" })
end
def test_render_partial_with_layout_raises_descriptive_error
diff --git a/actionview/test/template/tag_helper_test.rb b/actionview/test/template/tag_helper_test.rb
index 281fec7291..278c3e855f 100644
--- a/actionview/test/template/tag_helper_test.rb
+++ b/actionview/test/template/tag_helper_test.rb
@@ -59,6 +59,14 @@ class TagHelperTest < ActionView::TestCase
assert_equal "<p included=\"\"></p>", tag.p(included: "")
end
+ def test_tag_options_accepts_symbol_option_when_not_escaping
+ assert_equal "<p value=\"symbol\" />", tag("p", { value: :symbol }, false, false)
+ end
+
+ def test_tag_options_accepts_integer_option_when_not_escaping
+ assert_equal "<p value=\"42\" />", tag("p", { value: 42 }, false, false)
+ end
+
def test_tag_options_converts_boolean_option
assert_dom_equal '<p disabled="disabled" itemscope="itemscope" multiple="multiple" readonly="readonly" allowfullscreen="allowfullscreen" seamless="seamless" typemustmatch="typemustmatch" sortable="sortable" default="default" inert="inert" truespeed="truespeed" />',
tag("p", disabled: true, itemscope: true, multiple: true, readonly: true, allowfullscreen: true, seamless: true, typemustmatch: true, sortable: true, default: true, inert: true, truespeed: true)
@@ -163,7 +171,7 @@ class TagHelperTest < ActionView::TestCase
content_tag("p") { content_tag("b", "Hello") },
output_buffer
assert_equal tag.p(tag.b("Hello")),
- tag.p {tag.b("Hello") },
+ tag.p { tag.b("Hello") },
output_buffer
end
@@ -195,10 +203,10 @@ class TagHelperTest < ActionView::TestCase
end
def test_content_tag_with_unescaped_array_class
- str = content_tag("p", "limelight", {class: ["song", "play>"]}, false)
+ str = content_tag("p", "limelight", { class: ["song", "play>"] }, false)
assert_equal "<p class=\"song play>\">limelight</p>", str
- str = content_tag("p", "limelight", {class: ["song", ["play>"]]}, false)
+ str = content_tag("p", "limelight", { class: ["song", ["play>"]] }, false)
assert_equal "<p class=\"song play>\">limelight</p>", str
end
@@ -220,7 +228,7 @@ class TagHelperTest < ActionView::TestCase
end
def test_content_tag_with_unescaped_empty_array_class
- str = content_tag("p", "limelight", {class: []}, false)
+ str = content_tag("p", "limelight", { class: [] }, false)
assert_equal '<p class="">limelight</p>', str
end
@@ -274,6 +282,16 @@ class TagHelperTest < ActionView::TestCase
assert_equal '<p class="song> play&gt;"></p>', tag.p(class: [raw("song>"), "play>"])
end
+ def test_tag_does_not_honor_html_safe_double_quotes_as_attributes
+ assert_dom_equal '<p title="&quot;">content</p>',
+ content_tag('p', "content", title: '"'.html_safe)
+ end
+
+ def test_data_tag_does_not_honor_html_safe_double_quotes_as_attributes
+ assert_dom_equal '<p data-title="&quot;">content</p>',
+ content_tag('p', "content", data: { title: '"'.html_safe })
+ end
+
def test_skip_invalid_escaped_attributes
["&1;", "&#1dfa3;", "& #123;"].each do |escaped|
assert_equal %(<a href="#{escaped.gsub(/&/, '&amp;')}" />), tag("a", href: escaped)
@@ -287,39 +305,39 @@ class TagHelperTest < ActionView::TestCase
def test_tag_builder_disable_escaping
assert_equal '<a href="&amp;"></a>', tag.a(href: "&amp;", escape_attributes: false)
- assert_equal '<a href="&amp;">cnt</a>', tag.a(href: "&amp;" , escape_attributes: false) { "cnt"}
+ assert_equal '<a href="&amp;">cnt</a>', tag.a(href: "&amp;" , escape_attributes: false) { "cnt" }
assert_equal '<br data-hidden="&amp;">', tag.br("data-hidden": "&amp;" , escape_attributes: false)
assert_equal '<a href="&amp;">content</a>', tag.a("content", href: "&amp;", escape_attributes: false)
- assert_equal '<a href="&amp;">content</a>', tag.a(href: "&amp;", escape_attributes: false) { "content"}
+ assert_equal '<a href="&amp;">content</a>', tag.a(href: "&amp;", escape_attributes: false) { "content" }
end
def test_data_attributes
["data", :data].each { |data|
assert_dom_equal '<a data-a-float="3.14" data-a-big-decimal="-123.456" data-a-number="1" data-array="[1,2,3]" data-hash="{&quot;key&quot;:&quot;value&quot;}" data-string-with-quotes="double&quot;quote&quot;party&quot;" data-string="hello" data-symbol="foo" />',
- tag("a", data => { a_float: 3.14, a_big_decimal: BigDecimal.new("-123.456"), a_number: 1, string: "hello", symbol: :foo, array: [1, 2, 3], hash: { key: "value"}, string_with_quotes: 'double"quote"party"' })
+ tag("a", data => { a_float: 3.14, a_big_decimal: BigDecimal.new("-123.456"), a_number: 1, string: "hello", symbol: :foo, array: [1, 2, 3], hash: { key: "value" }, string_with_quotes: 'double"quote"party"' })
assert_dom_equal '<a data-a-float="3.14" data-a-big-decimal="-123.456" data-a-number="1" data-array="[1,2,3]" data-hash="{&quot;key&quot;:&quot;value&quot;}" data-string-with-quotes="double&quot;quote&quot;party&quot;" data-string="hello" data-symbol="foo" />',
- tag.a(data: { a_float: 3.14, a_big_decimal: BigDecimal.new("-123.456"), a_number: 1, string: "hello", symbol: :foo, array: [1, 2, 3], hash: { key: "value"}, string_with_quotes: 'double"quote"party"' })
+ tag.a(data: { a_float: 3.14, a_big_decimal: BigDecimal.new("-123.456"), a_number: 1, string: "hello", symbol: :foo, array: [1, 2, 3], hash: { key: "value" }, string_with_quotes: 'double"quote"party"' })
}
end
def test_aria_attributes
["aria", :aria].each { |aria|
assert_dom_equal '<a aria-a-float="3.14" aria-a-big-decimal="-123.456" aria-a-number="1" aria-array="[1,2,3]" aria-hash="{&quot;key&quot;:&quot;value&quot;}" aria-string-with-quotes="double&quot;quote&quot;party&quot;" aria-string="hello" aria-symbol="foo" />',
- tag("a", aria => { a_float: 3.14, a_big_decimal: BigDecimal.new("-123.456"), a_number: 1, string: "hello", symbol: :foo, array: [1, 2, 3], hash: { key: "value"}, string_with_quotes: 'double"quote"party"' })
+ tag("a", aria => { a_float: 3.14, a_big_decimal: BigDecimal.new("-123.456"), a_number: 1, string: "hello", symbol: :foo, array: [1, 2, 3], hash: { key: "value" }, string_with_quotes: 'double"quote"party"' })
assert_dom_equal '<a aria-a-float="3.14" aria-a-big-decimal="-123.456" aria-a-number="1" aria-array="[1,2,3]" aria-hash="{&quot;key&quot;:&quot;value&quot;}" aria-string-with-quotes="double&quot;quote&quot;party&quot;" aria-string="hello" aria-symbol="foo" />',
- tag.a(aria: { a_float: 3.14, a_big_decimal: BigDecimal.new("-123.456"), a_number: 1, string: "hello", symbol: :foo, array: [1, 2, 3], hash: { key: "value"}, string_with_quotes: 'double"quote"party"' })
+ tag.a(aria: { a_float: 3.14, a_big_decimal: BigDecimal.new("-123.456"), a_number: 1, string: "hello", symbol: :foo, array: [1, 2, 3], hash: { key: "value" }, string_with_quotes: 'double"quote"party"' })
}
end
def test_link_to_data_nil_equal
div_type1 = content_tag(:div, "test", "data-tooltip" => nil)
- div_type2 = content_tag(:div, "test", data: {tooltip: nil})
+ div_type2 = content_tag(:div, "test", data: { tooltip: nil })
assert_dom_equal div_type1, div_type2
end
def test_tag_builder_link_to_data_nil_equal
div_type1 = tag.div "test", 'data-tooltip': nil
- div_type2 = tag.div "test", data: {tooltip: nil}
+ div_type2 = tag.div "test", data: { tooltip: nil }
assert_dom_equal div_type1, div_type2
end
diff --git a/actionview/test/template/template_test.rb b/actionview/test/template/template_test.rb
index 533c1c3219..2988f152be 100644
--- a/actionview/test/template/template_test.rb
+++ b/actionview/test/template/template_test.rb
@@ -35,7 +35,7 @@ class TestERBTemplate < ActiveSupport::TestCase
"<%= @virtual_path %>",
"partial",
ERBHandler,
- :virtual_path => "partial"
+ virtual_path: "partial"
)
end
@@ -53,7 +53,7 @@ class TestERBTemplate < ActiveSupport::TestCase
end
def new_template(body = "<%= hello %>", details = { format: :html })
- ActionView::Template.new(body, "hello template", details.fetch(:handler) { ERBHandler }, {:virtual_path => "hello"}.merge!(details))
+ ActionView::Template.new(body, "hello template", details.fetch(:handler) { ERBHandler }, { virtual_path: "hello" }.merge!(details))
end
def render(locals = {})
@@ -91,7 +91,7 @@ class TestERBTemplate < ActiveSupport::TestCase
end
def test_template_does_not_lose_its_source_after_rendering_if_it_does_not_have_a_virtual_path
- @template = new_template("Hello", :virtual_path => nil)
+ @template = new_template("Hello", virtual_path: nil)
render
assert_equal "Hello", @template.source
end
@@ -99,7 +99,7 @@ class TestERBTemplate < ActiveSupport::TestCase
def test_locals
@template = new_template("<%= my_local %>")
@template.locals = [:my_local]
- assert_equal "I am a local", render(:my_local => "I am a local")
+ assert_equal "I am a local", render(my_local: "I am a local")
end
def test_restores_buffer
@@ -116,23 +116,23 @@ class TestERBTemplate < ActiveSupport::TestCase
end
def test_refresh_with_templates
- @template = new_template("Hello", :virtual_path => "test/foo/bar")
+ @template = new_template("Hello", virtual_path: "test/foo/bar")
@template.locals = [:key]
- assert_called_with(@context.lookup_context, :find_template,["bar", %w(test/foo), false, [:key]], returns: "template") do
+ assert_called_with(@context.lookup_context, :find_template, ["bar", %w(test/foo), false, [:key]], returns: "template") do
assert_equal "template", @template.refresh(@context)
end
end
def test_refresh_with_partials
- @template = new_template("Hello", :virtual_path => "test/_foo")
+ @template = new_template("Hello", virtual_path: "test/_foo")
@template.locals = [:key]
- assert_called_with(@context.lookup_context, :find_template,[ "foo", %w(test), true, [:key]], returns: "partial") do
+ assert_called_with(@context.lookup_context, :find_template, ["foo", %w(test), true, [:key]], returns: "partial") do
assert_equal "partial", @template.refresh(@context)
end
end
def test_refresh_raises_an_error_without_virtual_path
- @template = new_template("Hello", :virtual_path => nil)
+ @template = new_template("Hello", virtual_path: nil)
assert_raise RuntimeError do
@template.refresh(@context)
end
@@ -171,14 +171,14 @@ class TestERBTemplate < ActiveSupport::TestCase
# inside Rails.
def test_lying_with_magic_comment
assert_raises(ActionView::Template::Error) do
- @template = new_template("# encoding: UTF-8\nhello \xFCmlat", :virtual_path => nil)
+ @template = new_template("# encoding: UTF-8\nhello \xFCmlat", virtual_path: nil)
render
end
end
def test_encoding_can_be_specified_with_magic_comment_in_erb
with_external_encoding Encoding::UTF_8 do
- @template = new_template("<%# encoding: ISO-8859-1 %>hello \xFCmlat", :virtual_path => nil)
+ @template = new_template("<%# encoding: ISO-8859-1 %>hello \xFCmlat", virtual_path: nil)
assert_equal Encoding::UTF_8, render.encoding
assert_equal "hello \u{fc}mlat", render
end
@@ -186,7 +186,7 @@ class TestERBTemplate < ActiveSupport::TestCase
def test_error_when_template_isnt_valid_utf8
e = assert_raises ActionView::Template::Error do
- @template = new_template("hello \xFCmlat", :virtual_path => nil)
+ @template = new_template("hello \xFCmlat", virtual_path: nil)
render
end
assert_match(/\xFC/, e.message)
diff --git a/actionview/test/template/test_case_test.rb b/actionview/test/template/test_case_test.rb
index 40a5bfca53..597b2aa8dd 100644
--- a/actionview/test/template/test_case_test.rb
+++ b/actionview/test/template/test_case_test.rb
@@ -59,7 +59,7 @@ module ActionView
test "can render a layout with block" do
assert_equal "Before (ChrisCruft)\n!\nAfter",
- render(layout: "test/layout_for_partial", locals: {name: "ChrisCruft"}) {"!"}
+ render(layout: "test/layout_for_partial", locals: { name: "ChrisCruft" }) { "!" }
end
helper AnotherTestHelper
@@ -85,7 +85,7 @@ module ActionView
end
test "uses controller lookup context" do
- assert_equal self.lookup_context, @controller.lookup_context
+ assert_equal lookup_context, @controller.lookup_context
end
end
@@ -155,7 +155,7 @@ module ActionView
test "view_assigns returns a Hash of user defined ivars" do
@a = "b"
@c = "d"
- assert_equal({a: "b", c: "d"}, view_assigns)
+ assert_equal({ a: "b", c: "d" }, view_assigns)
end
test "view_assigns excludes internal ivars" do
diff --git a/actionview/test/template/text_helper_test.rb b/actionview/test/template/text_helper_test.rb
index 9f57e6a6ae..d77e4c6913 100644
--- a/actionview/test/template/text_helper_test.rb
+++ b/actionview/test/template/text_helper_test.rb
@@ -71,7 +71,7 @@ class TextHelperTest < ActionView::TestCase
end
def test_simple_format_does_not_modify_the_html_options_hash
- options = { class: "foobar"}
+ options = { class: "foobar" }
passed_options = options.dup
simple_format("some text", passed_options)
assert_equal options, passed_options
diff --git a/actionview/test/template/url_helper_test.rb b/actionview/test/template/url_helper_test.rb
index bbbeb39f3f..2ef2be65d2 100644
--- a/actionview/test/template/url_helper_test.rb
+++ b/actionview/test/template/url_helper_test.rb
@@ -94,7 +94,7 @@ class UrlHelperTest < ActiveSupport::TestCase
def test_to_form_params_with_namespace
assert_equal(
[{ name: "country[name]", value: "Denmark" }],
- to_form_params({name: "Denmark"}, "country")
+ to_form_params({ name: "Denmark" }, "country")
)
end
@@ -260,7 +260,7 @@ class UrlHelperTest < ActiveSupport::TestCase
end
def test_link_tag_with_back
- env = {"HTTP_REFERER" => "http://www.example.com/referer"}
+ env = { "HTTP_REFERER" => "http://www.example.com/referer" }
@controller = Struct.new(:request).new(Struct.new(:env).new(env))
expected = %{<a href="#{env["HTTP_REFERER"]}">go back</a>}
assert_dom_equal expected, link_to("go back", :back)
@@ -626,7 +626,7 @@ class UrlHelperTest < ActiveSupport::TestCase
end
def protect_against_forgery?
- self.request_forgery
+ request_forgery
end
def form_authenticity_token(*args)
diff --git a/activejob/CHANGELOG.md b/activejob/CHANGELOG.md
index 39503caeea..585ade7229 100644
--- a/activejob/CHANGELOG.md
+++ b/activejob/CHANGELOG.md
@@ -1,6 +1,10 @@
## Rails 5.1.0.alpha ##
-* Added declarative exception handling via ActiveJob::Base.retry_on and ActiveJob::Base.discard_on.
+* Yield the job instance so you have access to things like `job.arguments` on the custom logic after retries fail.
+
+ *DHH*
+
+* Added declarative exception handling via `ActiveJob::Base.retry_on` and `ActiveJob::Base.discard_on`.
Examples:
diff --git a/activejob/lib/active_job/enqueuing.rb b/activejob/lib/active_job/enqueuing.rb
index e69f76021b..18051a7d65 100644
--- a/activejob/lib/active_job/enqueuing.rb
+++ b/activejob/lib/active_job/enqueuing.rb
@@ -45,8 +45,8 @@ module ActiveJob
self.queue_name = self.class.queue_name_from_part(options[:queue]) if options[:queue]
self.priority = options[:priority].to_i if options[:priority]
run_callbacks :enqueue do
- if self.scheduled_at
- self.class.queue_adapter.enqueue_at self, self.scheduled_at
+ if scheduled_at
+ self.class.queue_adapter.enqueue_at self, scheduled_at
else
self.class.queue_adapter.enqueue self
end
diff --git a/activejob/lib/active_job/exceptions.rb b/activejob/lib/active_job/exceptions.rb
index a8ff55fbe4..f8d76587ad 100644
--- a/activejob/lib/active_job/exceptions.rb
+++ b/activejob/lib/active_job/exceptions.rb
@@ -12,7 +12,7 @@ module ActiveJob
# holding queue for inspection.
#
# You can also pass a block that'll be invoked if the retry attempts fail for custom logic rather than letting
- # the exception bubble up.
+ # the exception bubble up. This block is yielded with the job instance as the first and the error instance as the second parameter.
#
# ==== Options
# * <tt>:wait</tt> - Re-enqueues the job with a delay specified either in seconds (default: 3 seconds),
@@ -28,7 +28,7 @@ module ActiveJob
# class RemoteServiceJob < ActiveJob::Base
# retry_on CustomAppException # defaults to 3s wait, 5 attempts
# retry_on AnotherCustomAppException, wait: ->(executions) { executions * 2 }
- # retry_on(YetAnotherCustomAppException) do |exception|
+ # retry_on(YetAnotherCustomAppException) do |job, exception|
# ExceptionNotifier.caught(exception)
# end
# retry_on ActiveRecord::StatementInvalid, wait: 5.seconds, attempts: 3
@@ -47,7 +47,7 @@ module ActiveJob
retry_job wait: determine_delay(wait), queue: queue, priority: priority
else
if block_given?
- yield exception
+ yield self, exception
else
logger.error "Stopped retrying #{self.class} due to a #{exception}, which reoccurred on #{executions} attempts. The original exception was #{error.cause.inspect}."
raise error
diff --git a/activejob/lib/active_job/logging.rb b/activejob/lib/active_job/logging.rb
index 9900e10181..aa97ab2e22 100644
--- a/activejob/lib/active_job/logging.rb
+++ b/activejob/lib/active_job/logging.rb
@@ -18,7 +18,7 @@ module ActiveJob
around_perform do |job, block, _|
tag_logger(job.class.name, job.job_id) do
- payload = {adapter: job.class.queue_adapter, job: job}
+ payload = { adapter: job.class.queue_adapter, job: job }
ActiveSupport::Notifications.instrument("perform_start.active_job", payload.dup)
ActiveSupport::Notifications.instrument("perform.active_job", payload) do
block.call
@@ -41,7 +41,7 @@ module ActiveJob
def tag_logger(*tags)
if logger.respond_to?(:tagged)
tags.unshift "ActiveJob" unless logger_tagged_by_active_job?
- logger.tagged(*tags){ yield }
+ logger.tagged(*tags) { yield }
else
yield
end
diff --git a/activejob/test/cases/exceptions_test.rb b/activejob/test/cases/exceptions_test.rb
index 30e43c99cb..9ee1dbfa0a 100644
--- a/activejob/test/cases/exceptions_test.rb
+++ b/activejob/test/cases/exceptions_test.rb
@@ -58,8 +58,8 @@ class ExceptionsTest < ActiveJob::TestCase
test "custom handling of job that exceeds retry attempts" do
perform_enqueued_jobs do
- RetryJob.perform_later "CustomCatchError", 6
- assert_equal "Dealt with a job that failed to retry in a custom way", JobBuffer.last_value
+ RetryJob.perform_later 'CustomCatchError', 6
+ assert_equal "Dealt with a job that failed to retry in a custom way after 6 attempts", JobBuffer.last_value
end
end
diff --git a/activejob/test/cases/queuing_test.rb b/activejob/test/cases/queuing_test.rb
index 9690e0cc79..a3ecb15c31 100644
--- a/activejob/test/cases/queuing_test.rb
+++ b/activejob/test/cases/queuing_test.rb
@@ -2,7 +2,6 @@ require "helper"
require "jobs/hello_job"
require "active_support/core_ext/numeric/time"
-
class QueuingTest < ActiveSupport::TestCase
setup do
JobBuffer.clear
@@ -32,7 +31,6 @@ class QueuingTest < ActiveSupport::TestCase
assert_equal [ "Jamie" ], job.arguments
end
-
test "job returned by perform_at has the timestamp available" do
begin
job = HelloJob.set(wait_until: Time.utc(2014, 1, 1)).perform_later
diff --git a/activejob/test/cases/test_case_test.rb b/activejob/test/cases/test_case_test.rb
index 23fffd4235..3db2d9dec7 100644
--- a/activejob/test/cases/test_case_test.rb
+++ b/activejob/test/cases/test_case_test.rb
@@ -18,6 +18,6 @@ class ActiveJobTestCaseTest < ActiveJob::TestCase
end
def test_set_test_adapter
- assert_kind_of ActiveJob::QueueAdapters::TestAdapter, self.queue_adapter
+ assert_kind_of ActiveJob::QueueAdapters::TestAdapter, queue_adapter
end
end
diff --git a/activejob/test/jobs/callback_job.rb b/activejob/test/jobs/callback_job.rb
index 7f9fc1c74a..ca2a8e031a 100644
--- a/activejob/test/jobs/callback_job.rb
+++ b/activejob/test/jobs/callback_job.rb
@@ -17,7 +17,6 @@ class CallbackJob < ActiveJob::Base
job.history << "CallbackJob ran around_enqueue_stop"
end
-
def perform(person = "david")
# NOTHING!
end
diff --git a/activejob/test/jobs/retry_job.rb b/activejob/test/jobs/retry_job.rb
index be20156984..c02febc50c 100644
--- a/activejob/test/jobs/retry_job.rb
+++ b/activejob/test/jobs/retry_job.rb
@@ -15,7 +15,7 @@ class RetryJob < ActiveJob::Base
retry_on ShortWaitTenAttemptsError, wait: 1.second, attempts: 10
retry_on ExponentialWaitTenAttemptsError, wait: :exponentially_longer, attempts: 10
retry_on CustomWaitTenAttemptsError, wait: ->(executions) { executions * 2 }, attempts: 10
- retry_on(CustomCatchError) { |exception| JobBuffer.add("Dealt with a job that failed to retry in a custom way") }
+ retry_on(CustomCatchError) { |job, exception| JobBuffer.add("Dealt with a job that failed to retry in a custom way after #{job.arguments.second} attempts") }
discard_on DiscardableError
def perform(raising, attempts)
diff --git a/activejob/test/support/delayed_job/delayed/backend/test.rb b/activejob/test/support/delayed_job/delayed/backend/test.rb
index e4aca625cd..a900b18e2a 100644
--- a/activejob/test/support/delayed_job/delayed/backend/test.rb
+++ b/activejob/test/support/delayed_job/delayed/backend/test.rb
@@ -26,7 +26,7 @@ module Delayed
self.attempts = 0
self.priority = 0
self.id = (self.class.id += 1)
- hash.each{|k,v| send(:"#{k}=", v)}
+ hash.each { |k,v| send(:"#{k}=", v) }
end
@jobs = []
@@ -49,7 +49,7 @@ module Delayed
def self.create!(*args); create(*args); end
def self.clear_locks!(worker_name)
- all.select{|j| j.locked_by == worker_name}.each {|j| j.locked_by = nil; j.locked_at = nil}
+ all.select { |j| j.locked_by == worker_name }.each { |j| j.locked_by = nil; j.locked_at = nil }
end
# Find a few candidate jobs to run (in case some immediately get locked by others).
@@ -60,10 +60,10 @@ module Delayed
!j.failed?
end
- jobs = jobs.select{|j| Worker.queues.include?(j.queue)} if Worker.queues.any?
- jobs = jobs.select{|j| j.priority >= Worker.min_priority} if Worker.min_priority
- jobs = jobs.select{|j| j.priority <= Worker.max_priority} if Worker.max_priority
- jobs.sort_by{|j| [j.priority, j.run_at]}[0..limit-1]
+ jobs = jobs.select { |j| Worker.queues.include?(j.queue) } if Worker.queues.any?
+ jobs = jobs.select { |j| j.priority >= Worker.min_priority } if Worker.min_priority
+ jobs = jobs.select { |j| j.priority <= Worker.max_priority } if Worker.max_priority
+ jobs.sort_by { |j| [j.priority, j.run_at] }[0..limit-1]
end
# Lock this job for this worker.
@@ -84,7 +84,7 @@ module Delayed
end
def update_attributes(attrs = {})
- attrs.each{|k,v| send(:"#{k}=", v)}
+ attrs.each { |k,v| send(:"#{k}=", v) }
save
end
diff --git a/activejob/test/support/integration/adapters/sneakers.rb b/activejob/test/support/integration/adapters/sneakers.rb
index b3639572fb..08743c1f05 100644
--- a/activejob/test/support/integration/adapters/sneakers.rb
+++ b/activejob/test/support/integration/adapters/sneakers.rb
@@ -12,7 +12,6 @@ module Sneakers
end
end
-
module SneakersJobsManager
def setup
ActiveJob::Base.queue_adapter = :sneakers
diff --git a/activejob/test/support/que/inline.rb b/activejob/test/support/que/inline.rb
index ea9999b473..55eb0d01ef 100644
--- a/activejob/test/support/que/inline.rb
+++ b/activejob/test/support/que/inline.rb
@@ -9,6 +9,6 @@ Que::Job.class_eval do
options.delete(:priority)
args << options unless options.empty?
end
- self.run(*args)
+ run(*args)
end
end
diff --git a/activemodel/bin/test b/activemodel/bin/test
index 404cabba51..84a05bba08 100755
--- a/activemodel/bin/test
+++ b/activemodel/bin/test
@@ -1,4 +1,6 @@
#!/usr/bin/env ruby
-COMPONENT_ROOT = File.expand_path("../../", __FILE__)
+
+COMPONENT_ROOT = File.expand_path("..", __dir__)
require File.expand_path("../tools/test", COMPONENT_ROOT)
+
exit Minitest.run(ARGV)
diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb
index 0cdb0e8525..45ef14013a 100644
--- a/activemodel/lib/active_model/errors.rb
+++ b/activemodel/lib/active_model/errors.rb
@@ -276,11 +276,11 @@ module ActiveModel
# person.errors.to_hash(true) # => {:name=>["name cannot be nil"]}
def to_hash(full_messages = false)
if full_messages
- self.messages.each_with_object({}) do |(attribute, array), messages|
+ messages.each_with_object({}) do |(attribute, array), messages|
messages[attribute] = array.map { |message| full_message(attribute, message) }
end
else
- self.messages.dup
+ messages.dup
end
end
@@ -439,7 +439,8 @@ module ActiveModel
return message if attribute == :base
attr_name = attribute.to_s.tr(".", "_").humanize
attr_name = @base.class.human_attribute_name(attribute, default: attr_name)
- I18n.t(:"errors.format", default: "%{attribute} %{message}",
+ I18n.t(:"errors.format",
+ default: "%{attribute} %{message}",
attribute: attr_name,
message: message)
end
diff --git a/activemodel/lib/active_model/translation.rb b/activemodel/lib/active_model/translation.rb
index 75509b0588..b8cf43cc10 100644
--- a/activemodel/lib/active_model/translation.rb
+++ b/activemodel/lib/active_model/translation.rb
@@ -30,7 +30,7 @@ module ActiveModel
# ActiveModel::Errors#full_messages and
# ActiveModel::Translation#human_attribute_name.
def lookup_ancestors
- self.ancestors.select { |x| x.respond_to?(:model_name) }
+ ancestors.select { |x| x.respond_to?(:model_name) }
end
# Transforms attribute names into a more human format, such as "First name"
diff --git a/activemodel/lib/active_model/type/integer.rb b/activemodel/lib/active_model/type/integer.rb
index b76e9d96f6..41dd655a5c 100644
--- a/activemodel/lib/active_model/type/integer.rb
+++ b/activemodel/lib/active_model/type/integer.rb
@@ -59,7 +59,7 @@ module ActiveModel
end
def _limit
- self.limit || DEFAULT_LIMIT
+ limit || DEFAULT_LIMIT
end
end
end
diff --git a/activemodel/lib/active_model/validations/clusivity.rb b/activemodel/lib/active_model/validations/clusivity.rb
index a869dba672..18f1056e2b 100644
--- a/activemodel/lib/active_model/validations/clusivity.rb
+++ b/activemodel/lib/active_model/validations/clusivity.rb
@@ -17,11 +17,11 @@ module ActiveModel
def include?(record, value)
members = if delimiter.respond_to?(:call)
delimiter.call(record)
- elsif delimiter.respond_to?(:to_sym)
- record.send(delimiter)
- else
- delimiter
- end
+ elsif delimiter.respond_to?(:to_sym)
+ record.send(delimiter)
+ else
+ delimiter
+ end
members.send(inclusion_method(members), value)
end
diff --git a/activemodel/test/cases/attribute_methods_test.rb b/activemodel/test/cases/attribute_methods_test.rb
index f59180cceb..4767accb7c 100644
--- a/activemodel/test/cases/attribute_methods_test.rb
+++ b/activemodel/test/cases/attribute_methods_test.rb
@@ -48,7 +48,7 @@ class ModelWithAttributesWithSpaces
include ActiveModel::AttributeMethods
def attributes
- { 'foo bar': "value of foo bar"}
+ { 'foo bar': "value of foo bar" }
end
private
diff --git a/activemodel/test/cases/callbacks_test.rb b/activemodel/test/cases/callbacks_test.rb
index 2b1c8d0eb7..63b6c56f8c 100644
--- a/activemodel/test/cases/callbacks_test.rb
+++ b/activemodel/test/cases/callbacks_test.rb
@@ -109,8 +109,8 @@ class CallbacksTest < ActiveModel::TestCase
end
extend ActiveModel::Callbacks
define_model_callbacks :create
- def callback1; self.history << "callback1"; end
- def callback2; self.history << "callback2"; end
+ def callback1; history << "callback1"; end
+ def callback2; history << "callback2"; end
def create
run_callbacks(:create) {}
self
diff --git a/activemodel/test/cases/serialization_test.rb b/activemodel/test/cases/serialization_test.rb
index cead0bee22..5ee53285a3 100644
--- a/activemodel/test/cases/serialization_test.rb
+++ b/activemodel/test/cases/serialization_test.rb
@@ -51,32 +51,32 @@ class SerializationTest < ActiveModel::TestCase
end
def test_method_serializable_hash_should_work
- expected = {"name"=>"David", "gender"=>"male", "email"=>"david@example.com"}
+ expected = { "name"=>"David", "gender"=>"male", "email"=>"david@example.com" }
assert_equal expected, @user.serializable_hash
end
def test_method_serializable_hash_should_work_with_only_option
- expected = {"name"=>"David"}
+ expected = { "name"=>"David" }
assert_equal expected, @user.serializable_hash(only: [:name])
end
def test_method_serializable_hash_should_work_with_except_option
- expected = {"gender"=>"male", "email"=>"david@example.com"}
+ expected = { "gender"=>"male", "email"=>"david@example.com" }
assert_equal expected, @user.serializable_hash(except: [:name])
end
def test_method_serializable_hash_should_work_with_methods_option
- expected = {"name"=>"David", "gender"=>"male", "foo"=>"i_am_foo", "bar"=>"i_am_bar", "email"=>"david@example.com"}
+ expected = { "name"=>"David", "gender"=>"male", "foo"=>"i_am_foo", "bar"=>"i_am_bar", "email"=>"david@example.com" }
assert_equal expected, @user.serializable_hash(methods: [:foo, :bar])
end
def test_method_serializable_hash_should_work_with_only_and_methods
- expected = {"foo"=>"i_am_foo", "bar"=>"i_am_bar"}
+ expected = { "foo"=>"i_am_foo", "bar"=>"i_am_bar" }
assert_equal expected, @user.serializable_hash(only: [], methods: [:foo, :bar])
end
def test_method_serializable_hash_should_work_with_except_and_methods
- expected = {"gender"=>"male", "foo"=>"i_am_foo", "bar"=>"i_am_bar"}
+ expected = { "gender"=>"male", "foo"=>"i_am_foo", "bar"=>"i_am_bar" }
assert_equal expected, @user.serializable_hash(except: [:name, :email], methods: [:foo, :bar])
end
@@ -94,21 +94,21 @@ class SerializationTest < ActiveModel::TestCase
end
def test_include_option_with_singular_association
- expected = {"name"=>"David", "gender"=>"male", "email"=>"david@example.com",
- "address"=>{"street"=>"123 Lane", "city"=>"Springfield", "state"=>"CA", "zip"=>11111}}
+ expected = { "name"=>"David", "gender"=>"male", "email"=>"david@example.com",
+ "address"=>{ "street"=>"123 Lane", "city"=>"Springfield", "state"=>"CA", "zip"=>11111 } }
assert_equal expected, @user.serializable_hash(include: :address)
end
def test_include_option_with_plural_association
- expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David",
- "friends"=>[{"name"=>"Joe", "email"=>"joe@example.com", "gender"=>"male"},
- {"name"=>"Sue", "email"=>"sue@example.com", "gender"=>"female"}]}
+ expected = { "email"=>"david@example.com", "gender"=>"male", "name"=>"David",
+ "friends"=>[{ "name"=>"Joe", "email"=>"joe@example.com", "gender"=>"male" },
+ { "name"=>"Sue", "email"=>"sue@example.com", "gender"=>"female" }] }
assert_equal expected, @user.serializable_hash(include: :friends)
end
def test_include_option_with_empty_association
@user.friends = []
- expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David", "friends"=>[]}
+ expected = { "email"=>"david@example.com", "gender"=>"male", "name"=>"David", "friends"=>[] }
assert_equal expected, @user.serializable_hash(include: :friends)
end
@@ -124,52 +124,52 @@ class SerializationTest < ActiveModel::TestCase
def test_include_option_with_ary
@user.friends = FriendList.new(@user.friends)
- expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David",
- "friends"=>[{"name"=>"Joe", "email"=>"joe@example.com", "gender"=>"male"},
- {"name"=>"Sue", "email"=>"sue@example.com", "gender"=>"female"}]}
+ expected = { "email"=>"david@example.com", "gender"=>"male", "name"=>"David",
+ "friends"=>[{ "name"=>"Joe", "email"=>"joe@example.com", "gender"=>"male" },
+ { "name"=>"Sue", "email"=>"sue@example.com", "gender"=>"female" }] }
assert_equal expected, @user.serializable_hash(include: :friends)
end
def test_multiple_includes
- expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David",
- "address"=>{"street"=>"123 Lane", "city"=>"Springfield", "state"=>"CA", "zip"=>11111},
- "friends"=>[{"name"=>"Joe", "email"=>"joe@example.com", "gender"=>"male"},
- {"name"=>"Sue", "email"=>"sue@example.com", "gender"=>"female"}]}
+ expected = { "email"=>"david@example.com", "gender"=>"male", "name"=>"David",
+ "address"=>{ "street"=>"123 Lane", "city"=>"Springfield", "state"=>"CA", "zip"=>11111 },
+ "friends"=>[{ "name"=>"Joe", "email"=>"joe@example.com", "gender"=>"male" },
+ { "name"=>"Sue", "email"=>"sue@example.com", "gender"=>"female" }] }
assert_equal expected, @user.serializable_hash(include: [:address, :friends])
end
def test_include_with_options
- expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David",
- "address"=>{"street"=>"123 Lane"}}
+ expected = { "email"=>"david@example.com", "gender"=>"male", "name"=>"David",
+ "address"=>{ "street"=>"123 Lane" } }
assert_equal expected, @user.serializable_hash(include: { address: { only: "street" } })
end
def test_nested_include
@user.friends.first.friends = [@user]
- expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David",
- "friends"=>[{"name"=>"Joe", "email"=>"joe@example.com", "gender"=>"male",
- "friends"=> [{"email"=>"david@example.com", "gender"=>"male", "name"=>"David"}]},
- {"name"=>"Sue", "email"=>"sue@example.com", "gender"=>"female", "friends"=> []}]}
+ expected = { "email"=>"david@example.com", "gender"=>"male", "name"=>"David",
+ "friends"=>[{ "name"=>"Joe", "email"=>"joe@example.com", "gender"=>"male",
+ "friends"=> [{ "email"=>"david@example.com", "gender"=>"male", "name"=>"David" }] },
+ { "name"=>"Sue", "email"=>"sue@example.com", "gender"=>"female", "friends"=> [] }] }
assert_equal expected, @user.serializable_hash(include: { friends: { include: :friends } })
end
def test_only_include
- expected = {"name"=>"David", "friends" => [{"name" => "Joe"}, {"name" => "Sue"}]}
+ expected = { "name"=>"David", "friends" => [{ "name" => "Joe" }, { "name" => "Sue" }] }
assert_equal expected, @user.serializable_hash(only: :name, include: { friends: { only: :name } })
end
def test_except_include
- expected = {"name"=>"David", "email"=>"david@example.com",
- "friends"=> [{"name" => "Joe", "email" => "joe@example.com"},
- {"name" => "Sue", "email" => "sue@example.com"}]}
+ expected = { "name"=>"David", "email"=>"david@example.com",
+ "friends"=> [{ "name" => "Joe", "email" => "joe@example.com" },
+ { "name" => "Sue", "email" => "sue@example.com" }] }
assert_equal expected, @user.serializable_hash(except: :gender, include: { friends: { except: :gender } })
end
def test_multiple_includes_with_options
- expected = {"email"=>"david@example.com", "gender"=>"male", "name"=>"David",
- "address"=>{"street"=>"123 Lane"},
- "friends"=>[{"name"=>"Joe", "email"=>"joe@example.com", "gender"=>"male"},
- {"name"=>"Sue", "email"=>"sue@example.com", "gender"=>"female"}]}
- assert_equal expected, @user.serializable_hash(include: [{ address: {only: "street" } }, :friends])
+ expected = { "email"=>"david@example.com", "gender"=>"male", "name"=>"David",
+ "address"=>{ "street"=>"123 Lane" },
+ "friends"=>[{ "name"=>"Joe", "email"=>"joe@example.com", "gender"=>"male" },
+ { "name"=>"Sue", "email"=>"sue@example.com", "gender"=>"female" }] }
+ assert_equal expected, @user.serializable_hash(include: [{ address: { only: "street" } }, :friends])
end
end
diff --git a/activemodel/test/cases/translation_test.rb b/activemodel/test/cases/translation_test.rb
index 1717e0c7ce..9972f9daea 100644
--- a/activemodel/test/cases/translation_test.rb
+++ b/activemodel/test/cases/translation_test.rb
@@ -38,23 +38,23 @@ class ActiveModelI18nTests < ActiveModel::TestCase
end
def test_translated_model_attributes_with_symbols
- I18n.backend.store_translations "en", activemodel: { attributes: { person: { name: "person name attribute"} } }
+ I18n.backend.store_translations "en", activemodel: { attributes: { person: { name: "person name attribute" } } }
assert_equal "person name attribute", Person.human_attribute_name(:name)
end
def test_translated_model_attributes_with_ancestor
- I18n.backend.store_translations "en", activemodel: { attributes: { child: { name: "child name attribute"} } }
+ I18n.backend.store_translations "en", activemodel: { attributes: { child: { name: "child name attribute" } } }
assert_equal "child name attribute", Child.human_attribute_name("name")
end
def test_translated_model_attributes_with_ancestors_fallback
- I18n.backend.store_translations "en", activemodel: { attributes: { person: { name: "person name attribute"} } }
+ I18n.backend.store_translations "en", activemodel: { attributes: { person: { name: "person name attribute" } } }
assert_equal "person name attribute", Child.human_attribute_name("name")
end
def test_translated_model_attributes_with_attribute_matching_namespaced_model_name
I18n.backend.store_translations "en", activemodel: { attributes: {
- person: { gender: "person gender"},
+ person: { gender: "person gender" },
"person/gender": { attribute: "person gender attribute" }
} }
diff --git a/activemodel/test/cases/validations/callbacks_test.rb b/activemodel/test/cases/validations/callbacks_test.rb
index 99913be752..83e8ac9522 100644
--- a/activemodel/test/cases/validations/callbacks_test.rb
+++ b/activemodel/test/cases/validations/callbacks_test.rb
@@ -15,37 +15,37 @@ class DogWithMethodCallbacks < Dog
before_validation :set_before_validation_marker
after_validation :set_after_validation_marker
- def set_before_validation_marker; self.history << "before_validation_marker"; end
- def set_after_validation_marker; self.history << "after_validation_marker" ; end
+ def set_before_validation_marker; history << "before_validation_marker"; end
+ def set_after_validation_marker; history << "after_validation_marker" ; end
end
class DogValidatorsAreProc < Dog
- before_validation { self.history << "before_validation_marker" }
- after_validation { self.history << "after_validation_marker" }
+ before_validation { history << "before_validation_marker" }
+ after_validation { history << "after_validation_marker" }
end
class DogWithTwoValidators < Dog
- before_validation { self.history << "before_validation_marker1" }
- before_validation { self.history << "before_validation_marker2" }
+ before_validation { history << "before_validation_marker1" }
+ before_validation { history << "before_validation_marker2" }
end
class DogDeprecatedBeforeValidatorReturningFalse < Dog
before_validation { false }
- before_validation { self.history << "before_validation_marker2" }
+ before_validation { history << "before_validation_marker2" }
end
class DogBeforeValidatorThrowingAbort < Dog
before_validation { throw :abort }
- before_validation { self.history << "before_validation_marker2" }
+ before_validation { history << "before_validation_marker2" }
end
class DogAfterValidatorReturningFalse < Dog
after_validation { false }
- after_validation { self.history << "after_validation_marker" }
+ after_validation { history << "after_validation_marker" }
end
class DogWithMissingName < Dog
- before_validation { self.history << "before_validation_marker" }
+ before_validation { history << "before_validation_marker" }
validates_presence_of :name
end
@@ -53,8 +53,8 @@ class DogValidatorWithOnCondition < Dog
before_validation :set_before_validation_marker, on: :create
after_validation :set_after_validation_marker, on: :create
- def set_before_validation_marker; self.history << "before_validation_marker"; end
- def set_after_validation_marker; self.history << "after_validation_marker" ; end
+ def set_before_validation_marker; history << "before_validation_marker"; end
+ def set_after_validation_marker; history << "after_validation_marker" ; end
end
class DogValidatorWithIfCondition < Dog
@@ -64,14 +64,13 @@ class DogValidatorWithIfCondition < Dog
after_validation :set_after_validation_marker1, if: -> { true }
after_validation :set_after_validation_marker2, if: -> { false }
- def set_before_validation_marker1; self.history << "before_validation_marker1"; end
- def set_before_validation_marker2; self.history << "before_validation_marker2" ; end
+ def set_before_validation_marker1; history << "before_validation_marker1"; end
+ def set_before_validation_marker2; history << "before_validation_marker2" ; end
- def set_after_validation_marker1; self.history << "after_validation_marker1"; end
- def set_after_validation_marker2; self.history << "after_validation_marker2" ; end
+ def set_after_validation_marker1; history << "after_validation_marker1"; end
+ def set_after_validation_marker2; history << "after_validation_marker2" ; end
end
-
class CallbacksWithMethodNamesShouldBeCalled < ActiveModel::TestCase
def test_if_condition_is_respected_for_before_validation
d = DogValidatorWithIfCondition.new
diff --git a/activemodel/test/cases/validations/conditional_validation_test.rb b/activemodel/test/cases/validations/conditional_validation_test.rb
index 8c2f656838..5e81083b63 100644
--- a/activemodel/test/cases/validations/conditional_validation_test.rb
+++ b/activemodel/test/cases/validations/conditional_validation_test.rb
@@ -97,7 +97,7 @@ class ConditionalValidationTest < ActiveModel::TestCase
def test_if_validation_using_block_false
# When the block returns false
Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}",
- if: Proc.new { |r| r.title != "uhohuhoh"})
+ if: Proc.new { |r| r.title != "uhohuhoh" })
t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
assert t.valid?
assert_empty t.errors[:title]
@@ -106,7 +106,7 @@ class ConditionalValidationTest < ActiveModel::TestCase
def test_unless_validation_using_block_false
# When the block returns false
Topic.validates_length_of(:title, maximum: 5, too_long: "hoo %{count}",
- unless: Proc.new { |r| r.title != "uhohuhoh"} )
+ unless: Proc.new { |r| r.title != "uhohuhoh" } )
t = Topic.new("title" => "uhohuhoh", "content" => "whatever")
assert t.invalid?
assert t.errors[:title].any?
diff --git a/activemodel/test/cases/validations/confirmation_validation_test.rb b/activemodel/test/cases/validations/confirmation_validation_test.rb
index a980628765..b88e1c4ca4 100644
--- a/activemodel/test/cases/validations/confirmation_validation_test.rb
+++ b/activemodel/test/cases/validations/confirmation_validation_test.rb
@@ -55,8 +55,9 @@ class ConfirmationValidationTest < ActiveModel::TestCase
@old_load_path, @old_backend = I18n.load_path.dup, I18n.backend
I18n.load_path.clear
I18n.backend = I18n::Backend::Simple.new
- I18n.backend.store_translations("en", errors: { messages: { confirmation: "doesn't match %{attribute}" } },
- activemodel: { attributes: { topic: { title: "Test Title"} } })
+ I18n.backend.store_translations("en",
+ errors: { messages: { confirmation: "doesn't match %{attribute}" } },
+ activemodel: { attributes: { topic: { title: "Test Title" } } })
Topic.validates_confirmation_of(:title)
diff --git a/activemodel/test/cases/validations/i18n_validation_test.rb b/activemodel/test/cases/validations/i18n_validation_test.rb
index 9c0071fad7..85212a80fc 100644
--- a/activemodel/test/cases/validations/i18n_validation_test.rb
+++ b/activemodel/test/cases/validations/i18n_validation_test.rb
@@ -49,8 +49,8 @@ class I18nValidationTest < ActiveModel::TestCase
# [ case, validation_options, generate_message_options]
[ "given no options", {}, {}],
[ "given custom message", { message: "custom" }, { message: "custom" }],
- [ "given if condition", { if: lambda { true }}, {}],
- [ "given unless condition", { unless: lambda { false }}, {}],
+ [ "given if condition", { if: lambda { true } }, {}],
+ [ "given unless condition", { unless: lambda { false } }, {}],
[ "given option that is not reserved", { format: "jpg" }, { format: "jpg" }]
]
@@ -225,7 +225,7 @@ class I18nValidationTest < ActiveModel::TestCase
test "#{validation} finds custom model key translation when #{error_type}" do
I18n.backend.store_translations "en", activemodel: { errors: { models: { person: { attributes: { attribute => { error_type => "custom message" } } } } } }
- I18n.backend.store_translations "en", errors: { messages: { error_type => "global message"}}
+ I18n.backend.store_translations "en", errors: { messages: { error_type => "global message" } }
yield(@person, {})
@person.valid?
@@ -234,7 +234,7 @@ class I18nValidationTest < ActiveModel::TestCase
test "#{validation} finds custom model key translation with interpolation when #{error_type}" do
I18n.backend.store_translations "en", activemodel: { errors: { models: { person: { attributes: { attribute => { error_type => "custom message with %{extra}" } } } } } }
- I18n.backend.store_translations "en", errors: { messages: {error_type => "global message"} }
+ I18n.backend.store_translations "en", errors: { messages: { error_type => "global message" } }
yield(@person, { extra: "extra information" })
@person.valid?
@@ -242,7 +242,7 @@ class I18nValidationTest < ActiveModel::TestCase
end
test "#{validation} finds global default key translation when #{error_type}" do
- I18n.backend.store_translations "en", errors: { messages: {error_type => "global message"} }
+ I18n.backend.store_translations "en", errors: { messages: { error_type => "global message" } }
yield(@person, {})
@person.valid?
diff --git a/activemodel/test/cases/validations/inclusion_validation_test.rb b/activemodel/test/cases/validations/inclusion_validation_test.rb
index 732a8d362a..5aa43ea4a9 100644
--- a/activemodel/test/cases/validations/inclusion_validation_test.rb
+++ b/activemodel/test/cases/validations/inclusion_validation_test.rb
@@ -121,7 +121,7 @@ class InclusionValidationTest < ActiveModel::TestCase
end
def test_validates_inclusion_of_with_lambda
- Topic.validates_inclusion_of :title, in: lambda{ |topic| topic.author_name == "sikachu" ? %w( monkey elephant ) : %w( abe wasabi ) }
+ Topic.validates_inclusion_of :title, in: lambda { |topic| topic.author_name == "sikachu" ? %w( monkey elephant ) : %w( abe wasabi ) }
t = Topic.new
t.title = "wasabi"
diff --git a/activemodel/test/cases/validations/length_validation_test.rb b/activemodel/test/cases/validations/length_validation_test.rb
index dbbfb8351b..ade185c179 100644
--- a/activemodel/test/cases/validations/length_validation_test.rb
+++ b/activemodel/test/cases/validations/length_validation_test.rb
@@ -324,7 +324,7 @@ class LengthValidationTest < ActiveModel::TestCase
:content,
minimum: 5,
too_short: "Your essay must be at least %{count} words.",
- tokenizer: lambda {|str| str.scan(/\w+/) },
+ tokenizer: lambda { |str| str.scan(/\w+/) },
)
end
t = Topic.new(content: "this content should be long enough")
@@ -336,7 +336,6 @@ class LengthValidationTest < ActiveModel::TestCase
assert_equal ["Your essay must be at least 5 words."], t.errors[:content]
end
-
def test_validates_length_of_with_symbol
assert_deprecated do
Topic.validates_length_of(
diff --git a/activemodel/test/cases/validations/numericality_validation_test.rb b/activemodel/test/cases/validations/numericality_validation_test.rb
index 71ef449503..84ed430d2a 100644
--- a/activemodel/test/cases/validations/numericality_validation_test.rb
+++ b/activemodel/test/cases/validations/numericality_validation_test.rb
@@ -254,11 +254,11 @@ class NumericalityValidationTest < ActiveModel::TestCase
end
def test_validates_numericality_with_invalid_args
- assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, greater_than_or_equal_to: "foo" }
- assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, less_than_or_equal_to: "foo" }
- assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, greater_than: "foo" }
- assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, less_than: "foo" }
- assert_raise(ArgumentError){ Topic.validates_numericality_of :approved, equal_to: "foo" }
+ assert_raise(ArgumentError) { Topic.validates_numericality_of :approved, greater_than_or_equal_to: "foo" }
+ assert_raise(ArgumentError) { Topic.validates_numericality_of :approved, less_than_or_equal_to: "foo" }
+ assert_raise(ArgumentError) { Topic.validates_numericality_of :approved, greater_than: "foo" }
+ assert_raise(ArgumentError) { Topic.validates_numericality_of :approved, less_than: "foo" }
+ assert_raise(ArgumentError) { Topic.validates_numericality_of :approved, equal_to: "foo" }
end
private
diff --git a/activemodel/test/cases/validations/with_validation_test.rb b/activemodel/test/cases/validations/with_validation_test.rb
index 6b2c998ba4..7af51c5cc5 100644
--- a/activemodel/test/cases/validations/with_validation_test.rb
+++ b/activemodel/test/cases/validations/with_validation_test.rb
@@ -97,7 +97,7 @@ class ValidatesWithTest < ActiveModel::TestCase
test "passes all configuration options to the validator class" do
topic = Topic.new
validator = Minitest::Mock.new
- validator.expect(:new, validator, [{foo: :bar, if: "1 == 1", class: Topic}])
+ validator.expect(:new, validator, [{ foo: :bar, if: "1 == 1", class: Topic }])
validator.expect(:validate, nil, [topic])
validator.expect(:is_a?, false, [Symbol])
validator.expect(:is_a?, false, [String])
diff --git a/activemodel/test/cases/validations_test.rb b/activemodel/test/cases/validations_test.rb
index 51607ba955..7aaafc428e 100644
--- a/activemodel/test/cases/validations_test.rb
+++ b/activemodel/test/cases/validations_test.rb
@@ -51,7 +51,7 @@ class ValidationsTest < ActiveModel::TestCase
r = Reply.new
r.valid?
- errors = r.errors.collect {|attr, messages| [attr.to_s, messages]}
+ errors = r.errors.collect { |attr, messages| [attr.to_s, messages] }
assert errors.include?(["title", "is Empty"])
assert errors.include?(["content", "is Empty"])
@@ -198,9 +198,9 @@ class ValidationsTest < ActiveModel::TestCase
end
assert_nothing_raised do
- klass.validate :validator_a, if: ->{ true }
+ klass.validate :validator_a, if: -> { true }
klass.validate :validator_b, prepend: true
- klass.validate :validator_c, unless: ->{ true }
+ klass.validate :validator_c, unless: -> { true }
end
t = klass.new
@@ -233,7 +233,7 @@ class ValidationsTest < ActiveModel::TestCase
assert t.invalid?
assert_equal "can't be blank", t.errors["title"].first
Topic.validates_presence_of :title, :author_name
- Topic.validate {errors.add("author_email_address", "will never be valid")}
+ Topic.validate { errors.add("author_email_address", "will never be valid") }
Topic.validates_length_of :title, :content, minimum: 2
t = Topic.new title: ""
@@ -251,7 +251,7 @@ class ValidationsTest < ActiveModel::TestCase
end
def test_validation_with_if_and_on
- Topic.validates_presence_of :title, if: Proc.new{|x| x.author_name = "bad"; true }, on: :update
+ Topic.validates_presence_of :title, if: Proc.new { |x| x.author_name = "bad"; true }, on: :update
t = Topic.new(title: "")
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md
index dfd9a07997..6b996fd6bd 100644
--- a/activerecord/CHANGELOG.md
+++ b/activerecord/CHANGELOG.md
@@ -1,3 +1,13 @@
+* Doing count on relations that contain LEFT OUTER JOIN Arel node no longer
+ force a DISTINCT. This solves issues when using count after a left_joins.
+
+ *Maxime Handfield Lapointe*
+
+* RecordNotFound raised by association.find exposes `id`, `primary_key` and
+ `model` methods to be consistent with RecordNotFound raised by Record.find.
+
+ *Michel Pigassou*
+
* Hashes can once again be passed to setters of `composed_of`, if all of the
mapping methods are methods implemented on `Hash`.
@@ -47,7 +57,9 @@
*Xavier Noria*
* Using `group` with an attribute that has a custom type will properly cast
- the hash keys after calling a calculation method like `count`. Fixes #25595.
+ the hash keys after calling a calculation method like `count`.
+
+ Fixes #25595.
*Sean Griffin*
@@ -81,6 +93,7 @@
*Sean Griffin*
* Ensure hashes can be assigned to attributes created using `composed_of`.
+
Fixes #25210.
*Sean Griffin*
@@ -100,7 +113,7 @@
*Erol Fornoles*
-* PostgreSQL: Fix db:structure:load silent failure on SQL error.
+* PostgreSQL: Fix `db:structure:load` silent failure on SQL error.
The command line flag `-v ON_ERROR_STOP=1` should be used
when invoking `psql` to make sure errors are not suppressed.
diff --git a/activerecord/bin/test b/activerecord/bin/test
index 822e303ad8..23add35d45 100755
--- a/activerecord/bin/test
+++ b/activerecord/bin/test
@@ -1,6 +1,8 @@
#!/usr/bin/env ruby
-COMPONENT_ROOT = File.expand_path("../../", __FILE__)
+
+COMPONENT_ROOT = File.expand_path("..", __dir__)
require File.expand_path("../tools/test", COMPONENT_ROOT)
+
module Minitest
def self.plugin_active_record_options(opts, options)
opts.separator ""
diff --git a/activerecord/lib/active_record.rb b/activerecord/lib/active_record.rb
index fb7b8df01d..3b5dab16cb 100644
--- a/activerecord/lib/active_record.rb
+++ b/activerecord/lib/active_record.rb
@@ -68,7 +68,6 @@ module ActiveRecord
autoload :StatementCache
autoload :Store
autoload :Suppressor
- autoload :TableMetadata
autoload :Timestamp
autoload :Transactions
autoload :Translation
@@ -101,6 +100,7 @@ module ActiveRecord
end
autoload :Result
+ autoload :TableMetadata
end
module Coders
diff --git a/activerecord/lib/active_record/aggregations.rb b/activerecord/lib/active_record/aggregations.rb
index 55076c4314..8979b13286 100644
--- a/activerecord/lib/active_record/aggregations.rb
+++ b/activerecord/lib/active_record/aggregations.rb
@@ -242,8 +242,8 @@ module ActiveRecord
private
def reader_method(name, class_name, mapping, allow_nil, constructor)
define_method(name) do
- if @aggregation_cache[name].nil? && (!allow_nil || mapping.any? {|key, _| !_read_attribute(key).nil? })
- attrs = mapping.collect {|key, _| _read_attribute(key)}
+ if @aggregation_cache[name].nil? && (!allow_nil || mapping.any? { |key, _| !_read_attribute(key).nil? })
+ attrs = mapping.collect { |key, _| _read_attribute(key) }
object = constructor.respond_to?(:call) ?
constructor.call(*attrs) :
class_name.constantize.send(constructor, *attrs)
diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb
index 6e5877f6f5..7c688d663c 100644
--- a/activerecord/lib/active_record/associations/collection_association.rb
+++ b/activerecord/lib/active_record/associations/collection_association.rb
@@ -111,47 +111,47 @@ module ActiveRecord
end
end
- def first(*args)
- first_nth_or_last(:first, *args)
+ def first(limit = nil)
+ find_nth_or_last(:first, limit)
end
- def second(*args)
- first_nth_or_last(:second, *args)
+ def second
+ find_nth_or_last(:second)
end
- def third(*args)
- first_nth_or_last(:third, *args)
+ def third
+ find_nth_or_last(:third)
end
- def fourth(*args)
- first_nth_or_last(:fourth, *args)
+ def fourth
+ find_nth_or_last(:fourth)
end
- def fifth(*args)
- first_nth_or_last(:fifth, *args)
+ def fifth
+ find_nth_or_last(:fifth)
end
- def forty_two(*args)
- first_nth_or_last(:forty_two, *args)
+ def forty_two
+ find_nth_or_last(:forty_two)
end
- def third_to_last(*args)
- first_nth_or_last(:third_to_last, *args)
+ def third_to_last
+ find_nth_or_last(:third_to_last)
end
- def second_to_last(*args)
- first_nth_or_last(:second_to_last, *args)
+ def second_to_last
+ find_nth_or_last(:second_to_last)
end
- def last(*args)
- first_nth_or_last(:last, *args)
+ def last(limit = nil)
+ find_nth_or_last(:last, limit)
end
- def take(n = nil)
- if loaded?
- n ? target.take(n) : target.first
+ def take(limit = nil)
+ if find_from_target?
+ limit ? load_target.take(limit) : load_target.first
else
- scope.take(n)
+ scope.take(limit)
end
end
@@ -221,11 +221,11 @@ module ActiveRecord
dependent = if dependent
dependent
- elsif options[:dependent] == :destroy
- :delete_all
- else
- options[:dependent]
- end
+ elsif options[:dependent] == :destroy
+ :delete_all
+ else
+ options[:dependent]
+ end
delete_or_nullify_all_records(dependent).tap do
reset
@@ -608,14 +608,10 @@ module ActiveRecord
# * target already loaded
# * owner is new record
# * target contains new or changed record(s)
- def fetch_first_nth_or_last_using_find?(args)
- if args.first.is_a?(Hash)
- true
- else
- !(loaded? ||
- owner.new_record? ||
- target.any? { |record| record.new_record? || record.changed? })
- end
+ def find_from_target?
+ loaded? ||
+ owner.new_record? ||
+ target.any? { |record| record.new_record? || record.changed? }
end
def include_in_memory?(record)
@@ -646,11 +642,9 @@ module ActiveRecord
end
# Fetches the first/last using SQL if possible, otherwise from the target array.
- def first_nth_or_last(type, *args)
- args.shift if args.first.is_a?(Hash) && args.first.empty?
-
- collection = fetch_first_nth_or_last_using_find?(args) ? scope : load_target
- collection.send(type, *args)
+ def find_nth_or_last(ordinal, limit = nil)
+ collection = find_from_target? ? load_target : scope
+ limit ? collection.send(ordinal, limit) : collection.send(ordinal)
end
end
end
diff --git a/activerecord/lib/active_record/associations/collection_proxy.rb b/activerecord/lib/active_record/associations/collection_proxy.rb
index 806a905323..36f6c1b9c3 100644
--- a/activerecord/lib/active_record/associations/collection_proxy.rb
+++ b/activerecord/lib/active_record/associations/collection_proxy.rb
@@ -28,7 +28,6 @@ module ActiveRecord
# is computed directly through SQL and does not trigger by itself the
# instantiation of the actual post records.
class CollectionProxy < Relation
- delegate(*(ActiveRecord::Calculations.public_instance_methods - [:count]), to: :scope)
delegate :exists?, :update_all, :arel, to: :scope
def initialize(klass, association) #:nodoc:
@@ -167,44 +166,44 @@ module ActiveRecord
# another_person_without.pets # => []
# another_person_without.pets.first # => nil
# another_person_without.pets.first(3) # => []
- def first(*args)
- @association.first(*args)
+ def first(limit = nil)
+ @association.first(limit)
end
# Same as #first except returns only the second record.
- def second(*args)
- @association.second(*args)
+ def second
+ @association.second
end
# Same as #first except returns only the third record.
- def third(*args)
- @association.third(*args)
+ def third
+ @association.third
end
# Same as #first except returns only the fourth record.
- def fourth(*args)
- @association.fourth(*args)
+ def fourth
+ @association.fourth
end
# Same as #first except returns only the fifth record.
- def fifth(*args)
- @association.fifth(*args)
+ def fifth
+ @association.fifth
end
# Same as #first except returns only the forty second record.
# Also known as accessing "the reddit".
- def forty_two(*args)
- @association.forty_two(*args)
+ def forty_two
+ @association.forty_two
end
# Same as #first except returns only the third-to-last record.
- def third_to_last(*args)
- @association.third_to_last(*args)
+ def third_to_last
+ @association.third_to_last
end
# Same as #first except returns only the second-to-last record.
- def second_to_last(*args)
- @association.second_to_last(*args)
+ def second_to_last
+ @association.second_to_last
end
# Returns the last record, or the last +n+ records, from the collection.
@@ -233,8 +232,8 @@ module ActiveRecord
# another_person_without.pets # => []
# another_person_without.pets.last # => nil
# another_person_without.pets.last(3) # => []
- def last(*args)
- @association.last(*args)
+ def last(limit = nil)
+ @association.last(limit)
end
# Gives a record (or N records if a parameter is supplied) from the collection
@@ -262,8 +261,8 @@ module ActiveRecord
# another_person_without.pets # => []
# another_person_without.pets.take # => nil
# another_person_without.pets.take(2) # => []
- def take(n = nil)
- @association.take(n)
+ def take(limit = nil)
+ @association.take(limit)
end
# Returns a new object of the collection type that has been instantiated
@@ -738,6 +737,14 @@ module ActiveRecord
@association.count(column_name, &block)
end
+ def calculate(operation, column_name)
+ null_scope? ? scope.calculate(operation, column_name) : super
+ end
+
+ def pluck(*column_names)
+ null_scope? ? scope.pluck(*column_names) : super
+ end
+
# Returns the size of the collection. If the collection hasn't been loaded,
# it executes a <tt>SELECT COUNT(*)</tt> query. Else it calls <tt>collection.size</tt>.
#
@@ -1073,6 +1080,10 @@ module ActiveRecord
private
+ def null_scope?
+ @association.null_scope?
+ end
+
def exec_queries
load_target
end
diff --git a/activerecord/lib/active_record/associations/has_one_association.rb b/activerecord/lib/active_record/associations/has_one_association.rb
index 08a4611013..5ea9577301 100644
--- a/activerecord/lib/active_record/associations/has_one_association.rb
+++ b/activerecord/lib/active_record/associations/has_one_association.rb
@@ -32,7 +32,7 @@ module ActiveRecord
raise_on_type_mismatch!(record) if record
load_target
- return self.target if !(target || record)
+ return target unless target || record
assigning_another_record = target != record
if assigning_another_record || record.changed?
diff --git a/activerecord/lib/active_record/associations/preloader/through_association.rb b/activerecord/lib/active_record/associations/preloader/through_association.rb
index f53c30f80e..be9dfe7686 100644
--- a/activerecord/lib/active_record/associations/preloader/through_association.rb
+++ b/activerecord/lib/active_record/associations/preloader/through_association.rb
@@ -79,7 +79,6 @@ module ActiveRecord
end
end
-
def through_scope
scope = through_reflection.klass.unscoped
diff --git a/activerecord/lib/active_record/attribute.rb b/activerecord/lib/active_record/attribute.rb
index 95b3adae5f..380593e809 100644
--- a/activerecord/lib/active_record/attribute.rb
+++ b/activerecord/lib/active_record/attribute.rb
@@ -65,7 +65,7 @@ module ActiveRecord
def with_value_from_user(value)
type.assert_valid_value(value)
- self.class.from_user(name, value, type, self)
+ self.class.from_user(name, value, type, original_attribute || self)
end
def with_value_from_database(value)
diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb
index 367e7fba84..ba26a11b39 100644
--- a/activerecord/lib/active_record/attribute_methods.rb
+++ b/activerecord/lib/active_record/attribute_methods.rb
@@ -162,9 +162,9 @@ module ActiveRecord
def attribute_names
@attribute_names ||= if !abstract_class? && table_exists?
attribute_types.keys
- else
- []
- end
+ else
+ []
+ end
end
# Returns true if the given attribute exists, otherwise false.
diff --git a/activerecord/lib/active_record/attribute_methods/serialization.rb b/activerecord/lib/active_record/attribute_methods/serialization.rb
index 8fb29fb358..c70178cd2c 100644
--- a/activerecord/lib/active_record/attribute_methods/serialization.rb
+++ b/activerecord/lib/active_record/attribute_methods/serialization.rb
@@ -51,11 +51,11 @@ module ActiveRecord
# using the #as_json hook.
coder = if class_name_or_coder == ::JSON
Coders::JSON
- elsif [:load, :dump].all? { |x| class_name_or_coder.respond_to?(x) }
- class_name_or_coder
- else
- Coders::YAMLColumn.new(class_name_or_coder)
- end
+ elsif [:load, :dump].all? { |x| class_name_or_coder.respond_to?(x) }
+ class_name_or_coder
+ else
+ Coders::YAMLColumn.new(class_name_or_coder)
+ end
decorate_attribute_type(attr_name, :serialize) do |type|
Type::Serialized.new(type, coder)
diff --git a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
index ff9fd206c0..2c8e86fbb2 100644
--- a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
+++ b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
@@ -85,7 +85,7 @@ module ActiveRecord
def create_time_zone_conversion_attribute?(name, cast_type)
enabled_for_column = time_zone_aware_attributes &&
- !self.skip_time_zone_conversion_for_attributes.include?(name.to_sym)
+ !skip_time_zone_conversion_for_attributes.include?(name.to_sym)
result = enabled_for_column &&
time_zone_aware_types.include?(cast_type.type)
diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb
index 01d7886406..1e7e939097 100644
--- a/activerecord/lib/active_record/base.rb
+++ b/activerecord/lib/active_record/base.rb
@@ -312,8 +312,8 @@ module ActiveRecord #:nodoc:
include NestedAttributes
include Aggregations
include Transactions
- include NoTouching
include TouchLater
+ include NoTouching
include Reflection
include Serialization
include Store
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
index 535d79b525..d0c5bbe17d 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
@@ -617,7 +617,7 @@ module ActiveRecord
def attempt_to_checkout_all_existing_connections(raise_on_acquisition_timeout = true)
collected_conns = synchronize do
# account for our own connections
- @connections.select {|conn| conn.owner == Thread.current}
+ @connections.select { |conn| conn.owner == Thread.current }
end
newly_checked_out = []
@@ -654,7 +654,7 @@ module ActiveRecord
if release_newly_checked_out && newly_checked_out
# releasing only those conns that were checked out in this method, conns
# checked outside this method (before it was called) are not for us to release
- newly_checked_out.each {|conn| checkin(conn)}
+ newly_checked_out.each { |conn| checkin(conn) }
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
index 452e78a40b..126047584e 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
@@ -90,6 +90,7 @@ module ActiveRecord
# +binds+ as the bind substitutes. +name+ is logged along with
# the executed +sql+ statement.
def exec_insert(sql, name = nil, binds = [], pk = nil, sequence_name = nil)
+ sql, binds = sql_for_insert(sql, pk, nil, sequence_name, binds)
exec_query(sql, name, binds)
end
@@ -121,8 +122,7 @@ module ActiveRecord
# If the next id was calculated in advance (as in Oracle), it should be
# passed in as +id_value+.
def insert(arel, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = [])
- sql, binds, pk, sequence_name = sql_for_insert(to_sql(arel, binds), pk, id_value, sequence_name, binds)
- value = exec_insert(sql, name, binds, pk, sequence_name)
+ value = exec_insert(to_sql(arel, binds), name, binds, pk, sequence_name)
id_value || last_inserted_id(value)
end
alias create insert
@@ -344,7 +344,7 @@ module ActiveRecord
if limit.is_a?(Integer) || limit.is_a?(Arel::Nodes::SqlLiteral)
limit
elsif limit.to_s.include?(",")
- Arel.sql limit.to_s.split(",").map{ |i| Integer(i) }.join(",")
+ Arel.sql limit.to_s.split(",").map { |i| Integer(i) }.join(",")
else
Integer(limit)
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
index c10f45937e..d9a799676f 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
@@ -211,7 +211,7 @@ module ActiveRecord
def initialize(name, temporary = false, options = nil, as = nil, comment: nil)
@columns_hash = {}
- @indexes = {}
+ @indexes = []
@foreign_keys = []
@primary_keys = nil
@temporary = temporary
@@ -327,7 +327,7 @@ module ActiveRecord
#
# index(:account_id, name: 'index_projects_on_account_id')
def index(column_name, options = {})
- indexes[column_name] = options
+ indexes << [column_name, options]
end
def foreign_key(table_name, options = {}) # :nodoc:
@@ -341,9 +341,7 @@ module ActiveRecord
# <tt>:updated_at</tt> to the table. See {connection.add_timestamps}[rdoc-ref:SchemaStatements#add_timestamps]
#
# t.timestamps null: false
- def timestamps(*args)
- options = args.extract_options!
-
+ def timestamps(**options)
options[:null] = false if options[:null].nil?
column(:created_at, :datetime, options)
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
index d2ebc36fff..afa0860707 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
@@ -278,7 +278,7 @@ module ActiveRecord
result = execute schema_creation.accept td
unless supports_indexes_in_create?
- td.indexes.each_pair do |column_name, index_options|
+ td.indexes.each do |column_name, index_options|
add_index(table_name, column_name, index_options)
end
end
@@ -339,7 +339,7 @@ module ActiveRecord
column_options.reverse_merge!(null: false)
type = column_options.delete(:type) || :integer
- t1_column, t2_column = [table_1, table_2].map{ |t| t.to_s.singularize.foreign_key }
+ t1_column, t2_column = [table_1, table_2].map { |t| t.to_s.singularize.foreign_key }
create_table(join_table_name, options.merge!(id: false)) do |td|
td.send type, t1_column, column_options
@@ -533,6 +533,10 @@ module ActiveRecord
# add_column(:measurements, :huge_integer, :decimal, precision: 30)
# # ALTER TABLE "measurements" ADD "huge_integer" decimal(30)
#
+ # # Defines a column that stores an array of a type.
+ # add_column(:users, :skills, :text, array: true)
+ # # ALTER TABLE "users" ADD "skills" text[]
+ #
# # Defines a column with a database-specific type.
# add_column(:shapes, :triangle, 'polygon')
# # ALTER TABLE "shapes" ADD "triangle" polygon
@@ -962,7 +966,7 @@ module ActiveRecord
def foreign_key_for(from_table, options_or_to_table = {}) # :nodoc:
return unless supports_foreign_keys?
- foreign_keys(from_table).detect {|fk| fk.defined_for? options_or_to_table }
+ foreign_keys(from_table).detect { |fk| fk.defined_for? options_or_to_table }
end
def foreign_key_for!(from_table, options_or_to_table = {}) # :nodoc:
@@ -994,7 +998,7 @@ module ActiveRecord
if supports_multi_insert?
sql = "INSERT INTO #{sm_table} (version) VALUES\n"
- sql << versions.map {|v| "('#{v}')" }.join(",\n")
+ sql << versions.map { |v| "('#{v}')" }.join(",\n")
sql << ";\n\n"
sql
else
@@ -1024,7 +1028,7 @@ module ActiveRecord
sm_table = quote_table_name(ActiveRecord::Migrator.schema_migrations_table_name)
migrated = select_values("SELECT version FROM #{sm_table}").map(&:to_i)
- paths = migrations_paths.map {|p| "#{p}/[0-9]*_*.rb" }
+ paths = migrations_paths.map { |p| "#{p}/[0-9]*_*.rb" }
versions = Dir[*paths].map do |filename|
filename.split("/").last.split("_").first.to_i
end
@@ -1033,9 +1037,9 @@ module ActiveRecord
execute "INSERT INTO #{sm_table} (version) VALUES ('#{version}')"
end
- inserting = (versions - migrated).select {|v| v < version}
+ inserting = (versions - migrated).select { |v| v < version }
if inserting.any?
- if (duplicate = inserting.detect {|v| inserting.count(v) > 1})
+ if (duplicate = inserting.detect { |v| inserting.count(v) > 1 })
raise "Duplicate migration #{duplicate}. Please renumber your migrations to resolve the conflict."
end
execute insert_versions_sql(inserting)
@@ -1161,31 +1165,34 @@ module ActiveRecord
end
protected
- def add_index_sort_order(option_strings, column_names, options = {})
- if options.is_a?(Hash) && order = options[:order]
+
+ def add_index_sort_order(quoted_columns, **options)
+ if order = options[:order]
case order
when Hash
- column_names.each {|name| option_strings[name] += " #{order[name].upcase}" if order.has_key?(name)}
+ quoted_columns.each { |name, column| column << " #{order[name].upcase}" if order[name].present? }
when String
- column_names.each {|name| option_strings[name] += " #{order.upcase}"}
+ quoted_columns.each { |name, column| column << " #{order.upcase}" if order.present? }
end
end
- return option_strings
+ quoted_columns
end
# Overridden by the MySQL adapter for supporting index lengths
- def quoted_columns_for_index(column_names, options = {})
- return [column_names] if column_names.is_a?(String)
-
- option_strings = Hash[column_names.map {|name| [name, ""]}]
-
- # add index sort order if supported
+ def add_options_for_index_columns(quoted_columns, **options)
if supports_index_sort_order?
- option_strings = add_index_sort_order(option_strings, column_names, options)
+ quoted_columns = add_index_sort_order(quoted_columns, options)
end
- column_names.map {|name| quote_column_name(name) + option_strings[name]}
+ quoted_columns
+ end
+
+ def quoted_columns_for_index(column_names, **options)
+ return [column_names] if column_names.is_a?(String)
+
+ quoted_columns = Hash[column_names.map { |name| [name, quote_column_name(name).dup] }]
+ add_options_for_index_columns(quoted_columns, options).values
end
def index_name_for_remove(table_name, options = {})
@@ -1208,7 +1215,7 @@ module ActiveRecord
checks << lambda { |i| i.columns.join("_and_") == column_names.join("_and_") }
end
- raise ArgumentError "No name or columns specified" if checks.none?
+ raise ArgumentError, "No name or columns specified" if checks.none?
matching_indexes = indexes(table_name).select { |i| checks.all? { |check| check[i] } }
diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
index 0c7197a002..4dde525ebc 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
@@ -433,16 +433,16 @@ module ActiveRecord
@connection
end
- def case_sensitive_comparison(table, attribute, column, value)
- table[attribute].eq(Arel::Nodes::BindParam.new)
+ def case_sensitive_comparison(attribute, column, value) # :nodoc:
+ attribute.eq(value)
end
- def case_insensitive_comparison(table, attribute, column, value)
+ def case_insensitive_comparison(attribute, column, value) # :nodoc:
if can_perform_case_insensitive_comparison_for?(column)
- table[attribute].lower.eq(table.lower(Arel::Nodes::BindParam.new))
- else
- table[attribute].eq(Arel::Nodes::BindParam.new)
+ value = attribute.relation.lower(value)
+ attribute = attribute.lower
end
+ attribute.eq(value)
end
def can_perform_case_insensitive_comparison_for?(column)
diff --git a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
index bb1b753a37..f09c9c9e7f 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
@@ -613,12 +613,11 @@ module ActiveRecord
SQL
end
- def case_sensitive_comparison(table, attribute, column, value)
+ def case_sensitive_comparison(attribute, column, value) # :nodoc:
if column.collation && !column.case_sensitive?
- table[attribute].eq(Arel::Nodes::Bin.new(Arel::Nodes::BindParam.new))
- else
- super
+ value = Arel::Nodes::Bin.new(value)
end
+ attribute.eq(value)
end
def can_perform_case_insensitive_comparison_for?(column)
@@ -680,13 +679,13 @@ module ActiveRecord
m.register_type(%r(enum)i) do |sql_type|
limit = sql_type[/^enum\((.+)\)/i, 1]
- .split(",").map{|enum| enum.strip.length - 2}.max
+ .split(",").map { |enum| enum.strip.length - 2 }.max
MysqlString.new(limit: limit)
end
m.register_type(%r(^set)i) do |sql_type|
limit = sql_type[/^set\((.+)\)/i, 1]
- .split(",").map{|set| set.strip.length - 1}.sum - 1
+ .split(",").map { |set| set.strip.length - 1 }.sum - 1
MysqlString.new(limit: limit)
end
end
@@ -713,32 +712,25 @@ module ActiveRecord
MySQL::TypeMetadata.new(super(sql_type), extra: extra, strict: strict_mode?)
end
- def add_index_length(option_strings, column_names, options = {})
- if options.is_a?(Hash) && length = options[:length]
+ def add_index_length(quoted_columns, **options)
+ if length = options[:length]
case length
when Hash
- column_names.each {|name| option_strings[name] += "(#{length[name]})" if length.has_key?(name) && length[name].present?}
+ quoted_columns.each { |name, column| column << "(#{length[name]})" if length[name].present? }
when Integer
- column_names.each {|name| option_strings[name] += "(#{length})"}
+ quoted_columns.each { |name, column| column << "(#{length})" }
end
end
- return option_strings
+ quoted_columns
end
- def quoted_columns_for_index(column_names, options = {})
- option_strings = Hash[column_names.map {|name| [name, ""]}]
-
- # add index length
- option_strings = add_index_length(option_strings, column_names, options)
-
- # add index sort order
- option_strings = add_index_sort_order(option_strings, column_names, options)
-
- column_names.map {|name| quote_column_name(name) + option_strings[name]}
+ def add_options_for_index_columns(quoted_columns, **options)
+ quoted_columns = add_index_length(quoted_columns, options)
+ super
end
- # See https://dev.mysql.com/doc/refman/5.7/en/error-messages-server.html
+ # See https://dev.mysql.com/doc/refman/5.7/en/error-messages-server.html
ER_DUP_ENTRY = 1062
ER_NO_REFERENCED_ROW_2 = 1452
ER_DATA_TOO_LONG = 1406
@@ -800,7 +792,7 @@ module ActiveRecord
end
def remove_columns_sql(table_name, *column_names)
- column_names.map {|column_name| remove_column_sql(table_name, column_name) }
+ column_names.map { |column_name| remove_column_sql(table_name, column_name) }
end
def add_index_sql(table_name, column_name, options = {})
diff --git a/activerecord/lib/active_record/connection_adapters/connection_specification.rb b/activerecord/lib/active_record/connection_adapters/connection_specification.rb
index a7869f44ea..be6b55e53c 100644
--- a/activerecord/lib/active_record/connection_adapters/connection_specification.rb
+++ b/activerecord/lib/active_record/connection_adapters/connection_specification.rb
@@ -78,10 +78,12 @@ module ActiveRecord
def raw_config
if uri.opaque
- query_hash.merge( "adapter" => @adapter,
+ query_hash.merge(
+ "adapter" => @adapter,
"database" => uri.opaque)
else
- query_hash.merge( "adapter" => @adapter,
+ query_hash.merge(
+ "adapter" => @adapter,
"username" => uri.user,
"password" => uri.password,
"port" => uri.port,
diff --git a/activerecord/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb b/activerecord/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb
index 0b7dea232f..925555703d 100644
--- a/activerecord/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb
@@ -39,7 +39,7 @@ module ActiveRecord
def compute_column_widths(result)
[].tap do |widths|
result.columns.each_with_index do |column, i|
- cells_in_column = [column] + result.rows.map {|r| r[i].nil? ? "NULL" : r[i].to_s}
+ cells_in_column = [column] + result.rows.map { |r| r[i].nil? ? "NULL" : r[i].to_s }
widths << cells_in_column.map(&:length).max
end
end
@@ -47,7 +47,7 @@ module ActiveRecord
def build_separator(widths)
padding = 1
- "+" + widths.map {|w| "-" * (w + (padding*2))}.join("+") + "+"
+ "+" + widths.map { |w| "-" * (w + (padding*2)) }.join("+") + "+"
end
def build_cells(items, widths)
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb b/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb
index 87338986b9..46aca2ab54 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb
@@ -113,7 +113,7 @@ module ActiveRecord
end
def exec_delete(sql, name = nil, binds = [])
- execute_and_clear(sql, name, binds) {|result| result.cmd_tuples }
+ execute_and_clear(sql, name, binds) { |result| result.cmd_tuples }
end
alias :exec_update :exec_delete
@@ -134,16 +134,20 @@ module ActiveRecord
end
def exec_insert(sql, name = nil, binds = [], pk = nil, sequence_name = nil)
- val = exec_query(sql, name, binds)
- if !use_insert_returning? && pk
+ if use_insert_returning? || pk == false
+ super
+ else
+ result = exec_query(sql, name, binds)
unless sequence_name
table_ref = extract_table_ref_from_insert_sql(sql)
- sequence_name = default_sequence_name(table_ref, pk)
- return val unless sequence_name
+ if table_ref
+ pk = primary_key(table_ref) if pk.nil?
+ pk = suppress_composite_primary_key(pk)
+ sequence_name = default_sequence_name(table_ref, pk)
+ end
+ return result unless sequence_name
end
last_insert_id_result(sequence_name)
- else
- val
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/explain_pretty_printer.rb b/activerecord/lib/active_record/connection_adapters/postgresql/explain_pretty_printer.rb
index f95a63968c..99f3a5bbdf 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/explain_pretty_printer.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/explain_pretty_printer.rb
@@ -28,7 +28,7 @@ module ActiveRecord
pp << header.center(width).rstrip
pp << "-" * width
- pp += lines.map {|line| " #{line}"}
+ pp += lines.map { |line| " #{line}" }
nrows = result.rows.length
rows_label = nrows == 1 ? "row" : "rows"
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
index 531d323a55..696f2cd703 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
@@ -658,7 +658,7 @@ module ActiveRecord
# PostgreSQL requires the ORDER BY columns in the select list for distinct queries, and
# requires that the ORDER BY include the distinct column.
def columns_for_distinct(columns, orders) #:nodoc:
- order_columns = orders.reject(&:blank?).map{ |s|
+ order_columns = orders.reject(&:blank?).map { |s|
# Convert Arel node to string
s = s.to_sql unless s.is_a?(String)
# Remove any ASC/DESC modifiers
diff --git a/activerecord/lib/active_record/connection_adapters/schema_cache.rb b/activerecord/lib/active_record/connection_adapters/schema_cache.rb
index d1708a6af8..8219f132c3 100644
--- a/activerecord/lib/active_record/connection_adapters/schema_cache.rb
+++ b/activerecord/lib/active_record/connection_adapters/schema_cache.rb
@@ -35,7 +35,6 @@ module ActiveRecord
alias table_exists? data_source_exists?
deprecate table_exists?: "use #data_source_exists? instead"
-
# Add internal cache for table with +table_name+.
def add(table_name)
if data_source_exists?(table_name)
diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
index 57699badba..e2b534b511 100644
--- a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
@@ -418,7 +418,7 @@ module ActiveRecord
def rename_column(table_name, column_name, new_column_name) #:nodoc:
column = column_for(table_name, column_name)
- alter_table(table_name, rename: {column.name => new_column_name.to_s})
+ alter_table(table_name, rename: { column.name => new_column_name.to_s })
rename_column_indexes(table_name, column.name, new_column_name)
end
@@ -432,7 +432,7 @@ module ActiveRecord
def alter_table(table_name, options = {}) #:nodoc:
altered_table_name = "a#{table_name}"
- caller = lambda {|definition| yield definition if block_given?}
+ caller = lambda { |definition| yield definition if block_given? }
transaction do
move_table(table_name, altered_table_name,
@@ -482,7 +482,7 @@ module ActiveRecord
end
to_column_names = columns(to).map(&:name)
- columns = index.columns.map {|c| rename[c] || c }.select do |column|
+ columns = index.columns.map { |c| rename[c] || c }.select do |column|
to_column_names.include?(column)
end
@@ -496,10 +496,10 @@ module ActiveRecord
end
def copy_table_contents(from, to, columns, rename = {}) #:nodoc:
- column_mappings = Hash[columns.map {|name| [name, name]}]
+ column_mappings = Hash[columns.map { |name| [name, name] }]
rename.each { |a| column_mappings[a.last] = a.first }
from_columns = columns(from).collect(&:name)
- columns = columns.find_all{|col| from_columns.include?(column_mappings[col])}
+ columns = columns.find_all { |col| from_columns.include?(column_mappings[col]) }
from_columns_to_copy = columns.map { |col| column_mappings[col] }
quoted_columns = columns.map { |col| quote_column_name(col) } * ","
quoted_from_columns = from_columns_to_copy.map { |col| quote_column_name(col) } * ","
diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb
index 19a2720913..cb11cdefd9 100644
--- a/activerecord/lib/active_record/core.rb
+++ b/activerecord/lib/active_record/core.rb
@@ -83,7 +83,7 @@ module ActiveRecord
The flag error_on_ignored_order_or_limit is deprecated. Limits are
now supported. Please use error_on_ignored_order instead.
MSG
- self.error_on_ignored_order
+ error_on_ignored_order
end
def error_on_ignored_order_or_limit
@@ -268,7 +268,7 @@ module ActiveRecord
# Returns an instance of <tt>Arel::Table</tt> loaded with the current table name.
#
# class Post < ActiveRecord::Base
- # scope :published_and_commented, -> { published.and(self.arel_table[:comments_count].gt(0)) }
+ # scope :published_and_commented, -> { published.and(arel_table[:comments_count].gt(0)) }
# end
def arel_table # :nodoc:
@arel_table ||= Arel::Table.new(table_name, type_caster: type_caster)
@@ -498,14 +498,15 @@ module ActiveRecord
# We check defined?(@attributes) not to issue warnings if the object is
# allocated but not initialized.
inspection = if defined?(@attributes) && @attributes
- self.class.column_names.collect { |name|
+ self.class.column_names.collect do |name|
if has_attribute?(name)
"#{name}: #{attribute_for_inspect(name)}"
end
- }.compact.join(", ")
- else
- "not initialized"
- end
+ end.compact.join(", ")
+ else
+ "not initialized"
+ end
+
"#<#{self.class} #{inspection}>"
end
diff --git a/activerecord/lib/active_record/counter_cache.rb b/activerecord/lib/active_record/counter_cache.rb
index 0edb4b8a34..e2da512813 100644
--- a/activerecord/lib/active_record/counter_cache.rb
+++ b/activerecord/lib/active_record/counter_cache.rb
@@ -26,7 +26,7 @@ module ActiveRecord
has_many_association = has_many.find { |association| association.counter_cache_column && association.counter_cache_column.to_sym == counter_association.to_sym }
counter_association = has_many_association.plural_name if has_many_association
end
- raise ArgumentError, "'#{self.name}' has no association called '#{counter_association}'" unless has_many_association
+ raise ArgumentError, "'#{name}' has no association called '#{counter_association}'" unless has_many_association
if has_many_association.is_a? ActiveRecord::Reflection::ThroughReflection
has_many_association = has_many_association.through_reflection
diff --git a/activerecord/lib/active_record/enum.rb b/activerecord/lib/active_record/enum.rb
index 73f122cfd7..0a94ab58dd 100644
--- a/activerecord/lib/active_record/enum.rb
+++ b/activerecord/lib/active_record/enum.rb
@@ -227,7 +227,7 @@ module ActiveRecord
def raise_conflict_error(enum_name, method_name, type: "instance", source: "Active Record")
raise ArgumentError, ENUM_CONFLICT_MESSAGE % {
enum: enum_name,
- klass: self.name,
+ klass: name,
type: type,
method: method_name,
source: source
diff --git a/activerecord/lib/active_record/fixture_set/file.rb b/activerecord/lib/active_record/fixture_set/file.rb
index 0888208709..5ba354d758 100644
--- a/activerecord/lib/active_record/fixture_set/file.rb
+++ b/activerecord/lib/active_record/fixture_set/file.rb
@@ -38,7 +38,7 @@ module ActiveRecord
if row
row.last
else
- {'model_class': nil}
+ { 'model_class': nil }
end
end
end
diff --git a/activerecord/lib/active_record/locking/optimistic.rb b/activerecord/lib/active_record/locking/optimistic.rb
index 21a6a2c55f..1b6cda3861 100644
--- a/activerecord/lib/active_record/locking/optimistic.rb
+++ b/activerecord/lib/active_record/locking/optimistic.rb
@@ -184,7 +184,6 @@ module ActiveRecord
end
end
-
# In de/serialize we change `nil` to 0, so that we can allow passing
# `nil` values to `lock_version`, and not result in `ActiveRecord::StaleObjectError`
# during update record.
diff --git a/activerecord/lib/active_record/log_subscriber.rb b/activerecord/lib/active_record/log_subscriber.rb
index 20910fbb15..f31931316c 100644
--- a/activerecord/lib/active_record/log_subscriber.rb
+++ b/activerecord/lib/active_record/log_subscriber.rb
@@ -15,11 +15,6 @@ module ActiveRecord
rt
end
- def initialize
- super
- @odd = false
- end
-
def render_bind(attr, type_casted_value)
value = if attr.type.binary? && attr.value
"<#{attr.value_for_database.to_s.bytesize} bytes of binary data>"
diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb
index 9206547acf..063366bc60 100644
--- a/activerecord/lib/active_record/migration.rb
+++ b/activerecord/lib/active_record/migration.rb
@@ -725,7 +725,7 @@ module ActiveRecord
# end
def reversible
helper = ReversibleBlockHelper.new(reverting?)
- execute_block{ yield helper }
+ execute_block { yield helper }
end
# Runs the given migration classes.
diff --git a/activerecord/lib/active_record/migration/compatibility.rb b/activerecord/lib/active_record/migration/compatibility.rb
index a79251f908..04e538baa5 100644
--- a/activerecord/lib/active_record/migration/compatibility.rb
+++ b/activerecord/lib/active_record/migration/compatibility.rb
@@ -21,7 +21,7 @@ module ActiveRecord
end
alias :belongs_to :references
- def timestamps(*, **options)
+ def timestamps(**options)
options[:null] = true if options[:null].nil?
super
end
@@ -59,7 +59,7 @@ module ActiveRecord
end
alias :add_belongs_to :add_reference
- def add_timestamps(*, **options)
+ def add_timestamps(_, **options)
options[:null] = true if options[:null].nil?
super
end
diff --git a/activerecord/lib/active_record/model_schema.rb b/activerecord/lib/active_record/model_schema.rb
index 1537fffc22..5718e7fdd0 100644
--- a/activerecord/lib/active_record/model_schema.rb
+++ b/activerecord/lib/active_record/model_schema.rb
@@ -173,11 +173,11 @@ module ActiveRecord
end
def full_table_name_prefix #:nodoc:
- (parents.detect{ |p| p.respond_to?(:table_name_prefix) } || self).table_name_prefix
+ (parents.detect { |p| p.respond_to?(:table_name_prefix) } || self).table_name_prefix
end
def full_table_name_suffix #:nodoc:
- (parents.detect {|p| p.respond_to?(:table_name_suffix) } || self).table_name_suffix
+ (parents.detect { |p| p.respond_to?(:table_name_suffix) } || self).table_name_suffix
end
# Defines the name of the table column which will store the class name on single-table
@@ -433,7 +433,7 @@ module ActiveRecord
ActiveSupport::Deprecation.warn(<<-WARNING.strip_heredoc)
The behavior of the `:point` type will be changing in Rails 5.1 to
return a `Point` object, rather than an `Array`. If you'd like to
- keep the old behavior, you can add this line to #{self.name}:
+ keep the old behavior, you can add this line to #{name}:
attribute :#{column.name}, :legacy_point#{array_arguments}
diff --git a/activerecord/lib/active_record/nested_attributes.rb b/activerecord/lib/active_record/nested_attributes.rb
index 2cbef2425b..86f8cb5d26 100644
--- a/activerecord/lib/active_record/nested_attributes.rb
+++ b/activerecord/lib/active_record/nested_attributes.rb
@@ -477,7 +477,7 @@ module ActiveRecord
existing_records = if association.loaded?
association.target
else
- attribute_ids = attributes_collection.map {|a| a["id"] || a[:id] }.compact
+ attribute_ids = attributes_collection.map { |a| a["id"] || a[:id] }.compact
attribute_ids.empty? ? [] : association.scope.where(association.klass.primary_key => attribute_ids)
end
@@ -575,7 +575,7 @@ module ActiveRecord
end
def allow_destroy?(association_name)
- self.nested_attributes_options[association_name][:allow_destroy]
+ nested_attributes_options[association_name][:allow_destroy]
end
def raise_nested_attributes_record_not_found!(association_name, record_id)
diff --git a/activerecord/lib/active_record/no_touching.rb b/activerecord/lib/active_record/no_touching.rb
index edb5066fa0..4059020e25 100644
--- a/activerecord/lib/active_record/no_touching.rb
+++ b/activerecord/lib/active_record/no_touching.rb
@@ -45,6 +45,10 @@ module ActiveRecord
NoTouching.applied_to?(self.class)
end
+ def touch_later(*) # :nodoc:
+ super unless no_touching?
+ end
+
def touch(*) # :nodoc:
super unless no_touching?
end
diff --git a/activerecord/lib/active_record/railtie.rb b/activerecord/lib/active_record/railtie.rb
index 35c19b27bb..989d23bc37 100644
--- a/activerecord/lib/active_record/railtie.rb
+++ b/activerecord/lib/active_record/railtie.rb
@@ -23,7 +23,6 @@ module ActiveRecord
"ActiveRecord::RecordNotSaved" => :unprocessable_entity
)
-
config.active_record.use_schema_cache_dump = true
config.active_record.maintain_test_schema = true
diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake
index a2bcf54377..46235ab922 100644
--- a/activerecord/lib/active_record/railties/databases.rake
+++ b/activerecord/lib/active_record/railties/databases.rake
@@ -205,16 +205,16 @@ db_namespace = namespace :db do
fixtures_dir = if ENV["FIXTURES_DIR"]
File.join base_dir, ENV["FIXTURES_DIR"]
- else
- base_dir
- end
+ else
+ base_dir
+ end
fixture_files = if ENV["FIXTURES"]
ENV["FIXTURES"].split(",")
- else
- # The use of String#[] here is to support namespaced fixtures
- Dir["#{fixtures_dir}/**/*.yml"].map {|f| f[(fixtures_dir.size + 1)..-5] }
- end
+ else
+ # The use of String#[] here is to support namespaced fixtures.
+ Dir["#{fixtures_dir}/**/*.yml"].map { |f| f[(fixtures_dir.size + 1)..-5] }
+ end
ActiveRecord::FixtureSet.create_fixtures(fixtures_dir, fixture_files)
end
diff --git a/activerecord/lib/active_record/readonly_attributes.rb b/activerecord/lib/active_record/readonly_attributes.rb
index ce78f1756d..8ff265bdfa 100644
--- a/activerecord/lib/active_record/readonly_attributes.rb
+++ b/activerecord/lib/active_record/readonly_attributes.rb
@@ -16,7 +16,7 @@ module ActiveRecord
# Returns an array of all the attributes that have been specified as readonly.
def readonly_attributes
- self._attr_readonly
+ _attr_readonly
end
end
end
diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb
index 7caac60960..3553ff4da3 100644
--- a/activerecord/lib/active_record/reflection.rb
+++ b/activerecord/lib/active_record/reflection.rb
@@ -317,7 +317,6 @@ module ActiveRecord
end
end
-
# Holds all the meta-data about an aggregation as it was specified in the
# Active Record class.
class AggregateReflection < MacroReflection #:nodoc:
diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb
index 60ccb73d50..3983065d7a 100644
--- a/activerecord/lib/active_record/relation.rb
+++ b/activerecord/lib/active_record/relation.rb
@@ -657,7 +657,7 @@ module ActiveRecord
end
def pretty_print(q)
- q.pp(self.records)
+ q.pp(records)
end
# Returns true if relation is blank.
diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb
index ecf3700aab..b569abc7a8 100644
--- a/activerecord/lib/active_record/relation/calculations.rb
+++ b/activerecord/lib/active_record/relation/calculations.rb
@@ -117,7 +117,10 @@ module ActiveRecord
end
if has_include?(column_name)
- construct_relation_for_association_calculations.calculate(operation, column_name)
+ relation = construct_relation_for_association_calculations
+ relation = relation.distinct if operation.to_s.downcase == "count"
+
+ relation.calculate(operation, column_name)
else
perform_calculation(operation, column_name)
end
@@ -160,7 +163,7 @@ module ActiveRecord
#
def pluck(*column_names)
if loaded? && (column_names.map(&:to_s) - @klass.attribute_names - @klass.attribute_aliases.keys).empty?
- return @records.pluck(*column_names)
+ return records.pluck(*column_names)
end
if has_include?(column_names.first)
@@ -198,11 +201,6 @@ module ActiveRecord
if operation == "count"
column_name ||= select_for_count
-
- unless arel.ast.grep(Arel::Nodes::OuterJoin).empty?
- distinct = true
- end
-
column_name = primary_key if column_name == :all && distinct
distinct = nil if column_name =~ /\s*DISTINCT[\s(]+/i
end
diff --git a/activerecord/lib/active_record/relation/delegation.rb b/activerecord/lib/active_record/relation/delegation.rb
index b4147ce434..e1c36982dd 100644
--- a/activerecord/lib/active_record/relation/delegation.rb
+++ b/activerecord/lib/active_record/relation/delegation.rb
@@ -38,7 +38,7 @@ module ActiveRecord
delegate :to_xml, :encode_with, :length, :collect, :map, :each, :all?, :include?, :to_ary, :join,
:[], :&, :|, :+, :-, :sample, :reverse, :compact, :in_groups, :in_groups_of,
- :shuffle, :split, to: :records
+ :shuffle, :split, :index, to: :records
delegate :table_name, :quoted_table_name, :primary_key, :quoted_primary_key,
:connection, :columns_hash, to: :klass
diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb
index 6349701dba..ff43def901 100644
--- a/activerecord/lib/active_record/relation/finder_methods.rb
+++ b/activerecord/lib/active_record/relation/finder_methods.rb
@@ -103,7 +103,7 @@ module ActiveRecord
# Same as #take but raises ActiveRecord::RecordNotFound if no record
# is found. Note that #take! accepts no arguments.
def take!
- take or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql(@klass.arel_engine)}]")
+ take || raise_record_not_found_exception!
end
# Find the first record (or first N records if a parameter is supplied).
@@ -117,7 +117,7 @@ module ActiveRecord
#
def first(limit = nil)
if limit
- find_nth_with_limit_and_offset(0, limit, offset: offset_index)
+ find_nth_with_limit(0, limit)
else
find_nth 0
end
@@ -126,7 +126,7 @@ module ActiveRecord
# Same as #first but raises ActiveRecord::RecordNotFound if no record
# is found. Note that #first! accepts no arguments.
def first!
- find_nth! 0
+ first || raise_record_not_found_exception!
end
# Find the last record (or last N records if a parameter is supplied).
@@ -165,7 +165,7 @@ module ActiveRecord
# Same as #last but raises ActiveRecord::RecordNotFound if no record
# is found. Note that #last! accepts no arguments.
def last!
- last or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql(@klass.arel_engine)}]")
+ last || raise_record_not_found_exception!
end
# Find the second record.
@@ -181,7 +181,7 @@ module ActiveRecord
# Same as #second but raises ActiveRecord::RecordNotFound if no record
# is found.
def second!
- find_nth! 1
+ second || raise_record_not_found_exception!
end
# Find the third record.
@@ -197,7 +197,7 @@ module ActiveRecord
# Same as #third but raises ActiveRecord::RecordNotFound if no record
# is found.
def third!
- find_nth! 2
+ third || raise_record_not_found_exception!
end
# Find the fourth record.
@@ -213,7 +213,7 @@ module ActiveRecord
# Same as #fourth but raises ActiveRecord::RecordNotFound if no record
# is found.
def fourth!
- find_nth! 3
+ fourth || raise_record_not_found_exception!
end
# Find the fifth record.
@@ -229,7 +229,7 @@ module ActiveRecord
# Same as #fifth but raises ActiveRecord::RecordNotFound if no record
# is found.
def fifth!
- find_nth! 4
+ fifth || raise_record_not_found_exception!
end
# Find the forty-second record. Also known as accessing "the reddit".
@@ -245,7 +245,7 @@ module ActiveRecord
# Same as #forty_two but raises ActiveRecord::RecordNotFound if no record
# is found.
def forty_two!
- find_nth! 41
+ forty_two || raise_record_not_found_exception!
end
# Find the third-to-last record.
@@ -261,7 +261,7 @@ module ActiveRecord
# Same as #third_to_last but raises ActiveRecord::RecordNotFound if no record
# is found.
def third_to_last!
- find_nth_from_last 3 or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql(@klass.arel_engine)}]")
+ third_to_last || raise_record_not_found_exception!
end
# Find the second-to-last record.
@@ -277,7 +277,7 @@ module ActiveRecord
# Same as #second_to_last but raises ActiveRecord::RecordNotFound if no record
# is found.
def second_to_last!
- find_nth_from_last 2 or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql(@klass.arel_engine)}]")
+ second_to_last || raise_record_not_found_exception!
end
# Returns true if a record exists in the table that matches the +id+ or
@@ -345,18 +345,24 @@ module ActiveRecord
# of results obtained should be provided in the +result_size+ argument and
# the expected number of results should be provided in the +expected_size+
# argument.
- def raise_record_not_found_exception!(ids, result_size, expected_size) #:nodoc:
+ def raise_record_not_found_exception!(ids = nil, result_size = nil, expected_size = nil) # :nodoc:
conditions = arel.where_sql(@klass.arel_engine)
conditions = " [#{conditions}]" if conditions
-
- if Array(ids).size == 1
- error = "Couldn't find #{@klass.name} with '#{primary_key}'=#{ids}#{conditions}"
+ name = @klass.name
+
+ if ids.nil?
+ error = "Couldn't find #{name}"
+ error << " with#{conditions}" if conditions
+ raise RecordNotFound, error
+ elsif Array(ids).size == 1
+ error = "Couldn't find #{name} with '#{primary_key}'=#{ids}#{conditions}"
+ raise RecordNotFound.new(error, name, primary_key, ids)
else
- error = "Couldn't find all #{@klass.name.pluralize} with '#{primary_key}': "
+ error = "Couldn't find all #{name.pluralize} with '#{primary_key}': "
error << "(#{ids.join(", ")})#{conditions} (found #{result_size} results, but was looking for #{expected_size})"
- end
- raise RecordNotFound, error
+ raise RecordNotFound, error
+ end
end
private
@@ -426,7 +432,7 @@ module ActiveRecord
arel = relation.arel
id_rows = @klass.connection.select_all(arel, "SQL", relation.bound_attributes)
- id_rows.map {|row| row[primary_key]}
+ id_rows.map { |row| row[primary_key] }
end
def using_limitable_reflections?(reflections)
@@ -520,39 +526,23 @@ module ActiveRecord
end
end
- def find_nth(index, offset = nil)
- # TODO: once the offset argument is removed we rely on offset_index
- # within find_nth_with_limit, rather than pass it in via
- # find_nth_with_limit_and_offset
- if offset
- ActiveSupport::Deprecation.warn(<<-MSG.squish)
- Passing an offset argument to find_nth is deprecated,
- please use Relation#offset instead.
- MSG
- end
- if loaded?
- records[index]
- else
- offset ||= offset_index
- @offsets[offset + index] ||= find_nth_with_limit_and_offset(index, 1, offset: offset).first
- end
- end
-
- def find_nth!(index)
- find_nth(index) or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql(@klass.arel_engine)}]")
+ def find_nth(index)
+ @offsets[offset_index + index] ||= find_nth_with_limit(index, 1).first
end
def find_nth_with_limit(index, limit)
- # TODO: once the offset argument is removed from find_nth,
- # find_nth_with_limit_and_offset can be merged into this method
- relation = if order_values.empty? && primary_key
- order(arel_attribute(primary_key).asc)
- else
- self
- end
-
- relation = relation.offset(index) unless index.zero?
- relation.limit(limit).to_a
+ if loaded?
+ records[index, limit]
+ else
+ relation = if order_values.empty? && primary_key
+ order(arel_attribute(primary_key).asc)
+ else
+ self
+ end
+
+ relation = relation.offset(offset_index + index) unless index.zero?
+ relation.limit(limit).to_a
+ end
end
def find_nth_from_last(index)
@@ -561,9 +551,9 @@ module ActiveRecord
else
relation = if order_values.empty? && primary_key
order(arel_attribute(primary_key).asc)
- else
- self
- end
+ else
+ self
+ end
relation.to_a[-index]
# TODO: can be made more performant on large result sets by
@@ -576,15 +566,6 @@ module ActiveRecord
private
- def find_nth_with_limit_and_offset(index, limit, offset:) # :nodoc:
- if loaded?
- records[index, limit]
- else
- index += offset
- find_nth_with_limit(index, limit)
- end
- end
-
def find_last(limit)
limit ? records.last(limit) : records.last
end
diff --git a/activerecord/lib/active_record/relation/predicate_builder.rb b/activerecord/lib/active_record/relation/predicate_builder.rb
index df663a84ed..29422bf131 100644
--- a/activerecord/lib/active_record/relation/predicate_builder.rb
+++ b/activerecord/lib/active_record/relation/predicate_builder.rb
@@ -4,6 +4,7 @@ module ActiveRecord
require "active_record/relation/predicate_builder/association_query_handler"
require "active_record/relation/predicate_builder/base_handler"
require "active_record/relation/predicate_builder/basic_object_handler"
+ require "active_record/relation/predicate_builder/case_sensitive_handler"
require "active_record/relation/predicate_builder/class_handler"
require "active_record/relation/predicate_builder/polymorphic_array_handler"
require "active_record/relation/predicate_builder/range_handler"
@@ -16,6 +17,7 @@ module ActiveRecord
@handlers = []
register_handler(BasicObject, BasicObjectHandler.new)
+ register_handler(CaseSensitiveHandler::Value, CaseSensitiveHandler.new)
register_handler(Class, ClassHandler.new(self))
register_handler(Base, BaseHandler.new(self))
register_handler(Range, RangeHandler.new)
@@ -31,19 +33,9 @@ module ActiveRecord
expand_from_hash(attributes)
end
- def create_binds(attributes)
+ def create_binds(attributes, options)
attributes = convert_dot_notation_to_hash(attributes)
- create_binds_for_hash(attributes)
- end
-
- def expand(column, value)
- # Find the foreign key when using queries such as:
- # Post.where(author: author)
- #
- # For polymorphic relationships, find the foreign key and type:
- # PriceEstimate.where(estimate_of: treasure)
- value = AssociationQueryHandler.value_for(table, column, value) if table.associated_with?(column)
- build(table.arel_attribute(column), value)
+ create_binds_for_hash(attributes, options)
end
def self.references(attributes)
@@ -84,28 +76,28 @@ module ActiveRecord
return ["1=0"] if attributes.empty?
attributes.flat_map do |key, value|
- if value.is_a?(Hash)
+ if value.is_a?(Hash) && !table.has_column?(key)
associated_predicate_builder(key).expand_from_hash(value)
else
- expand(key, value)
+ build(table.arel_attribute(key), value)
end
end
end
-
- def create_binds_for_hash(attributes)
+ def create_binds_for_hash(attributes, options)
result = attributes.dup
binds = []
attributes.each do |column_name, value|
- case value
- when Hash
- attrs, bvs = associated_predicate_builder(column_name).create_binds_for_hash(value)
+ case
+ when value.is_a?(Hash) && !table.has_column?(column_name)
+ attrs, bvs = associated_predicate_builder(column_name).create_binds_for_hash(value, options)
result[column_name] = attrs
binds += bvs
- when Relation
+ next
+ when value.is_a?(Relation)
binds += value.bound_attributes
- when Range
+ when value.is_a?(Range) && !table.type(column_name).respond_to?(:subtype)
first = value.begin
last = value.end
unless first.respond_to?(:infinite?) && first.infinite?
@@ -118,11 +110,24 @@ module ActiveRecord
end
result[column_name] = RangeHandler::RangeWithBinds.new(first, last, value.exclude_end?)
- else
- if can_be_bound?(column_name, value)
- result[column_name] = Arel::Nodes::BindParam.new
- binds << build_bind_param(column_name, value)
- end
+ when can_be_bound?(column_name, value)
+ result[column_name] =
+ if perform_case_sensitive?(options)
+ CaseSensitiveHandler::Value.new(
+ Arel::Nodes::BindParam.new, table, options[:case_sensitive])
+ else
+ Arel::Nodes::BindParam.new
+ end
+ binds << build_bind_param(column_name, value)
+ end
+
+ # Find the foreign key when using queries such as:
+ # Post.where(author: author)
+ #
+ # For polymorphic relationships, find the foreign key and type:
+ # PriceEstimate.where(estimate_of: treasure)
+ if table.associated_with?(column_name)
+ result[column_name] = AssociationQueryHandler.value_for(table, column_name, value)
end
end
@@ -156,9 +161,17 @@ module ActiveRecord
end
def can_be_bound?(column_name, value)
- !value.nil? &&
- handler_for(value).is_a?(BasicObjectHandler) &&
- !table.associated_with?(column_name)
+ return if table.associated_with?(column_name)
+ case value
+ when Array, Range
+ table.type(column_name).respond_to?(:subtype)
+ else
+ !value.nil? && handler_for(value).is_a?(BasicObjectHandler)
+ end
+ end
+
+ def perform_case_sensitive?(options)
+ options.key?(:case_sensitive)
end
def build_bind_param(column_name, value)
diff --git a/activerecord/lib/active_record/relation/predicate_builder/case_sensitive_handler.rb b/activerecord/lib/active_record/relation/predicate_builder/case_sensitive_handler.rb
new file mode 100644
index 0000000000..acf0bbd829
--- /dev/null
+++ b/activerecord/lib/active_record/relation/predicate_builder/case_sensitive_handler.rb
@@ -0,0 +1,21 @@
+module ActiveRecord
+ class PredicateBuilder
+ class CaseSensitiveHandler # :nodoc:
+ def call(attribute, value)
+ value.call(attribute)
+ end
+
+ class Value < Struct.new(:value, :table, :case_sensitive?) # :nodoc:
+ def call(attribute)
+ klass = table.send(:klass)
+ column = klass.column_for_attribute(attribute.name)
+ if case_sensitive?
+ klass.connection.case_sensitive_comparison(attribute, column, value)
+ else
+ klass.connection.case_insensitive_comparison(attribute, column, value)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb
index 619b947f57..9a1ac207f2 100644
--- a/activerecord/lib/active_record/relation/query_methods.rb
+++ b/activerecord/lib/active_record/relation/query_methods.rb
@@ -1006,7 +1006,7 @@ module ActiveRecord
result = [] if multi_val_method
end
- self.send(unscope_code, result)
+ send(unscope_code, result)
end
def build_from
@@ -1137,9 +1137,9 @@ module ActiveRecord
def does_not_support_reverse?(order)
# Uses SQL function with multiple arguments.
- /\([^()]*,[^()]*\)/.match?(order) ||
- # Uses "nulls first" like construction.
- /nulls (first|last)\Z/i.match?(order)
+ (order.include?(",") && order.split(",").find { |section| section.count("(") != section.count(")") }) ||
+ # Uses "nulls first" like construction.
+ /nulls (first|last)\Z/i.match?(order)
end
def build_order(arel)
diff --git a/activerecord/lib/active_record/relation/where_clause_factory.rb b/activerecord/lib/active_record/relation/where_clause_factory.rb
index dc00149130..122ab04c00 100644
--- a/activerecord/lib/active_record/relation/where_clause_factory.rb
+++ b/activerecord/lib/active_record/relation/where_clause_factory.rb
@@ -17,7 +17,7 @@ module ActiveRecord
attributes = klass.send(:expand_hash_conditions_for_aggregates, attributes)
attributes.stringify_keys!
- attributes, binds = predicate_builder.create_binds(attributes)
+ attributes, binds = predicate_builder.create_binds(attributes, other.last || {})
parts = predicate_builder.build_from_hash(attributes)
when Arel::Nodes::Node
diff --git a/activerecord/lib/active_record/sanitization.rb b/activerecord/lib/active_record/sanitization.rb
index 6617008344..c40e98715e 100644
--- a/activerecord/lib/active_record/sanitization.rb
+++ b/activerecord/lib/active_record/sanitization.rb
@@ -5,13 +5,6 @@ module ActiveRecord
extend ActiveSupport::Concern
module ClassMethods
- # Used to sanitize objects before they're used in an SQL SELECT statement.
- # Delegates to {connection.quote}[rdoc-ref:ConnectionAdapters::Quoting#quote].
- def sanitize(object) # :nodoc:
- connection.quote(object)
- end
- alias_method :quote_value, :sanitize
-
protected
# Accepts an array or string of SQL conditions and sanitizes
@@ -216,7 +209,7 @@ module ActiveRecord
# TODO: Deprecate this
def quoted_id # :nodoc:
- self.class.quote_value(@attributes[self.class.primary_key].value_for_database)
+ self.class.connection.quote(@attributes[self.class.primary_key].value_for_database)
end
end
end
diff --git a/activerecord/lib/active_record/schema_dumper.rb b/activerecord/lib/active_record/schema_dumper.rb
index 5105088b2f..01f788a424 100644
--- a/activerecord/lib/active_record/schema_dumper.rb
+++ b/activerecord/lib/active_record/schema_dumper.rb
@@ -153,10 +153,10 @@ HEADER
}
# the string we're going to sprintf our values against, with standardized column widths
- format_string = lengths.map{ |len| "%-#{len}s" }
+ format_string = lengths.map { |len| "%-#{len}s" }
# find the max length for the 'type' column, which is special
- type_length = column_specs.map{ |column| column[:type].length }.max
+ type_length = column_specs.map { |column| column[:type].length }.max
# add column type definition to our format string
format_string.unshift " t.%-#{type_length}s "
@@ -164,7 +164,7 @@ HEADER
format_string *= ""
column_specs.each do |colspec|
- values = keys.zip(lengths).map{ |key, len| colspec.key?(key) ? colspec[key] + ", " : " " * len }
+ values = keys.zip(lengths).map { |key, len| colspec.key?(key) ? colspec[key] + ", " : " " * len }
values.unshift colspec[:type]
tbl.print((format_string % values).gsub(/,\s*$/, ""))
tbl.puts
diff --git a/activerecord/lib/active_record/scoping/default.rb b/activerecord/lib/active_record/scoping/default.rb
index 572a45aac9..7409706851 100644
--- a/activerecord/lib/active_record/scoping/default.rb
+++ b/activerecord/lib/active_record/scoping/default.rb
@@ -104,11 +104,11 @@ module ActiveRecord
def build_default_scope(base_rel = nil) # :nodoc:
return if abstract_class?
- if self.default_scope_override.nil?
+ if default_scope_override.nil?
self.default_scope_override = !Base.is_a?(method(:default_scope).owner)
end
- if self.default_scope_override
+ if default_scope_override
# The user has defined their own default scope method, so call that
evaluate_default_scope { default_scope }
elsif default_scopes.any?
diff --git a/activerecord/lib/active_record/scoping/named.rb b/activerecord/lib/active_record/scoping/named.rb
index 46ee3540bd..094c0e9c6f 100644
--- a/activerecord/lib/active_record/scoping/named.rb
+++ b/activerecord/lib/active_record/scoping/named.rb
@@ -174,7 +174,7 @@ module ActiveRecord
protected
def valid_scope_name?(name)
- if respond_to?(name, true)
+ if respond_to?(name, true) && logger
logger.warn "Creating scope :#{name}. " \
"Overwriting existing method #{self.name}.#{name}."
end
diff --git a/activerecord/lib/active_record/secure_token.rb b/activerecord/lib/active_record/secure_token.rb
index 2c412a45ed..7606961e2e 100644
--- a/activerecord/lib/active_record/secure_token.rb
+++ b/activerecord/lib/active_record/secure_token.rb
@@ -27,7 +27,7 @@ module ActiveRecord
# Load securerandom only when has_secure_token is used.
require "active_support/core_ext/securerandom"
define_method("regenerate_#{attribute}") { update! attribute => self.class.generate_unique_secure_token }
- before_create { self.send("#{attribute}=", self.class.generate_unique_secure_token) unless self.send("#{attribute}?")}
+ before_create { self.send("#{attribute}=", self.class.generate_unique_secure_token) unless self.send("#{attribute}?") }
end
def generate_unique_secure_token
diff --git a/activerecord/lib/active_record/store.rb b/activerecord/lib/active_record/store.rb
index f6bf2c7e48..066573192e 100644
--- a/activerecord/lib/active_record/store.rb
+++ b/activerecord/lib/active_record/store.rb
@@ -114,8 +114,8 @@ module ActiveRecord
def stored_attributes
parent = superclass.respond_to?(:stored_attributes) ? superclass.stored_attributes : {}
- if self.local_stored_attributes
- parent.merge!(self.local_stored_attributes) { |k, a, b| a | b }
+ if local_stored_attributes
+ parent.merge!(local_stored_attributes) { |k, a, b| a | b }
end
parent
end
diff --git a/activerecord/lib/active_record/table_metadata.rb b/activerecord/lib/active_record/table_metadata.rb
index e8d6a144f9..0ca880e635 100644
--- a/activerecord/lib/active_record/table_metadata.rb
+++ b/activerecord/lib/active_record/table_metadata.rb
@@ -37,6 +37,10 @@ module ActiveRecord
end
end
+ def has_column?(column_name)
+ klass && klass.columns_hash.key?(column_name.to_s)
+ end
+
def associated_with?(association_name)
klass && klass._reflect_on_association(association_name)
end
diff --git a/activerecord/lib/active_record/tasks/database_tasks.rb b/activerecord/lib/active_record/tasks/database_tasks.rb
index c0764fc4ab..a19913f2a8 100644
--- a/activerecord/lib/active_record/tasks/database_tasks.rb
+++ b/activerecord/lib/active_record/tasks/database_tasks.rb
@@ -78,9 +78,9 @@ module ActiveRecord
def fixtures_path
@fixtures_path ||= if ENV["FIXTURES_PATH"]
File.join(root, ENV["FIXTURES_PATH"])
- else
- File.join(root, "test", "fixtures")
- end
+ else
+ File.join(root, "test", "fixtures")
+ end
end
def root
diff --git a/activerecord/lib/active_record/timestamp.rb b/activerecord/lib/active_record/timestamp.rb
index d9c18a5e38..6641ab5df1 100644
--- a/activerecord/lib/active_record/timestamp.rb
+++ b/activerecord/lib/active_record/timestamp.rb
@@ -54,7 +54,7 @@ module ActiveRecord
private
def _create_record
- if self.record_timestamps
+ if record_timestamps
current_time = current_time_from_proper_timezone
all_timestamp_attributes.each do |column|
@@ -82,7 +82,7 @@ module ActiveRecord
end
def should_record_timestamps?
- self.record_timestamps && (!partial_writes? || changed?)
+ record_timestamps && (!partial_writes? || changed?)
end
def timestamp_attributes_for_create_in_model
diff --git a/activerecord/lib/active_record/validations/uniqueness.rb b/activerecord/lib/active_record/validations/uniqueness.rb
index 8c4930a81d..08c4b01439 100644
--- a/activerecord/lib/active_record/validations/uniqueness.rb
+++ b/activerecord/lib/active_record/validations/uniqueness.rb
@@ -50,37 +50,7 @@ module ActiveRecord
end
def build_relation(klass, attribute, value) # :nodoc:
- if reflection = klass._reflect_on_association(attribute)
- attribute = reflection.foreign_key
- value = value.attributes[reflection.klass.primary_key] unless value.nil?
- end
-
- if value.nil?
- return klass.unscoped.where!(attribute => value)
- end
-
- # the attribute may be an aliased attribute
- if klass.attribute_alias?(attribute)
- attribute = klass.attribute_alias(attribute)
- end
-
- attribute_name = attribute.to_s
-
- table = klass.arel_table
- column = klass.columns_hash[attribute_name]
- cast_type = klass.type_for_attribute(attribute_name)
-
- comparison = if !options[:case_sensitive]
- # will use SQL LOWER function before comparison, unless it detects a case insensitive collation
- klass.connection.case_insensitive_comparison(table, attribute, column, value)
- else
- klass.connection.case_sensitive_comparison(table, attribute, column, value)
- end
- klass.unscoped.tap do |scope|
- parts = [comparison]
- binds = [Relation::QueryAttribute.new(attribute_name, value, cast_type)]
- scope.where_clause += Relation::WhereClause.new(parts, binds)
- end
+ klass.unscoped.where!({ attribute => value }, options)
end
def scope_relation(record, relation)
diff --git a/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb b/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb
index 76182a3c24..bc9037c476 100644
--- a/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb
+++ b/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb
@@ -41,7 +41,7 @@ module ActiveRecord
def set_index_names
attributes.each_with_index do |attr, i|
- attr.index_name = [attr, attributes[i - 1]].map{ |a| index_name_for(a) }
+ attr.index_name = [attr, attributes[i - 1]].map { |a| index_name_for(a) }
end
end
diff --git a/activerecord/test/cases/adapter_test.rb b/activerecord/test/cases/adapter_test.rb
index b164c12c89..a72981e4d5 100644
--- a/activerecord/test/cases/adapter_test.rb
+++ b/activerecord/test/cases/adapter_test.rb
@@ -248,8 +248,8 @@ module ActiveRecord
author = Author.create!(name: "john")
Post.create!(author: author, title: "foo", body: "bar")
query = author.posts.where(title: "foo").select(:title)
- assert_equal({"title" => "foo"}, @connection.select_one(query.arel, nil, query.bound_attributes))
- assert_equal({"title" => "foo"}, @connection.select_one(query))
+ assert_equal({ "title" => "foo" }, @connection.select_one(query.arel, nil, query.bound_attributes))
+ assert_equal({ "title" => "foo" }, @connection.select_one(query))
assert @connection.select_all(query).is_a?(ActiveRecord::Result)
assert_equal "foo", @connection.select_value(query)
assert_equal ["foo"], @connection.select_values(query)
@@ -258,8 +258,8 @@ module ActiveRecord
def test_select_methods_passing_a_relation
Post.create!(title: "foo", body: "bar")
query = Post.where(title: "foo").select(:title)
- assert_equal({"title" => "foo"}, @connection.select_one(query.arel, nil, query.bound_attributes))
- assert_equal({"title" => "foo"}, @connection.select_one(query))
+ assert_equal({ "title" => "foo" }, @connection.select_one(query.arel, nil, query.bound_attributes))
+ assert_equal({ "title" => "foo" }, @connection.select_one(query))
assert @connection.select_all(query).is_a?(ActiveRecord::Result)
assert_equal "foo", @connection.select_value(query)
assert_equal ["foo"], @connection.select_values(query)
diff --git a/activerecord/test/cases/adapters/mysql2/active_schema_test.rb b/activerecord/test/cases/adapters/mysql2/active_schema_test.rb
index e7e37cac36..a70eb5a094 100644
--- a/activerecord/test/cases/adapters/mysql2/active_schema_test.rb
+++ b/activerecord/test/cases/adapters/mysql2/active_schema_test.rb
@@ -30,10 +30,10 @@ class Mysql2ActiveSchemaTest < ActiveRecord::Mysql2TestCase
assert_equal expected, add_index(:people, [:last_name, :first_name], length: 15)
expected = "CREATE INDEX `index_people_on_last_name_and_first_name` ON `people` (`last_name`(15), `first_name`) "
- assert_equal expected, add_index(:people, [:last_name, :first_name], length: {last_name: 15})
+ assert_equal expected, add_index(:people, [:last_name, :first_name], length: { last_name: 15 })
expected = "CREATE INDEX `index_people_on_last_name_and_first_name` ON `people` (`last_name`(15), `first_name`(10)) "
- assert_equal expected, add_index(:people, [:last_name, :first_name], length: {last_name: 15, first_name: 10})
+ assert_equal expected, add_index(:people, [:last_name, :first_name], length: { last_name: 15, first_name: 10 })
%w(SPATIAL FULLTEXT UNIQUE).each do |type|
expected = "CREATE #{type} INDEX `index_people_on_last_name` ON `people` (`last_name`) "
diff --git a/activerecord/test/cases/adapters/mysql2/case_sensitivity_test.rb b/activerecord/test/cases/adapters/mysql2/case_sensitivity_test.rb
index 4d81877a9a..50ba9ab831 100644
--- a/activerecord/test/cases/adapters/mysql2/case_sensitivity_test.rb
+++ b/activerecord/test/cases/adapters/mysql2/case_sensitivity_test.rb
@@ -30,7 +30,7 @@ class Mysql2CaseSensitivityTest < ActiveRecord::Mysql2TestCase
CollationTest.create!(string_cs_column: "A")
invalid = CollationTest.new(string_cs_column: "a")
queries = assert_sql { invalid.save }
- cs_uniqueness_query = queries.detect { |q| q.match(/string_cs_column/)}
+ cs_uniqueness_query = queries.detect { |q| q.match(/string_cs_column/) }
assert_match(/lower/i, cs_uniqueness_query)
end
diff --git a/activerecord/test/cases/adapters/mysql2/connection_test.rb b/activerecord/test/cases/adapters/mysql2/connection_test.rb
index a3f83e73a6..9ede57d395 100644
--- a/activerecord/test/cases/adapters/mysql2/connection_test.rb
+++ b/activerecord/test/cases/adapters/mysql2/connection_test.rb
@@ -114,7 +114,7 @@ class Mysql2ConnectionTest < ActiveRecord::Mysql2TestCase
def test_mysql_set_session_variable
run_without_connection do |orig_connection|
- ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: {default_week_format: 3}))
+ ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { default_week_format: 3 }))
session_mode = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.DEFAULT_WEEK_FORMAT"
assert_equal 3, session_mode.rows.first.first.to_i
end
@@ -122,7 +122,7 @@ class Mysql2ConnectionTest < ActiveRecord::Mysql2TestCase
def test_mysql_set_session_variable_to_default
run_without_connection do |orig_connection|
- ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: {default_week_format: :default}))
+ ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { default_week_format: :default }))
global_mode = ActiveRecord::Base.connection.exec_query "SELECT @@GLOBAL.DEFAULT_WEEK_FORMAT"
session_mode = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.DEFAULT_WEEK_FORMAT"
assert_equal global_mode.rows, session_mode.rows
diff --git a/activerecord/test/cases/adapters/mysql2/json_test.rb b/activerecord/test/cases/adapters/mysql2/json_test.rb
index 2f7dc3f7ef..6b7d259023 100644
--- a/activerecord/test/cases/adapters/mysql2/json_test.rb
+++ b/activerecord/test/cases/adapters/mysql2/json_test.rb
@@ -51,11 +51,11 @@ if ActiveRecord::Base.connection.supports_json?
end
def test_cast_value_on_write
- x = JsonDataType.new payload: {"string" => "foo", :symbol => :bar}
- assert_equal({"string" => "foo", :symbol => :bar}, x.payload_before_type_cast)
- assert_equal({"string" => "foo", "symbol" => "bar"}, x.payload)
+ x = JsonDataType.new payload: { "string" => "foo", :symbol => :bar }
+ assert_equal({ "string" => "foo", :symbol => :bar }, x.payload_before_type_cast)
+ assert_equal({ "string" => "foo", "symbol" => "bar" }, x.payload)
x.save
- assert_equal({"string" => "foo", "symbol" => "bar"}, x.reload.payload)
+ assert_equal({ "string" => "foo", "symbol" => "bar" }, x.reload.payload)
end
def test_type_cast_json
@@ -63,12 +63,12 @@ if ActiveRecord::Base.connection.supports_json?
data = "{\"a_key\":\"a_value\"}"
hash = type.deserialize(data)
- assert_equal({"a_key" => "a_value"}, hash)
- assert_equal({"a_key" => "a_value"}, type.deserialize(data))
+ assert_equal({ "a_key" => "a_value" }, hash)
+ assert_equal({ "a_key" => "a_value" }, type.deserialize(data))
assert_equal({}, type.deserialize("{}"))
- assert_equal({"key"=>nil}, type.deserialize('{"key": null}'))
- assert_equal({"c"=>"}",'"a"'=>'b "a b'}, type.deserialize(%q({"c":"}", "\"a\"":"b \"a b"})))
+ assert_equal({ "key"=>nil }, type.deserialize('{"key": null}'))
+ assert_equal({ "c"=>"}",'"a"'=>'b "a b' }, type.deserialize(%q({"c":"}", "\"a\"":"b \"a b"})))
end
def test_rewrite
@@ -81,13 +81,13 @@ if ActiveRecord::Base.connection.supports_json?
def test_select
@connection.execute "insert into json_data_type (payload) VALUES ('{\"k\":\"v\"}')"
x = JsonDataType.first
- assert_equal({"k" => "v"}, x.payload)
+ assert_equal({ "k" => "v" }, x.payload)
end
def test_select_multikey
@connection.execute %q|insert into json_data_type (payload) VALUES ('{"k1":"v1", "k2":"v2", "k3":[1,2,3]}')|
x = JsonDataType.first
- assert_equal({"k1" => "v1", "k2" => "v2", "k3" => [1,2,3]}, x.payload)
+ assert_equal({ "k1" => "v1", "k2" => "v2", "k3" => [1,2,3] }, x.payload)
end
def test_null_json
@@ -99,13 +99,13 @@ if ActiveRecord::Base.connection.supports_json?
def test_select_array_json_value
@connection.execute %q|insert into json_data_type (payload) VALUES ('["v0",{"k1":"v1"}]')|
x = JsonDataType.first
- assert_equal(["v0", {"k1" => "v1"}], x.payload)
+ assert_equal(["v0", { "k1" => "v1" }], x.payload)
end
def test_rewrite_array_json_value
@connection.execute %q|insert into json_data_type (payload) VALUES ('["v0",{"k1":"v1"}]')|
x = JsonDataType.first
- x.payload = ["v1", {"k2" => "v2"}, "v3"]
+ x.payload = ["v1", { "k2" => "v2" }, "v3"]
assert x.save!
end
diff --git a/activerecord/test/cases/adapters/mysql2/schema_test.rb b/activerecord/test/cases/adapters/mysql2/schema_test.rb
index 3c08a4ed1f..aea930cfe6 100644
--- a/activerecord/test/cases/adapters/mysql2/schema_test.rb
+++ b/activerecord/test/cases/adapters/mysql2/schema_test.rb
@@ -78,9 +78,9 @@ module ActiveRecord
indexes = @connection.indexes(table).sort_by(&:name)
assert_equal 3,indexes.size
- index_a = indexes.select{|i| i.name == index_a_name}[0]
- index_b = indexes.select{|i| i.name == index_b_name}[0]
- index_c = indexes.select{|i| i.name == index_c_name}[0]
+ index_a = indexes.select { |i| i.name == index_a_name }[0]
+ index_b = indexes.select { |i| i.name == index_b_name }[0]
+ index_c = indexes.select { |i| i.name == index_c_name }[0]
assert_equal :btree, index_a.using
assert_nil index_a.type
assert_equal :btree, index_b.using
@@ -121,6 +121,6 @@ class Mysql2AnsiQuotesTest < ActiveRecord::Mysql2TestCase
def test_foreign_keys_method_with_ansi_quotes
fks = @connection.foreign_keys("lessons_students")
assert_equal([["lessons_students", "students", :cascade]],
- fks.map {|fk| [fk.from_table, fk.to_table, fk.on_delete] })
+ fks.map { |fk| [fk.from_table, fk.to_table, fk.on_delete] })
end
end
diff --git a/activerecord/test/cases/adapters/postgresql/active_schema_test.rb b/activerecord/test/cases/adapters/postgresql/active_schema_test.rb
index a4a06a2da4..d3c65f3d94 100644
--- a/activerecord/test/cases/adapters/postgresql/active_schema_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/active_schema_test.rb
@@ -81,6 +81,12 @@ class PostgresqlActiveSchemaTest < ActiveRecord::PostgreSQLTestCase
assert_equal expected, remove_index(:people, name: "index_people_on_last_name", algorithm: :concurrently)
end
+ def test_remove_index_with_wrong_option
+ assert_raises ArgumentError do
+ remove_index(:people, coulmn: :last_name)
+ end
+ end
+
private
def method_missing(method_symbol, *arguments)
ActiveRecord::Base.connection.send(method_symbol, *arguments)
diff --git a/activerecord/test/cases/adapters/postgresql/array_test.rb b/activerecord/test/cases/adapters/postgresql/array_test.rb
index e496960f21..60da9d8859 100644
--- a/activerecord/test/cases/adapters/postgresql/array_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/array_test.rb
@@ -184,7 +184,7 @@ class PostgresqlArrayTest < ActiveRecord::PostgreSQLTestCase
def test_insert_fixture
tag_values = ["val1", "val2", "val3_with_'_multiple_quote_'_chars"]
- @connection.insert_fixture({"tags" => tag_values}, "pg_arrays" )
+ @connection.insert_fixture({ "tags" => tag_values }, "pg_arrays" )
assert_equal(PgArray.last.tags, tag_values)
end
@@ -290,6 +290,12 @@ class PostgresqlArrayTest < ActiveRecord::PostgreSQLTestCase
assert_equal record.tags, record.reload.tags
end
+ def test_where_by_attribute_with_array
+ tags = ["black", "blue"]
+ record = PgArray.create!(tags: tags)
+ assert_equal record, PgArray.where(tags: tags).take
+ end
+
def test_uniqueness_validation
klass = Class.new(PgArray) do
validates_uniqueness_of :tags
diff --git a/activerecord/test/cases/adapters/postgresql/connection_test.rb b/activerecord/test/cases/adapters/postgresql/connection_test.rb
index d01f601031..48c82cb7b9 100644
--- a/activerecord/test/cases/adapters/postgresql/connection_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/connection_test.rb
@@ -184,7 +184,7 @@ module ActiveRecord
def test_set_session_variable_true
run_without_connection do |orig_connection|
- ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: {debug_print_plan: true}))
+ ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { debug_print_plan: true }))
set_true = ActiveRecord::Base.connection.exec_query "SHOW DEBUG_PRINT_PLAN"
assert_equal set_true.rows, [["on"]]
end
@@ -192,7 +192,7 @@ module ActiveRecord
def test_set_session_variable_false
run_without_connection do |orig_connection|
- ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: {debug_print_plan: false}))
+ ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { debug_print_plan: false }))
set_false = ActiveRecord::Base.connection.exec_query "SHOW DEBUG_PRINT_PLAN"
assert_equal set_false.rows, [["off"]]
end
@@ -201,14 +201,14 @@ module ActiveRecord
def test_set_session_variable_nil
run_without_connection do |orig_connection|
# This should be a no-op that does not raise an error
- ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: {debug_print_plan: nil}))
+ ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { debug_print_plan: nil }))
end
end
def test_set_session_variable_default
run_without_connection do |orig_connection|
# This should execute a query that does not raise an error
- ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: {debug_print_plan: :default}))
+ ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { debug_print_plan: :default }))
end
end
@@ -224,14 +224,14 @@ module ActiveRecord
got_lock = @connection.get_advisory_lock(lock_id)
assert got_lock, "get_advisory_lock should have returned true but it didn't"
- advisory_lock = @connection.query(list_advisory_locks).find {|l| l[1] == lock_id}
+ advisory_lock = @connection.query(list_advisory_locks).find { |l| l[1] == lock_id }
assert advisory_lock,
"expected to find an advisory lock with lock_id #{lock_id} but there wasn't one"
released_lock = @connection.release_advisory_lock(lock_id)
assert released_lock, "expected release_advisory_lock to return true but it didn't"
- advisory_locks = @connection.query(list_advisory_locks).select {|l| l[1] == lock_id}
+ advisory_locks = @connection.query(list_advisory_locks).select { |l| l[1] == lock_id }
assert_empty advisory_locks,
"expected to have released advisory lock with lock_id #{lock_id} but it was still held"
end
diff --git a/activerecord/test/cases/adapters/postgresql/datatype_test.rb b/activerecord/test/cases/adapters/postgresql/datatype_test.rb
index aa077b59a0..0ac8b7339b 100644
--- a/activerecord/test/cases/adapters/postgresql/datatype_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/datatype_test.rb
@@ -1,7 +1,6 @@
require "cases/helper"
require "support/ddl_helper"
-
class PostgresqlTime < ActiveRecord::Base
end
diff --git a/activerecord/test/cases/adapters/postgresql/hstore_test.rb b/activerecord/test/cases/adapters/postgresql/hstore_test.rb
index 817dfbf705..3a8fcf388a 100644
--- a/activerecord/test/cases/adapters/postgresql/hstore_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/hstore_test.rb
@@ -64,8 +64,8 @@ if ActiveRecord::Base.connection.supports_extensions?
@connection.add_column "hstores", "permissions", :hstore, default: '"users"=>"read", "articles"=>"write"'
Hstore.reset_column_information
- assert_equal({"users"=>"read", "articles"=>"write"}, Hstore.column_defaults["permissions"])
- assert_equal({"users"=>"read", "articles"=>"write"}, Hstore.new.permissions)
+ assert_equal({ "users"=>"read", "articles"=>"write" }, Hstore.column_defaults["permissions"])
+ assert_equal({ "users"=>"read", "articles"=>"write" }, Hstore.new.permissions)
ensure
Hstore.reset_column_information
end
@@ -103,18 +103,18 @@ if ActiveRecord::Base.connection.supports_extensions?
end
def test_cast_value_on_write
- x = Hstore.new tags: {"bool" => true, "number" => 5}
- assert_equal({"bool" => true, "number" => 5}, x.tags_before_type_cast)
- assert_equal({"bool" => "true", "number" => "5"}, x.tags)
+ x = Hstore.new tags: { "bool" => true, "number" => 5 }
+ assert_equal({ "bool" => true, "number" => 5 }, x.tags_before_type_cast)
+ assert_equal({ "bool" => "true", "number" => "5" }, x.tags)
x.save
- assert_equal({"bool" => "true", "number" => "5"}, x.reload.tags)
+ assert_equal({ "bool" => "true", "number" => "5" }, x.reload.tags)
end
def test_type_cast_hstore
- assert_equal({"1" => "2"}, @type.deserialize("\"1\"=>\"2\""))
+ assert_equal({ "1" => "2" }, @type.deserialize("\"1\"=>\"2\""))
assert_equal({}, @type.deserialize(""))
- assert_equal({"key"=>nil}, @type.deserialize("key => NULL"))
- assert_equal({"c"=>"}",'"a"'=>'b "a b'}, @type.deserialize(%q(c=>"}", "\"a\""=>"b \"a b")))
+ assert_equal({ "key"=>nil }, @type.deserialize("key => NULL"))
+ assert_equal({ "c"=>"}",'"a"'=>'b "a b' }, @type.deserialize(%q(c=>"}", "\"a\""=>"b \"a b")))
end
def test_with_store_accessors
@@ -182,31 +182,31 @@ if ActiveRecord::Base.connection.supports_extensions?
end
def test_parse1
- assert_equal({"a"=>nil,"b"=>nil,"c"=>"NuLl","null"=>"c"}, @type.deserialize('a=>null,b=>NuLl,c=>"NuLl",null=>c'))
+ assert_equal({ "a"=>nil,"b"=>nil,"c"=>"NuLl","null"=>"c" }, @type.deserialize('a=>null,b=>NuLl,c=>"NuLl",null=>c'))
end
def test_parse2
- assert_equal({" " => " "}, @type.deserialize("\\ =>\\ "))
+ assert_equal({ " " => " " }, @type.deserialize("\\ =>\\ "))
end
def test_parse3
- assert_equal({"=" => ">"}, @type.deserialize("==>>"))
+ assert_equal({ "=" => ">" }, @type.deserialize("==>>"))
end
def test_parse4
- assert_equal({"=a"=>"q=w"}, @type.deserialize('\=a=>q=w'))
+ assert_equal({ "=a"=>"q=w" }, @type.deserialize('\=a=>q=w'))
end
def test_parse5
- assert_equal({"=a"=>"q=w"}, @type.deserialize('"=a"=>q\=w'))
+ assert_equal({ "=a"=>"q=w" }, @type.deserialize('"=a"=>q\=w'))
end
def test_parse6
- assert_equal({"\"a"=>"q>w"}, @type.deserialize('"\"a"=>q>w'))
+ assert_equal({ "\"a"=>"q>w" }, @type.deserialize('"\"a"=>q>w'))
end
def test_parse7
- assert_equal({"\"a"=>"q\"w"}, @type.deserialize('\"a=>q"w'))
+ assert_equal({ "\"a"=>"q\"w" }, @type.deserialize('\"a=>q"w'))
end
def test_rewrite
@@ -219,19 +219,19 @@ if ActiveRecord::Base.connection.supports_extensions?
def test_select
@connection.execute "insert into hstores (tags) VALUES ('1=>2')"
x = Hstore.first
- assert_equal({"1" => "2"}, x.tags)
+ assert_equal({ "1" => "2" }, x.tags)
end
def test_array_cycle
- assert_array_cycle([{"AA" => "BB", "CC" => "DD"}, {"AA" => nil}])
+ assert_array_cycle([{ "AA" => "BB", "CC" => "DD" }, { "AA" => nil }])
end
def test_array_strings_with_quotes
- assert_array_cycle([{"this has" => 'some "s that need to be escaped"'}])
+ assert_array_cycle([{ "this has" => 'some "s that need to be escaped"' }])
end
def test_array_strings_with_commas
- assert_array_cycle([{"this,has" => "many,values"}])
+ assert_array_cycle([{ "this,has" => "many,values" }])
end
def test_array_strings_with_array_delimiters
@@ -239,17 +239,17 @@ if ActiveRecord::Base.connection.supports_extensions?
end
def test_array_strings_with_null_strings
- assert_array_cycle([{"NULL" => "NULL"}])
+ assert_array_cycle([{ "NULL" => "NULL" }])
end
def test_contains_nils
- assert_array_cycle([{"NULL" => nil}])
+ assert_array_cycle([{ "NULL" => nil }])
end
def test_select_multikey
@connection.execute "insert into hstores (tags) VALUES ('1=>2,2=>3')"
x = Hstore.first
- assert_equal({"1" => "2", "2" => "3"}, x.tags)
+ assert_equal({ "1" => "2", "2" => "3" }, x.tags)
end
def test_create
@@ -303,17 +303,17 @@ if ActiveRecord::Base.connection.supports_extensions?
HstoreWithSerialize.create! tags: TagCollection.new("one" => "two")
record = HstoreWithSerialize.first
assert_instance_of TagCollection, record.tags
- assert_equal({"one" => "two"}, record.tags.to_hash)
+ assert_equal({ "one" => "two" }, record.tags.to_hash)
record.tags = TagCollection.new("three" => "four")
record.save!
- assert_equal({"three" => "four"}, HstoreWithSerialize.first.tags.to_hash)
+ assert_equal({ "three" => "four" }, HstoreWithSerialize.first.tags.to_hash)
end
def test_clone_hstore_with_serialized_attributes
HstoreWithSerialize.create! tags: TagCollection.new("one" => "two")
record = HstoreWithSerialize.first
dupe = record.dup
- assert_equal({"one" => "two"}, dupe.tags.to_hash)
+ assert_equal({ "one" => "two" }, dupe.tags.to_hash)
end
def test_schema_dump_with_shorthand
diff --git a/activerecord/test/cases/adapters/postgresql/json_test.rb b/activerecord/test/cases/adapters/postgresql/json_test.rb
index d0e206ae80..c74f70f251 100644
--- a/activerecord/test/cases/adapters/postgresql/json_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/json_test.rb
@@ -38,11 +38,11 @@ module PostgresqlJSONSharedTestCases
end
def test_default
- @connection.add_column "json_data_type", "permissions", column_type, default: {"users": "read", "posts": ["read", "write"]}
+ @connection.add_column "json_data_type", "permissions", column_type, default: { "users": "read", "posts": ["read", "write"] }
JsonDataType.reset_column_information
- assert_equal({"users"=>"read", "posts"=>["read", "write"]}, JsonDataType.column_defaults["permissions"])
- assert_equal({"users"=>"read", "posts"=>["read", "write"]}, JsonDataType.new.permissions)
+ assert_equal({ "users"=>"read", "posts"=>["read", "write"] }, JsonDataType.column_defaults["permissions"])
+ assert_equal({ "users"=>"read", "posts"=>["read", "write"] }, JsonDataType.new.permissions)
ensure
JsonDataType.reset_column_information
end
@@ -68,11 +68,11 @@ module PostgresqlJSONSharedTestCases
end
def test_cast_value_on_write
- x = JsonDataType.new payload: {"string" => "foo", :symbol => :bar}
- assert_equal({"string" => "foo", :symbol => :bar}, x.payload_before_type_cast)
- assert_equal({"string" => "foo", "symbol" => "bar"}, x.payload)
+ x = JsonDataType.new payload: { "string" => "foo", :symbol => :bar }
+ assert_equal({ "string" => "foo", :symbol => :bar }, x.payload_before_type_cast)
+ assert_equal({ "string" => "foo", "symbol" => "bar" }, x.payload)
x.save
- assert_equal({"string" => "foo", "symbol" => "bar"}, x.reload.payload)
+ assert_equal({ "string" => "foo", "symbol" => "bar" }, x.reload.payload)
end
def test_type_cast_json
@@ -80,12 +80,12 @@ module PostgresqlJSONSharedTestCases
data = "{\"a_key\":\"a_value\"}"
hash = type.deserialize(data)
- assert_equal({"a_key" => "a_value"}, hash)
- assert_equal({"a_key" => "a_value"}, type.deserialize(data))
+ assert_equal({ "a_key" => "a_value" }, hash)
+ assert_equal({ "a_key" => "a_value" }, type.deserialize(data))
assert_equal({}, type.deserialize("{}"))
- assert_equal({"key"=>nil}, type.deserialize('{"key": null}'))
- assert_equal({"c"=>"}",'"a"'=>'b "a b'}, type.deserialize(%q({"c":"}", "\"a\"":"b \"a b"})))
+ assert_equal({ "key"=>nil }, type.deserialize('{"key": null}'))
+ assert_equal({ "c"=>"}",'"a"'=>'b "a b' }, type.deserialize(%q({"c":"}", "\"a\"":"b \"a b"})))
end
def test_rewrite
@@ -98,13 +98,13 @@ module PostgresqlJSONSharedTestCases
def test_select
@connection.execute "insert into json_data_type (payload) VALUES ('{\"k\":\"v\"}')"
x = JsonDataType.first
- assert_equal({"k" => "v"}, x.payload)
+ assert_equal({ "k" => "v" }, x.payload)
end
def test_select_multikey
@connection.execute %q|insert into json_data_type (payload) VALUES ('{"k1":"v1", "k2":"v2", "k3":[1,2,3]}')|
x = JsonDataType.first
- assert_equal({"k1" => "v1", "k2" => "v2", "k3" => [1,2,3]}, x.payload)
+ assert_equal({ "k1" => "v1", "k2" => "v2", "k3" => [1,2,3] }, x.payload)
end
def test_null_json
@@ -116,13 +116,13 @@ module PostgresqlJSONSharedTestCases
def test_select_array_json_value
@connection.execute %q|insert into json_data_type (payload) VALUES ('["v0",{"k1":"v1"}]')|
x = JsonDataType.first
- assert_equal(["v0", {"k1" => "v1"}], x.payload)
+ assert_equal(["v0", { "k1" => "v1" }], x.payload)
end
def test_rewrite_array_json_value
@connection.execute %q|insert into json_data_type (payload) VALUES ('["v0",{"k1":"v1"}]')|
x = JsonDataType.first
- x.payload = ["v1", {"k2" => "v2"}, "v3"]
+ x.payload = ["v1", { "k2" => "v2" }, "v3"]
assert x.save!
end
diff --git a/activerecord/test/cases/adapters/postgresql/range_test.rb b/activerecord/test/cases/adapters/postgresql/range_test.rb
index 3f819f7bd5..f411884dfd 100644
--- a/activerecord/test/cases/adapters/postgresql/range_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/range_test.rb
@@ -282,6 +282,12 @@ _SQL
assert_raises(ArgumentError) { PostgresqlRange.create!(tstz_range: "(''2010-01-01 14:30:00+05'', ''2011-01-01 14:30:00-03'']") }
end
+ def test_where_by_attribute_with_range
+ range = 1..100
+ record = PostgresqlRange.create!(int4_range: range)
+ assert_equal record, PostgresqlRange.where(int4_range: range).take
+ end
+
def test_update_all_with_ranges
PostgresqlRange.create!
diff --git a/activerecord/test/cases/adapters/postgresql/schema_test.rb b/activerecord/test/cases/adapters/postgresql/schema_test.rb
index d821cbafdf..b0be25de0c 100644
--- a/activerecord/test/cases/adapters/postgresql/schema_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/schema_test.rb
@@ -332,7 +332,7 @@ class SchemaTest < ActiveRecord::PostgreSQLTestCase
@connection.execute "CREATE INDEX \"things_Index\" ON #{SCHEMA_NAME}.things (name)"
with_schema_search_path SCHEMA_NAME do
- assert_nothing_raised { @connection.remove_index "things", name: "things_Index"}
+ assert_nothing_raised { @connection.remove_index "things", name: "things_Index" }
end
end
diff --git a/activerecord/test/cases/adapters/postgresql/utils_test.rb b/activerecord/test/cases/adapters/postgresql/utils_test.rb
index 70f72dd929..01c597beae 100644
--- a/activerecord/test/cases/adapters/postgresql/utils_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/utils_test.rb
@@ -54,7 +54,7 @@ class PostgreSQLNameTest < ActiveRecord::PostgreSQLTestCase
end
test "can be used as hash key" do
- hash = {Name.new("schema", "article_seq") => "success"}
+ hash = { Name.new("schema", "article_seq") => "success" }
assert_equal "success", hash[Name.new("schema", "article_seq")]
assert_equal nil, hash[Name.new("schema", "articles")]
assert_equal nil, hash[Name.new("public", "article_seq")]
diff --git a/activerecord/test/cases/adapters/sqlite3/copy_table_test.rb b/activerecord/test/cases/adapters/sqlite3/copy_table_test.rb
index 70e2f0fec1..8342b05870 100644
--- a/activerecord/test/cases/adapters/sqlite3/copy_table_test.rb
+++ b/activerecord/test/cases/adapters/sqlite3/copy_table_test.rb
@@ -11,7 +11,7 @@ class CopyTableTest < ActiveRecord::SQLite3TestCase
end
def test_copy_table(from = "customers", to = "customers2", options = {})
- assert_nothing_raised {copy_table(from, to, options)}
+ assert_nothing_raised { copy_table(from, to, options) }
assert_equal row_count(from), row_count(to)
if block_given?
@@ -25,7 +25,7 @@ class CopyTableTest < ActiveRecord::SQLite3TestCase
def test_copy_table_renaming_column
test_copy_table("customers", "customers2",
- rename: {"name" => "person_name"}) do |from, to, options|
+ rename: { "name" => "person_name" }) do |from, to, options|
expected = column_values(from, "name")
assert_equal expected, column_values(to, "person_name")
assert expected.any?, "No values in table: #{expected.inspect}"
@@ -55,8 +55,8 @@ class CopyTableTest < ActiveRecord::SQLite3TestCase
def test_copy_table_with_id_col_that_is_not_primary_key
test_copy_table("goofy_string_id", "goofy_string_id2") do
- original_id = @connection.columns("goofy_string_id").detect{|col| col.name == "id" }
- copied_id = @connection.columns("goofy_string_id2").detect{|col| col.name == "id" }
+ original_id = @connection.columns("goofy_string_id").detect { |col| col.name == "id" }
+ copied_id = @connection.columns("goofy_string_id2").detect { |col| col.name == "id" }
assert_equal original_id.type, copied_id.type
assert_equal original_id.sql_type, copied_id.sql_type
assert_equal original_id.limit, copied_id.limit
@@ -77,15 +77,15 @@ class CopyTableTest < ActiveRecord::SQLite3TestCase
protected
def copy_table(from, to, options = {})
- @connection.copy_table(from, to, {temporary: true}.merge(options))
+ @connection.copy_table(from, to, { temporary: true }.merge(options))
end
def column_names(table)
- @connection.table_structure(table).map {|column| column["name"]}
+ @connection.table_structure(table).map { |column| column["name"] }
end
def column_values(table, column)
- @connection.select_all("SELECT #{column} FROM #{table} ORDER BY id").map {|row| row[column]}
+ @connection.select_all("SELECT #{column} FROM #{table} ORDER BY id").map { |row| row[column] }
end
def table_indexes_without_name(table)
diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
index 4800d3d7d5..d2f0710cb2 100644
--- a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
+++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
@@ -405,7 +405,7 @@ module ActiveRecord
configurations["arunit"]["database"])
statement = ::SQLite3::Statement.new(db,
"CREATE TABLE statement_test (number integer not null)")
- statement.stub(:step, ->{ raise ::SQLite3::BusyException.new("busy") }) do
+ statement.stub(:step, -> { raise ::SQLite3::BusyException.new("busy") }) do
assert_called(statement, :columns, returns: []) do
assert_called(statement, :close) do
::SQLite3::Statement.stub(:new, statement) do
diff --git a/activerecord/test/cases/ar_schema_test.rb b/activerecord/test/cases/ar_schema_test.rb
index a4919c913d..e3eccad71f 100644
--- a/activerecord/test/cases/ar_schema_test.rb
+++ b/activerecord/test/cases/ar_schema_test.rb
@@ -17,6 +17,7 @@ if ActiveRecord::Base.connection.supports_migrations?
@connection.drop_table :nep_fruits rescue nil
@connection.drop_table :nep_schema_migrations rescue nil
@connection.drop_table :has_timestamps rescue nil
+ @connection.drop_table :multiple_indexes rescue nil
ActiveRecord::SchemaMigration.delete_all rescue nil
ActiveRecord::Migration.verbose = @original_verbose
end
@@ -93,6 +94,21 @@ if ActiveRecord::Base.connection.supports_migrations?
assert_equal "20131219224947", ActiveRecord::SchemaMigration.normalize_migration_number("20131219224947")
end
+ def test_schema_load_with_multiple_indexes_for_column_of_different_names
+ ActiveRecord::Schema.define do
+ create_table :multiple_indexes do |t|
+ t.string "foo"
+ t.index ["foo"], name: "multiple_indexes_foo_1"
+ t.index ["foo"], name: "multiple_indexes_foo_2"
+ end
+ end
+
+ indexes = @connection.indexes("multiple_indexes")
+
+ assert_equal 2, indexes.length
+ assert_equal ["multiple_indexes_foo_1", "multiple_indexes_foo_2"], indexes.collect(&:name).sort
+ end
+
def test_timestamps_without_null_set_null_to_false_on_create_table
ActiveRecord::Schema.define do
create_table :has_timestamps do |t|
diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb
index 2413bf0c3a..3f42cb9b9d 100644
--- a/activerecord/test/cases/associations/belongs_to_associations_test.rb
+++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb
@@ -94,7 +94,7 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
account = model.new
assert_not account.valid?
- assert_equal [{error: :blank}], account.errors.details[:company]
+ assert_equal [{ error: :blank }], account.errors.details[:company]
ensure
ActiveRecord::Base.belongs_to_required_by_default = original_value
end
@@ -111,7 +111,7 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
account = model.new
assert_not account.valid?
- assert_equal [{error: :blank}], account.errors.details[:company]
+ assert_equal [{ error: :blank }], account.errors.details[:company]
ensure
ActiveRecord::Base.belongs_to_required_by_default = original_value
end
@@ -203,14 +203,14 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
def test_eager_loading_with_primary_key
Firm.create("name" => "Apple")
Client.create("name" => "Citibank", :firm_name => "Apple")
- citibank_result = Client.all.merge!(where: {name: "Citibank"}, includes: :firm_with_primary_key).first
+ citibank_result = Client.all.merge!(where: { name: "Citibank" }, includes: :firm_with_primary_key).first
assert citibank_result.association(:firm_with_primary_key).loaded?
end
def test_eager_loading_with_primary_key_as_symbol
Firm.create("name" => "Apple")
Client.create("name" => "Citibank", :firm_name => "Apple")
- citibank_result = Client.all.merge!(where: {name: "Citibank"}, includes: :firm_with_primary_key_symbols).first
+ citibank_result = Client.all.merge!(where: { name: "Citibank" }, includes: :firm_with_primary_key_symbols).first
assert citibank_result.association(:firm_with_primary_key_symbols).loaded?
end
@@ -1004,21 +1004,21 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
def test_build_with_block
client = Client.create(name: "Client Company")
- firm = client.build_firm{ |f| f.name = "Agency Company" }
+ firm = client.build_firm { |f| f.name = "Agency Company" }
assert_equal "Agency Company", firm.name
end
def test_create_with_block
client = Client.create(name: "Client Company")
- firm = client.create_firm{ |f| f.name = "Agency Company" }
+ firm = client.create_firm { |f| f.name = "Agency Company" }
assert_equal "Agency Company", firm.name
end
def test_create_bang_with_block
client = Client.create(name: "Client Company")
- firm = client.create_firm!{ |f| f.name = "Agency Company" }
+ firm = client.create_firm! { |f| f.name = "Agency Company" }
assert_equal "Agency Company", firm.name
end
diff --git a/activerecord/test/cases/associations/callbacks_test.rb b/activerecord/test/cases/associations/callbacks_test.rb
index 15ef2d55c3..c3d560cb56 100644
--- a/activerecord/test/cases/associations/callbacks_test.rb
+++ b/activerecord/test/cases/associations/callbacks_test.rb
@@ -137,7 +137,6 @@ class AssociationCallbacksTest < ActiveRecord::TestCase
assert_equal "after_adding<new>", ar.developers_log.last
end
-
def test_has_and_belongs_to_many_remove_callback
david = developers(:david)
jamis = developers(:jamis)
@@ -160,7 +159,7 @@ class AssociationCallbacksTest < ActiveRecord::TestCase
activerecord.reload
assert activerecord.developers_with_callbacks.size == 2
end
- activerecord.developers_with_callbacks.flat_map {|d| ["before_removing#{d.id}","after_removing#{d.id}"]}.sort
+ activerecord.developers_with_callbacks.flat_map { |d| ["before_removing#{d.id}","after_removing#{d.id}"] }.sort
assert activerecord.developers_with_callbacks.clear
assert_predicate activerecord.developers_log, :empty?
end
diff --git a/activerecord/test/cases/associations/cascaded_eager_loading_test.rb b/activerecord/test/cases/associations/cascaded_eager_loading_test.rb
index d79246a6c7..9ae1558dc9 100644
--- a/activerecord/test/cases/associations/cascaded_eager_loading_test.rb
+++ b/activerecord/test/cases/associations/cascaded_eager_loading_test.rb
@@ -16,28 +16,28 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
:categorizations, :people, :categories, :edges, :vertices
def test_eager_association_loading_with_cascaded_two_levels
- authors = Author.all.merge!(includes: {posts: :comments}, order: "authors.id").to_a
+ authors = Author.all.merge!(includes: { posts: :comments }, order: "authors.id").to_a
assert_equal 3, authors.size
assert_equal 5, authors[0].posts.size
assert_equal 3, authors[1].posts.size
- assert_equal 10, authors[0].posts.collect{|post| post.comments.size }.inject(0){|sum,i| sum+i}
+ assert_equal 10, authors[0].posts.collect { |post| post.comments.size }.inject(0) { |sum,i| sum+i }
end
def test_eager_association_loading_with_cascaded_two_levels_and_one_level
- authors = Author.all.merge!(includes: [{posts: :comments}, :categorizations], order: "authors.id").to_a
+ authors = Author.all.merge!(includes: [{ posts: :comments }, :categorizations], order: "authors.id").to_a
assert_equal 3, authors.size
assert_equal 5, authors[0].posts.size
assert_equal 3, authors[1].posts.size
- assert_equal 10, authors[0].posts.collect{|post| post.comments.size }.inject(0){|sum,i| sum+i}
+ assert_equal 10, authors[0].posts.collect { |post| post.comments.size }.inject(0) { |sum,i| sum+i }
assert_equal 1, authors[0].categorizations.size
assert_equal 2, authors[1].categorizations.size
end
def test_eager_association_loading_with_hmt_does_not_table_name_collide_when_joining_associations
assert_nothing_raised do
- Author.joins(:posts).eager_load(:comments).where(posts: {tags_count: 1}).to_a
+ Author.joins(:posts).eager_load(:comments).where(posts: { tags_count: 1 }).to_a
end
- authors = Author.joins(:posts).eager_load(:comments).where(posts: {tags_count: 1}).to_a
+ authors = Author.joins(:posts).eager_load(:comments).where(posts: { tags_count: 1 }).to_a
assert_equal 1, assert_no_queries { authors.size }
assert_equal 10, assert_no_queries { authors[0].comments.size }
end
@@ -50,7 +50,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
end
def test_cascaded_eager_association_loading_with_join_for_count
- categories = Category.joins(:categorizations).includes([{posts: :comments}, :authors])
+ categories = Category.joins(:categorizations).includes([{ posts: :comments }, :authors])
assert_equal 4, categories.count
assert_equal 4, categories.to_a.count
@@ -82,29 +82,29 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
end
def test_eager_association_loading_with_cascaded_two_levels_with_two_has_many_associations
- authors = Author.all.merge!(includes: {posts: [:comments, :categorizations]}, order: "authors.id").to_a
+ authors = Author.all.merge!(includes: { posts: [:comments, :categorizations] }, order: "authors.id").to_a
assert_equal 3, authors.size
assert_equal 5, authors[0].posts.size
assert_equal 3, authors[1].posts.size
- assert_equal 10, authors[0].posts.collect{|post| post.comments.size }.inject(0){|sum,i| sum+i}
+ assert_equal 10, authors[0].posts.collect { |post| post.comments.size }.inject(0) { |sum,i| sum+i }
end
def test_eager_association_loading_with_cascaded_two_levels_and_self_table_reference
- authors = Author.all.merge!(includes: {posts: [:comments, :author]}, order: "authors.id").to_a
+ authors = Author.all.merge!(includes: { posts: [:comments, :author] }, order: "authors.id").to_a
assert_equal 3, authors.size
assert_equal 5, authors[0].posts.size
assert_equal authors(:david).name, authors[0].name
- assert_equal [authors(:david).name], authors[0].posts.collect{|post| post.author.name}.uniq
+ assert_equal [authors(:david).name], authors[0].posts.collect { |post| post.author.name }.uniq
end
def test_eager_association_loading_with_cascaded_two_levels_with_condition
- authors = Author.all.merge!(includes: {posts: :comments}, where: "authors.id=1", order: "authors.id").to_a
+ authors = Author.all.merge!(includes: { posts: :comments }, where: "authors.id=1", order: "authors.id").to_a
assert_equal 1, authors.size
assert_equal 5, authors[0].posts.size
end
def test_eager_association_loading_with_cascaded_three_levels_by_ping_pong
- firms = Firm.all.merge!(includes: {account: {firm: :account}}, order: "companies.id").to_a
+ firms = Firm.all.merge!(includes: { account: { firm: :account } }, order: "companies.id").to_a
assert_equal 2, firms.size
assert_equal firms.first.account, firms.first.account.firm.account
assert_equal companies(:first_firm).account, assert_no_queries { firms.first.account.firm.account }
@@ -158,7 +158,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
end
def test_eager_association_loading_where_first_level_returns_nil
- authors = Author.all.merge!(includes: {post_about_thinking: :comments}, order: "authors.id DESC").to_a
+ authors = Author.all.merge!(includes: { post_about_thinking: :comments }, order: "authors.id DESC").to_a
assert_equal [authors(:bob), authors(:mary), authors(:david)], authors
assert_no_queries do
authors[2].post_about_thinking.comments.first
@@ -166,12 +166,12 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
end
def test_eager_association_loading_with_recursive_cascading_four_levels_has_many_through
- source = Vertex.all.merge!(includes: {sinks: {sinks: {sinks: :sinks}}}, order: "vertices.id").first
+ source = Vertex.all.merge!(includes: { sinks: { sinks: { sinks: :sinks } } }, order: "vertices.id").first
assert_equal vertices(:vertex_4), assert_no_queries { source.sinks.first.sinks.first.sinks.first }
end
def test_eager_association_loading_with_recursive_cascading_four_levels_has_and_belongs_to_many
- sink = Vertex.all.merge!(includes: {sources: {sources: {sources: :sources}}}, order: "vertices.id DESC").first
+ sink = Vertex.all.merge!(includes: { sources: { sources: { sources: :sources } } }, order: "vertices.id DESC").first
assert_equal vertices(:vertex_1), assert_no_queries { sink.sources.first.sources.first.sources.first.sources.first }
end
diff --git a/activerecord/test/cases/associations/eager_load_nested_include_test.rb b/activerecord/test/cases/associations/eager_load_nested_include_test.rb
index 7a3d0c6068..a7a8c6a783 100644
--- a/activerecord/test/cases/associations/eager_load_nested_include_test.rb
+++ b/activerecord/test/cases/associations/eager_load_nested_include_test.rb
@@ -58,8 +58,6 @@ class NonPolyTwo < ActiveRecord::Base
include Remembered
end
-
-
class EagerLoadPolyAssocsTest < ActiveRecord::TestCase
NUM_SIMPLE_OBJS = 50
NUM_SHAPE_EXPRESSIONS = 100
@@ -119,8 +117,8 @@ class EagerLoadNestedIncludeWithMissingDataTest < ActiveRecord::TestCase
def test_missing_data_in_a_nested_include_should_not_cause_errors_when_constructing_objects
assert_nothing_raised do
# @davey_mcdave doesn't have any author_favorites
- includes = {posts: :comments, categorizations: :category, author_favorites: :favorite_author }
- Author.all.merge!(includes: includes, where: {authors: {name: @davey_mcdave.name}}, order: "categories.name").to_a
+ includes = { posts: :comments, categorizations: :category, author_favorites: :favorite_author }
+ Author.all.merge!(includes: includes, where: { authors: { name: @davey_mcdave.name } }, order: "categories.name").to_a
end
end
end
diff --git a/activerecord/test/cases/associations/eager_singularization_test.rb b/activerecord/test/cases/associations/eager_singularization_test.rb
index 373b17483c..5d1c1c4b9b 100644
--- a/activerecord/test/cases/associations/eager_singularization_test.rb
+++ b/activerecord/test/cases/associations/eager_singularization_test.rb
@@ -1,6 +1,5 @@
require "cases/helper"
-
if ActiveRecord::Base.connection.supports_migrations?
class EagerSingularizationTest < ActiveRecord::TestCase
class Virus < ActiveRecord::Base
diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb
index c7c945e33f..2c826acf96 100644
--- a/activerecord/test/cases/associations/eager_test.rb
+++ b/activerecord/test/cases/associations/eager_test.rb
@@ -109,7 +109,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_duplicate_middle_objects
comments = Comment.all.merge!(where: "post_id = 1", includes: [post: :author]).to_a
assert_no_queries do
- comments.each {|comment| comment.post.author.name}
+ comments.each { |comment| comment.post.author.name }
end
end
@@ -175,7 +175,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
popular_post.readers.create!(person: people(:david))
readers = Reader.all.merge!(where: ["post_id = ?", popular_post.id],
- includes: {post: :comments}).to_a
+ includes: { post: :comments }).to_a
readers.each do |reader|
assert_equal [comment], reader.post.comments
end
@@ -188,7 +188,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
comment = car_post.comments.create!(body: "hmm")
categories = Category.all.merge!(where: { "posts.id" => car_post.id },
- includes: {posts: :comments}).to_a
+ includes: { posts: :comments }).to_a
categories.each do |category|
assert_equal [comment], category.posts[0].comments
end
@@ -206,7 +206,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_finding_with_includes_on_has_many_association_with_same_include_includes_only_once
author_id = authors(:david).id
- author = assert_queries(3) { Author.all.merge!(includes: {posts_with_comments: :comments}).find(author_id) } # find the author, then find the posts, then find the comments
+ author = assert_queries(3) { Author.all.merge!(includes: { posts_with_comments: :comments }).find(author_id) } # find the author, then find the posts, then find the comments
author.posts_with_comments.each do |post_with_comments|
assert_equal post_with_comments.comments.length, post_with_comments.comments.count
assert_nil post_with_comments.comments.to_a.uniq!
@@ -217,7 +217,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
author = authors(:david)
post = author.post_about_thinking_with_last_comment
last_comment = post.last_comment
- author = assert_queries(3) { Author.all.merge!(includes: {post_about_thinking_with_last_comment: :last_comment}).find(author.id)} # find the author, then find the posts, then find the comments
+ author = assert_queries(3) { Author.all.merge!(includes: { post_about_thinking_with_last_comment: :last_comment }).find(author.id) } # find the author, then find the posts, then find the comments
assert_no_queries do
assert_equal post, author.post_about_thinking_with_last_comment
assert_equal last_comment, author.post_about_thinking_with_last_comment.last_comment
@@ -228,7 +228,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
post = posts(:welcome)
author = post.author
author_address = author.author_address
- post = assert_queries(3) { Post.all.merge!(includes: {author_with_address: :author_address}).find(post.id) } # find the post, then find the author, then find the address
+ post = assert_queries(3) { Post.all.merge!(includes: { author_with_address: :author_address }).find(post.id) } # find the post, then find the author, then find the address
assert_no_queries do
assert_equal author, post.author_with_address
assert_equal author_address, post.author_with_address.author_address
@@ -238,7 +238,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_finding_with_includes_on_null_belongs_to_association_with_same_include_includes_only_once
post = posts(:welcome)
post.update!(author: nil)
- post = assert_queries(1) { Post.all.merge!(includes: {author_with_address: :author_address}).find(post.id) }
+ post = assert_queries(1) { Post.all.merge!(includes: { author_with_address: :author_address }).find(post.id) }
# find the post, then find the author which is null so no query for the author or address
assert_no_queries do
assert_equal nil, post.author_with_address
@@ -284,7 +284,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
# Regression test for 21c75e5
def test_nested_loading_does_not_raise_exception_when_association_does_not_exist
assert_nothing_raised do
- Post.all.merge!(includes: {author: :author_addresss}).find(posts(:authorless).id)
+ Post.all.merge!(includes: { author: :author_addresss }).find(posts(:authorless).id)
end
end
@@ -292,33 +292,33 @@ class EagerAssociationTest < ActiveRecord::TestCase
post_id = Comment.where(author_id: nil).where.not(post_id: nil).first.post_id
assert_nothing_raised do
- Post.preload(comments: [{author: :essays}]).find(post_id)
+ Post.preload(comments: [{ author: :essays }]).find(post_id)
end
end
def test_nested_loading_through_has_one_association
- aa = AuthorAddress.all.merge!(includes: {author: :posts}).find(author_addresses(:david_address).id)
+ aa = AuthorAddress.all.merge!(includes: { author: :posts }).find(author_addresses(:david_address).id)
assert_equal aa.author.posts.count, aa.author.posts.length
end
def test_nested_loading_through_has_one_association_with_order
- aa = AuthorAddress.all.merge!(includes: {author: :posts}, order: "author_addresses.id").find(author_addresses(:david_address).id)
+ aa = AuthorAddress.all.merge!(includes: { author: :posts }, order: "author_addresses.id").find(author_addresses(:david_address).id)
assert_equal aa.author.posts.count, aa.author.posts.length
end
def test_nested_loading_through_has_one_association_with_order_on_association
- aa = AuthorAddress.all.merge!(includes: {author: :posts}, order: "authors.id").find(author_addresses(:david_address).id)
+ aa = AuthorAddress.all.merge!(includes: { author: :posts }, order: "authors.id").find(author_addresses(:david_address).id)
assert_equal aa.author.posts.count, aa.author.posts.length
end
def test_nested_loading_through_has_one_association_with_order_on_nested_association
- aa = AuthorAddress.all.merge!(includes: {author: :posts}, order: "posts.id").find(author_addresses(:david_address).id)
+ aa = AuthorAddress.all.merge!(includes: { author: :posts }, order: "posts.id").find(author_addresses(:david_address).id)
assert_equal aa.author.posts.count, aa.author.posts.length
end
def test_nested_loading_through_has_one_association_with_conditions
aa = AuthorAddress.references(:author_addresses).merge(
- includes: {author: :posts},
+ includes: { author: :posts },
where: "author_addresses.id > 0"
).find author_addresses(:david_address).id
assert_equal aa.author.posts.count, aa.author.posts.length
@@ -326,7 +326,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_nested_loading_through_has_one_association_with_conditions_on_association
aa = AuthorAddress.references(:authors).merge(
- includes: {author: :posts},
+ includes: { author: :posts },
where: "authors.id > 0"
).find author_addresses(:david_address).id
assert_equal aa.author.posts.count, aa.author.posts.length
@@ -334,7 +334,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_nested_loading_through_has_one_association_with_conditions_on_nested_association
aa = AuthorAddress.references(:posts).merge(
- includes: {author: :posts},
+ includes: { author: :posts },
where: "posts.id > 0"
).find author_addresses(:david_address).id
assert_equal aa.author.posts.count, aa.author.posts.length
@@ -392,7 +392,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_association_loading_with_belongs_to_and_conditions_hash
comments = []
assert_nothing_raised do
- comments = Comment.all.merge!(includes: :post, where: {posts: {id: 4}}, limit: 3, order: "comments.id").to_a
+ comments = Comment.all.merge!(includes: :post, where: { posts: { id: 4 } }, limit: 3, order: "comments.id").to_a
end
assert_equal 3, comments.length
assert_equal [5,6,7], comments.collect(&:id)
@@ -441,25 +441,25 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_load_belongs_to_quotes_table_and_column_names
job = Job.includes(:ideal_reference).find jobs(:unicyclist).id
references(:michael_unicyclist)
- assert_no_queries{ assert_equal references(:michael_unicyclist), job.ideal_reference}
+ assert_no_queries { assert_equal references(:michael_unicyclist), job.ideal_reference }
end
def test_eager_load_has_one_quotes_table_and_column_names
michael = Person.all.merge!(includes: :favourite_reference).find(people(:michael).id)
references(:michael_unicyclist)
- assert_no_queries{ assert_equal references(:michael_unicyclist), michael.favourite_reference}
+ assert_no_queries { assert_equal references(:michael_unicyclist), michael.favourite_reference }
end
def test_eager_load_has_many_quotes_table_and_column_names
michael = Person.all.merge!(includes: :references).find(people(:michael).id)
references(:michael_magician,:michael_unicyclist)
- assert_no_queries{ assert_equal references(:michael_magician,:michael_unicyclist), michael.references.sort_by(&:id) }
+ assert_no_queries { assert_equal references(:michael_magician,:michael_unicyclist), michael.references.sort_by(&:id) }
end
def test_eager_load_has_many_through_quotes_table_and_column_names
michael = Person.all.merge!(includes: :jobs).find(people(:michael).id)
jobs(:magician, :unicyclist)
- assert_no_queries{ assert_equal jobs(:unicyclist, :magician), michael.jobs.sort_by(&:id) }
+ assert_no_queries { assert_equal jobs(:unicyclist, :magician), michael.jobs.sort_by(&:id) }
end
def test_eager_load_has_many_with_string_keys
@@ -903,8 +903,8 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_multiple_associations_with_same_table_has_many_and_habtm
# Eager includes of has many and habtm associations aren't necessarily sorted in the same way
def assert_equal_after_sort(item1, item2, item3 = nil)
- assert_equal(item1.sort{|a,b| a.id <=> b.id}, item2.sort{|a,b| a.id <=> b.id})
- assert_equal(item3.sort{|a,b| a.id <=> b.id}, item2.sort{|a,b| a.id <=> b.id}) if item3
+ assert_equal(item1.sort { |a,b| a.id <=> b.id }, item2.sort { |a,b| a.id <=> b.id })
+ assert_equal(item3.sort { |a,b| a.id <=> b.id }, item2.sort { |a,b| a.id <=> b.id }) if item3
end
# Test regular association, association with conditions, association with
# STI, and association with conditions assured not to be true
@@ -959,12 +959,12 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_preconfigured_includes_with_belongs_to
author = posts(:welcome).author_with_posts
- assert_no_queries {assert_equal 5, author.posts.size}
+ assert_no_queries { assert_equal 5, author.posts.size }
end
def test_preconfigured_includes_with_has_one
comment = posts(:sti_comments).very_special_comment_with_post
- assert_no_queries {assert_equal posts(:sti_comments), comment.post}
+ assert_no_queries { assert_equal posts(:sti_comments), comment.post }
end
def test_eager_association_with_scope_with_joins
@@ -1066,7 +1066,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
Post.all.merge!(joins: :comments, includes: :author, order: "comments.id DESC").to_a
end
assert_equal posts(:eager_other), posts[1]
- assert_equal authors(:mary), assert_no_queries { posts[1].author}
+ assert_equal authors(:mary), assert_no_queries { posts[1].author }
end
def test_eager_loading_with_conditions_on_joined_table_preloads
@@ -1074,21 +1074,21 @@ class EagerAssociationTest < ActiveRecord::TestCase
Post.all.merge!(select: "distinct posts.*", includes: :author, joins: [:comments], where: "comments.body like 'Thank you%'", order: "posts.id").to_a
end
assert_equal [posts(:welcome)], posts
- assert_equal authors(:david), assert_no_queries { posts[0].author}
+ assert_equal authors(:david), assert_no_queries { posts[0].author }
posts = assert_queries(2) do
Post.all.merge!(select: "distinct posts.*", includes: :author, joins: [:comments], where: "comments.body like 'Thank you%'", order: "posts.id").to_a
end
assert_equal [posts(:welcome)], posts
- assert_equal authors(:david), assert_no_queries { posts[0].author}
+ assert_equal authors(:david), assert_no_queries { posts[0].author }
posts = assert_queries(2) do
- Post.all.merge!(includes: :author, joins: {taggings: :tag}, where: "tags.name = 'General'", order: "posts.id").to_a
+ Post.all.merge!(includes: :author, joins: { taggings: :tag }, where: "tags.name = 'General'", order: "posts.id").to_a
end
assert_equal posts(:welcome, :thinking), posts
posts = assert_queries(2) do
- Post.all.merge!(includes: :author, joins: {taggings: {tag: :taggings}}, where: "taggings_tags.super_tag_id=2", order: "posts.id").to_a
+ Post.all.merge!(includes: :author, joins: { taggings: { tag: :taggings } }, where: "taggings_tags.super_tag_id=2", order: "posts.id").to_a
end
assert_equal posts(:welcome, :thinking), posts
end
@@ -1110,13 +1110,13 @@ class EagerAssociationTest < ActiveRecord::TestCase
Post.all.merge!(select: "distinct posts.*", includes: :author, joins: "INNER JOIN comments on comments.post_id = posts.id", where: "comments.body like 'Thank you%'", order: "posts.id").to_a
end
assert_equal [posts(:welcome)], posts
- assert_equal authors(:david), assert_no_queries { posts[0].author}
+ assert_equal authors(:david), assert_no_queries { posts[0].author }
posts = assert_queries(2) do
Post.all.merge!(select: "distinct posts.*", includes: :author, joins: ["INNER JOIN comments on comments.post_id = posts.id"], where: "comments.body like 'Thank you%'", order: "posts.id").to_a
end
assert_equal [posts(:welcome)], posts
- assert_equal authors(:david), assert_no_queries { posts[0].author}
+ assert_equal authors(:david), assert_no_queries { posts[0].author }
end
def test_eager_loading_with_select_on_joined_table_preloads
@@ -1124,7 +1124,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
Post.all.merge!(select: "posts.*, authors.name as author_name", includes: :comments, joins: :author, order: "posts.id").to_a
end
assert_equal "David", posts[0].author_name
- assert_equal posts(:welcome).comments, assert_no_queries { posts[0].comments}
+ assert_equal posts(:welcome).comments, assert_no_queries { posts[0].comments }
end
def test_eager_loading_with_conditions_on_join_model_preloads
@@ -1139,7 +1139,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
people = Person.males.merge(includes: :primary_contact).to_a
assert_not_equal people.length, 0
people.each do |person|
- assert_no_queries {assert_not_nil person.primary_contact}
+ assert_no_queries { assert_not_nil person.primary_contact }
assert_equal Person.find(person.id).primary_contact, person.primary_contact
end
end
@@ -1182,7 +1182,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_include_has_one_using_primary_key
expected = accounts(:signals37)
- firm = Firm.all.merge!(includes: :account_using_primary_key, order: "accounts.id").to_a.detect {|f| f.id == 1}
+ firm = Firm.all.merge!(includes: :account_using_primary_key, order: "accounts.id").to_a.detect { |f| f.id == 1 }
assert_no_queries do
assert_equal expected, firm.account_using_primary_key
end
@@ -1253,16 +1253,16 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_join_eager_with_empty_order_should_generate_valid_sql
assert_nothing_raised do
- Post.includes(:comments).order("").where(comments: {body: "Thank you for the welcome"}).first
+ Post.includes(:comments).order("").where(comments: { body: "Thank you for the welcome" }).first
end
end
def test_deep_including_through_habtm
# warm up habtm cache
- posts = Post.all.merge!(includes: {categories: :categorizations}, order: "posts.id").to_a
+ posts = Post.all.merge!(includes: { categories: :categorizations }, order: "posts.id").to_a
posts[0].categories[0].categorizations.length
- posts = Post.all.merge!(includes: {categories: :categorizations}, order: "posts.id").to_a
+ posts = Post.all.merge!(includes: { categories: :categorizations }, order: "posts.id").to_a
assert_no_queries { assert_equal 2, posts[0].categories[0].categorizations.length }
assert_no_queries { assert_equal 1, posts[0].categories[1].categorizations.length }
assert_no_queries { assert_equal 2, posts[1].categories[0].categorizations.length }
@@ -1360,7 +1360,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
test "including associations with where.not adds implicit references" do
author = assert_queries(2) {
- Author.includes(:posts).where.not(posts: { title: "Welcome to the weblog"} ).last
+ Author.includes(:posts).where.not(posts: { title: "Welcome to the weblog" } ).last
}
assert_no_queries {
diff --git a/activerecord/test/cases/associations/extension_test.rb b/activerecord/test/cases/associations/extension_test.rb
index 8f9fc10ba5..cc86e1a16d 100644
--- a/activerecord/test/cases/associations/extension_test.rb
+++ b/activerecord/test/cases/associations/extension_test.rb
@@ -76,6 +76,6 @@ class AssociationsExtensionsTest < ActiveRecord::TestCase
private
def extend!(model)
- ActiveRecord::Associations::Builder::HasMany.define_extensions(model, :association_name) { }
+ ActiveRecord::Associations::Builder::HasMany.define_extensions(model, :association_name) {}
end
end
diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
index c4f174e470..36f541a506 100644
--- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
@@ -258,7 +258,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
def test_habtm_saving_multiple_relationships
new_project = Project.new("name" => "Grimetime")
amount_of_developers = 4
- developers = (0...amount_of_developers).collect {|i| Developer.create(name: "JME #{i}") }.reverse
+ developers = (0...amount_of_developers).collect { |i| Developer.create(name: "JME #{i}") }.reverse
new_project.developer_ids = [developers[0].id, developers[1].id]
new_project.developers_with_callback_ids = [developers[2].id, developers[3].id]
@@ -283,7 +283,8 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
end
def test_habtm_collection_size_from_params
- devel = Developer.new( projects_attributes: {
+ devel = Developer.new(
+ projects_attributes: {
"0" => {}
})
@@ -587,7 +588,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
end
def test_dynamic_find_all_should_respect_readonly_access
- projects(:active_record).readonly_developers.each { |d| assert_raise(ActiveRecord::ReadOnlyRecord) { d.save! } if d.valid?}
+ projects(:active_record).readonly_developers.each { |d| assert_raise(ActiveRecord::ReadOnlyRecord) { d.save! } if d.valid? }
projects(:active_record).readonly_developers.each(&:readonly?)
end
@@ -699,7 +700,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
assert_equal(
3,
Developer.references(:developers_projects_join).merge(
- includes: {projects: :developers},
+ includes: { projects: :developers },
where: "projects_developers_projects_join.joined_on IS NOT NULL"
).to_a.size
)
@@ -719,7 +720,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
assert_equal(
3,
Developer.references(:developers_projects_join).merge(
- includes: {projects: :developers}, where: "projects_developers_projects_join.joined_on IS NOT NULL",
+ includes: { projects: :developers }, where: "projects_developers_projects_join.joined_on IS NOT NULL",
group: group.join(",")
).to_a.size
)
diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb
index 09692fc3a0..1bfb1ea0c8 100644
--- a/activerecord/test/cases/associations/has_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -305,7 +305,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
test "building the association with an array" do
speedometer = Speedometer.new(speedometer_id: "a")
- data = [{name: "first"}, {name: "second"}]
+ data = [{ name: "first" }, { name: "second" }]
speedometer.minivans.build(data)
assert_equal 2, speedometer.minivans.size
@@ -380,47 +380,78 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_no_queries do
bulbs.first()
- bulbs.first({})
end
assert_no_queries do
bulbs.second()
- bulbs.second({})
end
assert_no_queries do
bulbs.third()
- bulbs.third({})
end
assert_no_queries do
bulbs.fourth()
- bulbs.fourth({})
end
assert_no_queries do
bulbs.fifth()
- bulbs.fifth({})
end
assert_no_queries do
bulbs.forty_two()
- bulbs.forty_two({})
end
assert_no_queries do
bulbs.third_to_last()
- bulbs.third_to_last({})
end
assert_no_queries do
bulbs.second_to_last()
- bulbs.second_to_last({})
end
assert_no_queries do
bulbs.last()
- bulbs.last({})
+ end
+ end
+
+ def test_finder_method_with_dirty_target
+ company = companies(:first_firm)
+ new_clients = []
+ assert_no_queries(ignore_none: false) do
+ new_clients << company.clients_of_firm.build(name: "Another Client")
+ new_clients << company.clients_of_firm.build(name: "Another Client II")
+ new_clients << company.clients_of_firm.build(name: "Another Client III")
+ end
+
+ assert_not company.clients_of_firm.loaded?
+ assert_queries(1) do
+ assert_same new_clients[0], company.clients_of_firm.third
+ assert_same new_clients[1], company.clients_of_firm.fourth
+ assert_same new_clients[2], company.clients_of_firm.fifth
+ assert_same new_clients[0], company.clients_of_firm.third_to_last
+ assert_same new_clients[1], company.clients_of_firm.second_to_last
+ assert_same new_clients[2], company.clients_of_firm.last
+ end
+ end
+
+ def test_finder_bang_method_with_dirty_target
+ company = companies(:first_firm)
+ new_clients = []
+ assert_no_queries(ignore_none: false) do
+ new_clients << company.clients_of_firm.build(name: "Another Client")
+ new_clients << company.clients_of_firm.build(name: "Another Client II")
+ new_clients << company.clients_of_firm.build(name: "Another Client III")
+ end
+
+ assert_not company.clients_of_firm.loaded?
+ assert_queries(1) do
+ assert_same new_clients[0], company.clients_of_firm.third!
+ assert_same new_clients[1], company.clients_of_firm.fourth!
+ assert_same new_clients[2], company.clients_of_firm.fifth!
+ assert_same new_clients[0], company.clients_of_firm.third_to_last!
+ assert_same new_clients[1], company.clients_of_firm.second_to_last!
+ assert_same new_clients[2], company.clients_of_firm.last!
end
end
@@ -487,7 +518,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_finding_array_compatibility
- assert_equal 3, Firm.order(:id).find{|f| f.id > 0}.clients.length
+ assert_equal 3, Firm.order(:id).find { |f| f.id > 0 }.clients.length
end
def test_find_many_with_merged_options
@@ -525,14 +556,18 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_taking_with_a_number
# taking from unloaded Relation
bob = Author.find(authors(:bob).id)
+ new_post = bob.posts.build
+ assert_not bob.posts.loaded?
assert_equal [posts(:misc_by_bob)], bob.posts.take(1)
- bob = Author.find(authors(:bob).id)
assert_equal [posts(:misc_by_bob), posts(:other_by_bob)], bob.posts.take(2)
+ assert_equal [posts(:misc_by_bob), posts(:other_by_bob), new_post], bob.posts.take(3)
# taking from loaded Relation
- bob.posts.to_a
- assert_equal [posts(:misc_by_bob)], authors(:bob).posts.take(1)
- assert_equal [posts(:misc_by_bob), posts(:other_by_bob)], authors(:bob).posts.take(2)
+ bob.posts.load
+ assert bob.posts.loaded?
+ assert_equal [posts(:misc_by_bob)], bob.posts.take(1)
+ assert_equal [posts(:misc_by_bob), posts(:other_by_bob)], bob.posts.take(2)
+ assert_equal [posts(:misc_by_bob), posts(:other_by_bob), new_post], bob.posts.take(3)
end
def test_taking_with_inverse_of
@@ -618,6 +653,18 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_raise(ActiveRecord::RecordNotFound) { firm.clients.find(2, 99) }
end
+ def test_find_one_message_on_primary_key
+ firm = Firm.all.merge!(order: "id").first
+
+ e = assert_raises(ActiveRecord::RecordNotFound) do
+ firm.clients.find(0)
+ end
+ assert_equal 0, e.id
+ assert_equal "id", e.primary_key
+ assert_equal "Client", e.model
+ assert_match (/\ACouldn't find Client with 'id'=0/), e.message
+ end
+
def test_find_ids_and_inverse_of
force_signal37_to_load_all_clients_of_firm
@@ -644,7 +691,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert ! firm.clients.loaded?
assert_queries(4) do
- firm.clients.find_each(batch_size: 1) {|c| assert_equal firm.id, c.firm_id }
+ firm.clients.find_each(batch_size: 1) { |c| assert_equal firm.id, c.firm_id }
end
assert ! firm.clients.loaded?
@@ -670,7 +717,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_queries(2) do
firm.clients.find_in_batches(batch_size: 2) do |clients|
- clients.each {|c| assert_equal firm.id, c.firm_id }
+ clients.each { |c| assert_equal firm.id, c.firm_id }
end
end
@@ -701,7 +748,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_find_all_with_include_and_conditions
assert_nothing_raised do
- Developer.all.merge!(joins: :audit_logs, where: {"audit_logs.message" => nil, :name => "Smith"}).to_a
+ Developer.all.merge!(joins: :audit_logs, where: { "audit_logs.message" => nil, :name => "Smith" }).to_a
end
end
@@ -888,7 +935,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_build_many
company = companies(:first_firm)
- new_clients = assert_no_queries(ignore_none: false) { company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) }
+ new_clients = assert_no_queries(ignore_none: false) { company.clients_of_firm.build([{ "name" => "Another Client" }, { "name" => "Another Client II" }]) }
assert_equal 2, new_clients.size
end
@@ -914,7 +961,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_build_via_block
company = companies(:first_firm)
- new_client = assert_no_queries(ignore_none: false) { company.clients_of_firm.build {|client| client.name = "Another Client" } }
+ new_client = assert_no_queries(ignore_none: false) { company.clients_of_firm.build { |client| client.name = "Another Client" } }
assert !company.clients_of_firm.loaded?
assert_equal "Another Client", new_client.name
@@ -925,7 +972,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_build_many_via_block
company = companies(:first_firm)
new_clients = assert_no_queries(ignore_none: false) do
- company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) do |client|
+ company.clients_of_firm.build([{ "name" => "Another Client" }, { "name" => "Another Client II" }]) do |client|
client.name = "changed"
end
end
@@ -962,7 +1009,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_create_many
- companies(:first_firm).clients_of_firm.create([{"name" => "Another Client"}, {"name" => "Another Client II"}])
+ companies(:first_firm).clients_of_firm.create([{ "name" => "Another Client" }, { "name" => "Another Client II" }])
assert_equal 4, companies(:first_firm).clients_of_firm.reload.size
end
@@ -1564,7 +1611,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_restrict_with_error_with_locale
I18n.backend = I18n::Backend::Simple.new
- I18n.backend.store_translations "en", activerecord: {attributes: {restricted_with_error_firm: {companies: "client companies"}}}
+ I18n.backend.store_translations "en", activerecord: { attributes: { restricted_with_error_firm: { companies: "client companies" } } }
firm = RestrictedWithErrorFirm.create!(name: "restrict")
firm.companies.create(name: "child")
@@ -1742,7 +1789,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
lambda { authors(:mary).comments = [comments(:greetings), comments(:more_greetings)] },
lambda { authors(:mary).comments << Comment.create!(body: "Yay", post_id: 424242) },
lambda { authors(:mary).comments.delete(authors(:mary).comments.first) },
- ].each {|block| assert_raise(ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection, &block) }
+ ].each { |block| assert_raise(ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection, &block) }
end
def test_dynamic_find_should_respect_association_order_for_through
diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb
index 90004eb70f..3508793122 100644
--- a/activerecord/test/cases/associations/has_many_through_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb
@@ -348,7 +348,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
end
def test_delete_association
- assert_queries(2){posts(:welcome);people(:michael); }
+ assert_queries(2) { posts(:welcome);people(:michael); }
assert_queries(1) do
posts(:welcome).people.delete(people(:michael))
@@ -541,7 +541,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
end
def test_replace_association
- assert_queries(4){posts(:welcome);people(:david);people(:michael); posts(:welcome).people.reload}
+ assert_queries(4) { posts(:welcome);people(:david);people(:michael); posts(:welcome).people.reload }
# 1 query to delete the existing reader (michael)
# 1 query to associate the new reader (david)
@@ -549,7 +549,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
posts(:welcome).people = [people(:david)]
end
- assert_queries(0){
+ assert_queries(0) {
assert posts(:welcome).people.include?(people(:david))
assert !posts(:welcome).people.include?(people(:michael))
}
@@ -658,7 +658,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
def test_push_with_invalid_join_record
repair_validations(Contract) do
- Contract.validate {|r| r.errors[:base] << "Invalid Contract" }
+ Contract.validate { |r| r.errors[:base] << "Invalid Contract" }
firm = companies(:first_firm)
lifo = Developer.new(name: "lifo")
@@ -812,7 +812,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
lambda { authors(:david).very_special_comments = [VerySpecialComment.create!(body: "Gorp!", post_id: 1011), VerySpecialComment.create!(body: "Eep!", post_id: 1012)] },
lambda { authors(:david).very_special_comments << VerySpecialComment.create!(body: "Hoohah!", post_id: 1013) },
lambda { authors(:david).very_special_comments.delete(authors(:david).very_special_comments.first) },
- ].each {|block| assert_raise(ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection, &block) }
+ ].each { |block| assert_raise(ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection, &block) }
end
def test_has_many_association_through_a_has_many_association_to_self
@@ -886,7 +886,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
def test_collection_singular_ids_setter_raises_exception_when_invalid_ids_set
company = companies(:rails_core)
ids = [Developer.first.id, -9999]
- assert_raises(ActiveRecord::AssociationTypeMismatch) {company.developer_ids= ids}
+ assert_raises(ActiveRecord::AssociationTypeMismatch) { company.developer_ids= ids }
end
def test_build_a_model_from_hm_through_association_with_where_clause
diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb
index ad0d47920d..1a0e6d2f8e 100644
--- a/activerecord/test/cases/associations/has_one_associations_test.rb
+++ b/activerecord/test/cases/associations/has_one_associations_test.rb
@@ -221,7 +221,7 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
def test_restrict_with_error_with_locale
I18n.backend = I18n::Backend::Simple.new
- I18n.backend.store_translations "en", activerecord: {attributes: {restricted_with_error_firm: {account: "firm account"}}}
+ I18n.backend.store_translations "en", activerecord: { attributes: { restricted_with_error_firm: { account: "firm account" } } }
firm = RestrictedWithErrorFirm.create!(name: "restrict")
firm.create_account(credit_limit: 10)
@@ -539,21 +539,21 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
def test_build_with_block
car = Car.create(name: "honda")
- bulb = car.build_bulb{ |b| b.color = "Red" }
+ bulb = car.build_bulb { |b| b.color = "Red" }
assert_equal "RED!", bulb.color
end
def test_create_with_block
car = Car.create(name: "honda")
- bulb = car.create_bulb{ |b| b.color = "Red" }
+ bulb = car.create_bulb { |b| b.color = "Red" }
assert_equal "RED!", bulb.color
end
def test_create_bang_with_block
car = Car.create(name: "honda")
- bulb = car.create_bulb!{ |b| b.color = "Red" }
+ bulb = car.create_bulb! { |b| b.color = "Red" }
assert_equal "RED!", bulb.color
end
diff --git a/activerecord/test/cases/associations/has_one_through_associations_test.rb b/activerecord/test/cases/associations/has_one_through_associations_test.rb
index 3a7f48fbb7..e95eeb64db 100644
--- a/activerecord/test/cases/associations/has_one_through_associations_test.rb
+++ b/activerecord/test/cases/associations/has_one_through_associations_test.rb
@@ -95,7 +95,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
Member.all.merge!(includes: :club, where: ["name = ?", "Groucho Marx"]).to_a
end
assert_equal 1, members.size
- assert_not_nil assert_no_queries {members[0].club}
+ assert_not_nil assert_no_queries { members[0].club }
end
def test_has_one_through_eager_loading_through_polymorphic
@@ -103,7 +103,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
Member.all.merge!(includes: :sponsor_club, where: ["name = ?", "Groucho Marx"]).to_a
end
assert_equal 1, members.size
- assert_not_nil assert_no_queries {members[0].sponsor_club}
+ assert_not_nil assert_no_queries { members[0].sponsor_club }
end
def test_has_one_through_with_conditions_eager_loading
@@ -125,7 +125,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
def test_eager_has_one_through_polymorphic_with_source_type
clubs = Club.all.merge!(includes: :sponsored_member, where: ["name = ?","Moustache and Eyebrow Fancier Club"]).to_a
# Only the eyebrow fanciers club has a sponsored_member
- assert_not_nil assert_no_queries {clubs[0].sponsored_member}
+ assert_not_nil assert_no_queries { clubs[0].sponsored_member }
end
def test_has_one_through_nonpreload_eagerloading
@@ -133,7 +133,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
Member.all.merge!(includes: :club, where: ["members.name = ?", "Groucho Marx"], order: "clubs.name").to_a #force fallback
end
assert_equal 1, members.size
- assert_not_nil assert_no_queries {members[0].club}
+ assert_not_nil assert_no_queries { members[0].club }
end
def test_has_one_through_nonpreload_eager_loading_through_polymorphic
@@ -141,7 +141,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
Member.all.merge!(includes: :sponsor_club, where: ["members.name = ?", "Groucho Marx"], order: "clubs.name").to_a #force fallback
end
assert_equal 1, members.size
- assert_not_nil assert_no_queries {members[0].sponsor_club}
+ assert_not_nil assert_no_queries { members[0].sponsor_club }
end
def test_has_one_through_nonpreload_eager_loading_through_polymorphic_with_more_than_one_through_record
diff --git a/activerecord/test/cases/associations/inner_join_association_test.rb b/activerecord/test/cases/associations/inner_join_association_test.rb
index be5c8854be..7414869c8f 100644
--- a/activerecord/test/cases/associations/inner_join_association_test.rb
+++ b/activerecord/test/cases/associations/inner_join_association_test.rb
@@ -20,7 +20,7 @@ class InnerJoinAssociationTest < ActiveRecord::TestCase
def test_construct_finder_sql_does_not_table_name_collide_on_duplicate_associations
assert_nothing_raised do
- sql = Person.joins(agents: {agents: :agents}).joins(agents: {agents: {primary_contact: :agents}}).to_sql
+ sql = Person.joins(agents: { agents: :agents }).joins(agents: { agents: { primary_contact: :agents } }).to_sql
assert_match(/agents_people_4/i, sql)
end
end
@@ -47,7 +47,7 @@ class InnerJoinAssociationTest < ActiveRecord::TestCase
end
def test_join_conditions_allow_nil_associations
- authors = Author.includes(:essays).where(essays: {id: nil})
+ authors = Author.includes(:essays).where(essays: { id: nil })
assert_equal 2, authors.count
end
@@ -60,13 +60,13 @@ class InnerJoinAssociationTest < ActiveRecord::TestCase
def test_find_with_implicit_inner_joins_honors_readonly_with_select
authors = Author.joins(:posts).select("authors.*").to_a
assert !authors.empty?, "expected authors to be non-empty"
- assert authors.all? {|a| !a.readonly? }, "expected no authors to be readonly"
+ assert authors.all? { |a| !a.readonly? }, "expected no authors to be readonly"
end
def test_find_with_implicit_inner_joins_honors_readonly_false
authors = Author.joins(:posts).readonly(false).to_a
assert !authors.empty?, "expected authors to be non-empty"
- assert authors.all? {|a| !a.readonly? }, "expected no authors to be readonly"
+ assert authors.all? { |a| !a.readonly? }, "expected no authors to be readonly"
end
def test_find_with_implicit_inner_joins_does_not_set_associations
@@ -76,17 +76,17 @@ class InnerJoinAssociationTest < ActiveRecord::TestCase
end
def test_count_honors_implicit_inner_joins
- real_count = Author.all.to_a.sum{|a| a.posts.count }
+ real_count = Author.all.to_a.sum { |a| a.posts.count }
assert_equal real_count, Author.joins(:posts).count, "plain inner join count should match the number of referenced posts records"
end
def test_calculate_honors_implicit_inner_joins
- real_count = Author.all.to_a.sum{|a| a.posts.count }
+ real_count = Author.all.to_a.sum { |a| a.posts.count }
assert_equal real_count, Author.joins(:posts).calculate(:count, "authors.id"), "plain inner join count should match the number of referenced posts records"
end
def test_calculate_honors_implicit_inner_joins_and_distinct_and_conditions
- real_count = Author.all.to_a.select {|a| a.posts.any? {|p| p.title.start_with?("Welcome")} }.length
+ real_count = Author.all.to_a.select { |a| a.posts.any? { |p| p.title.start_with?("Welcome") } }.length
authors_with_welcoming_post_titles = Author.all.merge!(joins: :posts, where: "posts.title like 'Welcome%'").distinct.calculate(:count, "authors.id")
assert_equal real_count, authors_with_welcoming_post_titles, "inner join and conditions should have only returned authors posting titles starting with 'Welcome'"
end
diff --git a/activerecord/test/cases/associations/inverse_associations_test.rb b/activerecord/test/cases/associations/inverse_associations_test.rb
index ae0468ef1e..0b23cea420 100644
--- a/activerecord/test/cases/associations/inverse_associations_test.rb
+++ b/activerecord/test/cases/associations/inverse_associations_test.rb
@@ -226,9 +226,8 @@ class InverseHasOneTests < ActiveRecord::TestCase
assert_equal m.name, f.man.name, "Name of man should be the same after changes to child-owned instance"
end
-
def test_parent_instance_should_be_shared_with_eager_loaded_child_on_find
- m = Man.all.merge!(where: {name: "Gordon"}, includes: :face).first
+ m = Man.all.merge!(where: { name: "Gordon" }, includes: :face).first
f = m.face
assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
m.name = "Bongo"
@@ -236,7 +235,7 @@ class InverseHasOneTests < ActiveRecord::TestCase
f.man.name = "Mungo"
assert_equal m.name, f.man.name, "Name of man should be the same after changes to child-owned instance"
- m = Man.all.merge!(where: {name: "Gordon"}, includes: :face, order: "faces.id").first
+ m = Man.all.merge!(where: { name: "Gordon" }, includes: :face, order: "faces.id").first
f = m.face
assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
m.name = "Bongo"
@@ -311,7 +310,7 @@ class InverseHasManyTests < ActiveRecord::TestCase
end
def test_parent_instance_should_be_shared_with_eager_loaded_children
- m = Man.all.merge!(where: {name: "Gordon"}, includes: :interests).first
+ m = Man.all.merge!(where: { name: "Gordon" }, includes: :interests).first
is = m.interests
is.each do |i|
assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
@@ -321,7 +320,7 @@ class InverseHasManyTests < ActiveRecord::TestCase
assert_equal m.name, i.man.name, "Name of man should be the same after changes to child-owned instance"
end
- m = Man.all.merge!(where: {name: "Gordon"}, includes: :interests, order: "interests.id").first
+ m = Man.all.merge!(where: { name: "Gordon" }, includes: :interests, order: "interests.id").first
is = m.interests
is.each do |i|
assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
@@ -334,7 +333,7 @@ class InverseHasManyTests < ActiveRecord::TestCase
def test_parent_instance_should_be_shared_with_newly_block_style_built_child
m = Man.first
- i = m.interests.build {|ii| ii.topic = "Industrial Revolution Re-enactment"}
+ i = m.interests.build { |ii| ii.topic = "Industrial Revolution Re-enactment" }
assert_not_nil i.topic, "Child attributes supplied to build via blocks should be populated"
assert_not_nil i.man
assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
@@ -357,7 +356,7 @@ class InverseHasManyTests < ActiveRecord::TestCase
def test_parent_instance_should_be_shared_with_newly_block_style_created_child
m = Man.first
- i = m.interests.create {|ii| ii.topic = "Industrial Revolution Re-enactment"}
+ i = m.interests.create { |ii| ii.topic = "Industrial Revolution Re-enactment" }
assert_not_nil i.topic, "Child attributes supplied to create via blocks should be populated"
assert_not_nil i.man
assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
@@ -511,7 +510,7 @@ class InverseBelongsToTests < ActiveRecord::TestCase
end
def test_eager_loaded_child_instance_should_be_shared_with_parent_on_find
- f = Face.all.merge!(includes: :man, where: {description: "trusting"}).first
+ f = Face.all.merge!(includes: :man, where: { description: "trusting" }).first
m = f.man
assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance"
f.description = "gormless"
@@ -519,7 +518,7 @@ class InverseBelongsToTests < ActiveRecord::TestCase
m.face.description = "pleasing"
assert_equal f.description, m.face.description, "Description of face should be the same after changes to parent-owned instance"
- f = Face.all.merge!(includes: :man, order: "men.id", where: {description: "trusting"}).first
+ f = Face.all.merge!(includes: :man, order: "men.id", where: { description: "trusting" }).first
m = f.man
assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance"
f.description = "gormless"
@@ -554,7 +553,7 @@ class InverseBelongsToTests < ActiveRecord::TestCase
i = interests(:trainspotting)
m = i.man
assert_not_nil m.interests
- iz = m.interests.detect { |_iz| _iz.id == i.id}
+ iz = m.interests.detect { |_iz| _iz.id == i.id }
assert_not_nil iz
assert_equal i.topic, iz.topic, "Interest topics should be the same before changes to child"
i.topic = "Eating cheese with a spoon"
@@ -584,7 +583,7 @@ class InversePolymorphicBelongsToTests < ActiveRecord::TestCase
fixtures :men, :faces, :interests
def test_child_instance_should_be_shared_with_parent_on_find
- f = Face.all.merge!(where: {description: "confused"}).first
+ f = Face.all.merge!(where: { description: "confused" }).first
m = f.polymorphic_man
assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same before changes to child instance"
f.description = "gormless"
@@ -594,7 +593,7 @@ class InversePolymorphicBelongsToTests < ActiveRecord::TestCase
end
def test_eager_loaded_child_instance_should_be_shared_with_parent_on_find
- f = Face.all.merge!(where: {description: "confused"}, includes: :man).first
+ f = Face.all.merge!(where: { description: "confused" }, includes: :man).first
m = f.polymorphic_man
assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same before changes to child instance"
f.description = "gormless"
@@ -602,7 +601,7 @@ class InversePolymorphicBelongsToTests < ActiveRecord::TestCase
m.polymorphic_face.description = "pleasing"
assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same after changes to parent-owned instance"
- f = Face.all.merge!(where: {description: "confused"}, includes: :man, order: "men.id").first
+ f = Face.all.merge!(where: { description: "confused" }, includes: :man, order: "men.id").first
m = f.polymorphic_man
assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same before changes to child instance"
f.description = "gormless"
@@ -655,7 +654,7 @@ class InversePolymorphicBelongsToTests < ActiveRecord::TestCase
i = interests(:llama_wrangling)
m = i.polymorphic_man
assert_not_nil m.polymorphic_interests
- iz = m.polymorphic_interests.detect { |_iz| _iz.id == i.id}
+ iz = m.polymorphic_interests.detect { |_iz| _iz.id == i.id }
assert_not_nil iz
assert_equal i.topic, iz.topic, "Interest topics should be the same before changes to child"
i.topic = "Eating cheese with a spoon"
diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb
index 7d67c289ff..61678ae210 100644
--- a/activerecord/test/cases/associations/join_model_test.rb
+++ b/activerecord/test/cases/associations/join_model_test.rb
@@ -237,7 +237,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
category = categories(:sti_test)
ernie = category.authors_with_select.create(name: "Ernie")
assert_nothing_raised do
- assert_equal ernie, category.authors_with_select.detect {|a| a.name == "Ernie"}
+ assert_equal ernie, category.authors_with_select.detect { |a| a.name == "Ernie" }
end
end
@@ -472,7 +472,6 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
assert new_tag.persisted?
assert saved_post.reload.tags.reload.include?(new_tag)
-
new_post = Post.new(title: "Association replacement works!", body: "You best believe it.")
saved_tag = tags(:general)
@@ -643,7 +642,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
def test_polymorphic_has_many
expected = taggings(:welcome_general)
p = Post.all.merge!(includes: :taggings).find(posts(:welcome).id)
- assert_no_queries {assert p.taggings.include?(expected)}
+ assert_no_queries { assert p.taggings.include?(expected) }
assert posts(:welcome).taggings.include?(taggings(:welcome_general))
end
@@ -651,12 +650,12 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
expected = posts(:welcome)
tagging = Tagging.all.merge!(includes: :taggable).find(taggings(:welcome_general).id)
- assert_no_queries { assert_equal expected, tagging.taggable}
+ assert_no_queries { assert_equal expected, tagging.taggable }
end
def test_polymorphic_belongs_to
- p = Post.all.merge!(includes: {taggings: :taggable}).find(posts(:welcome).id)
- assert_no_queries {assert_equal posts(:welcome), p.taggings.first.taggable}
+ p = Post.all.merge!(includes: { taggings: :taggable }).find(posts(:welcome).id)
+ assert_no_queries { assert_equal posts(:welcome), p.taggings.first.taggable }
end
def test_preload_polymorphic_has_many_through
@@ -749,17 +748,17 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
def test_proper_error_message_for_eager_load_and_includes_association_errors
includes_error = assert_raises(ActiveRecord::ConfigurationError) {
- Post.includes(:nonexistent_relation).where(nonexistent_relation: {name: "Rochester"}).find(1)
+ Post.includes(:nonexistent_relation).where(nonexistent_relation: { name: "Rochester" }).find(1)
}
assert_equal("Can't join 'Post' to association named 'nonexistent_relation'; perhaps you misspelled it?", includes_error.message)
eager_load_error = assert_raises(ActiveRecord::ConfigurationError) {
- Post.eager_load(:nonexistent_relation).where(nonexistent_relation: {name: "Rochester"}).find(1)
+ Post.eager_load(:nonexistent_relation).where(nonexistent_relation: { name: "Rochester" }).find(1)
}
assert_equal("Can't join 'Post' to association named 'nonexistent_relation'; perhaps you misspelled it?", eager_load_error.message)
includes_and_eager_load_error = assert_raises(ActiveRecord::ConfigurationError) {
- Post.eager_load(:nonexistent_relation).includes(:nonexistent_relation).where(nonexistent_relation: {name: "Rochester"}).find(1)
+ Post.eager_load(:nonexistent_relation).includes(:nonexistent_relation).where(nonexistent_relation: { name: "Rochester" }).find(1)
}
assert_equal("Can't join 'Post' to association named 'nonexistent_relation'; perhaps you misspelled it?", includes_and_eager_load_error.message)
end
diff --git a/activerecord/test/cases/associations/left_outer_join_association_test.rb b/activerecord/test/cases/associations/left_outer_join_association_test.rb
index 003240bb26..2cc6468827 100644
--- a/activerecord/test/cases/associations/left_outer_join_association_test.rb
+++ b/activerecord/test/cases/associations/left_outer_join_association_test.rb
@@ -18,35 +18,44 @@ class LeftOuterJoinAssociationTest < ActiveRecord::TestCase
def test_construct_finder_sql_does_not_table_name_collide_on_duplicate_associations
assert_nothing_raised do
queries = capture_sql do
- Person.left_outer_joins(agents: {agents: :agents})
- .left_outer_joins(agents: {agents: {primary_contact: :agents}}).to_a
+ Person.left_outer_joins(agents: { agents: :agents })
+ .left_outer_joins(agents: { agents: { primary_contact: :agents } }).to_a
end
assert queries.any? { |sql| /agents_people_4/i.match?(sql) }
end
end
- def test_construct_finder_sql_executes_a_left_outer_join
- assert_not_equal Author.count, Author.joins(:posts).count
- assert_equal Author.count, Author.left_outer_joins(:posts).count
+ def test_left_outer_joins_count_is_same_as_size_of_loaded_results
+ assert_equal 17, Post.left_outer_joins(:comments).to_a.size
+ assert_equal 17, Post.left_outer_joins(:comments).count
end
- def test_left_outer_join_by_left_joins
- assert_not_equal Author.count, Author.joins(:posts).count
- assert_equal Author.count, Author.left_joins(:posts).count
+ def test_left_joins_aliases_left_outer_joins
+ assert_equal Post.left_outer_joins(:comments).to_sql, Post.left_joins(:comments).to_sql
+ end
+
+ def test_left_outer_joins_return_has_value_for_every_comment
+ all_post_ids = Post.pluck(:id)
+ assert_equal all_post_ids, all_post_ids & Post.left_outer_joins(:comments).pluck(:id)
+ end
+
+ def test_left_outer_joins_actually_does_a_left_outer_join
+ queries = capture_sql { Author.left_outer_joins(:posts).to_a }
+ assert queries.any? { |sql| /LEFT OUTER JOIN/i.match?(sql) }
end
def test_construct_finder_sql_ignores_empty_left_outer_joins_hash
- queries = capture_sql { Author.left_outer_joins({}) }
+ queries = capture_sql { Author.left_outer_joins({}).to_a }
assert queries.none? { |sql| /LEFT OUTER JOIN/i.match?(sql) }
end
def test_construct_finder_sql_ignores_empty_left_outer_joins_array
- queries = capture_sql { Author.left_outer_joins([]) }
+ queries = capture_sql { Author.left_outer_joins([]).to_a }
assert queries.none? { |sql| /LEFT OUTER JOIN/i.match?(sql) }
end
def test_left_outer_joins_forbids_to_use_string_as_argument
- assert_raise(ArgumentError){ Author.left_outer_joins('LEFT OUTER JOIN "posts" ON "posts"."user_id" = "users"."id"').to_a }
+ assert_raise(ArgumentError) { Author.left_outer_joins('LEFT OUTER JOIN "posts" ON "posts"."user_id" = "users"."id"').to_a }
end
def test_join_conditions_added_to_join_clause
diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb
index 3ff9a625b2..5222703570 100644
--- a/activerecord/test/cases/associations_test.rb
+++ b/activerecord/test/cases/associations_test.rb
@@ -56,10 +56,9 @@ class AssociationsTest < ActiveRecord::TestCase
assert_equal "Deck", ship.parts[0].name
end
-
def test_include_with_order_works
- assert_nothing_raised {Account.all.merge!(order: "id", includes: :firm).first}
- assert_nothing_raised {Account.all.merge!(order: :id, includes: :firm).first}
+ assert_nothing_raised { Account.all.merge!(order: "id", includes: :firm).first }
+ assert_nothing_raised { Account.all.merge!(order: :id, includes: :firm).first }
end
def test_bad_collection_keys
@@ -200,13 +199,13 @@ class AssociationProxyTest < ActiveRecord::TestCase
end
def test_create_via_association_with_block
- post = authors(:david).posts.create(title: "New on Edge") {|p| p.body = "More cool stuff!"}
+ post = authors(:david).posts.create(title: "New on Edge") { |p| p.body = "More cool stuff!" }
assert_equal post.title, "New on Edge"
assert_equal post.body, "More cool stuff!"
end
def test_create_with_bang_via_association_with_block
- post = authors(:david).posts.create!(title: "New on Edge") {|p| p.body = "More cool stuff!"}
+ post = authors(:david).posts.create!(title: "New on Edge") { |p| p.body = "More cool stuff!" }
assert_equal post.title, "New on Edge"
assert_equal post.body, "More cool stuff!"
end
@@ -257,6 +256,13 @@ class AssociationProxyTest < ActiveRecord::TestCase
assert_no_queries { david.posts.first! }
end
+ def test_pluck_uses_loaded_target
+ david = authors(:david)
+ assert_equal david.posts.pluck(:title), david.posts.load.pluck(:title)
+ assert david.posts.loaded?
+ assert_no_queries { david.posts.pluck(:title) }
+ end
+
def test_reset_unloads_target
david = authors(:david)
david.posts.reload
diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb
index ae5127cc56..7eae2363f8 100644
--- a/activerecord/test/cases/autosave_association_test.rb
+++ b/activerecord/test/cases/autosave_association_test.rb
@@ -196,21 +196,21 @@ class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCas
end
def test_callbacks_firing_order_on_create
- eye = Eye.create(iris_attributes: {color: "honey"})
+ eye = Eye.create(iris_attributes: { color: "honey" })
assert_equal [true, false], eye.after_create_callbacks_stack
end
def test_callbacks_firing_order_on_update
- eye = Eye.create(iris_attributes: {color: "honey"})
- eye.update(iris_attributes: {color: "green"})
+ eye = Eye.create(iris_attributes: { color: "honey" })
+ eye.update(iris_attributes: { color: "green" })
assert_equal [true, false], eye.after_update_callbacks_stack
end
def test_callbacks_firing_order_on_save
- eye = Eye.create(iris_attributes: {color: "honey"})
+ eye = Eye.create(iris_attributes: { color: "honey" })
assert_equal [false, false], eye.after_save_callbacks_stack
- eye.update(iris_attributes: {color: "blue"})
+ eye.update(iris_attributes: { color: "blue" })
assert_equal [false, false, false, false], eye.after_save_callbacks_stack
end
end
@@ -443,7 +443,7 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociationWithAcceptsNestedAttrib
assert_not invalid_electron.valid?
assert valid_electron.valid?
assert_not molecule.valid?
- assert_equal [{error: :blank}], molecule.errors.details["electrons.name"]
+ assert_equal [{ error: :blank }], molecule.errors.details["electrons.name"]
end
def test_errors_details_should_be_indexed_when_passed_as_array
@@ -457,7 +457,7 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociationWithAcceptsNestedAttrib
assert_not tuning_peg_invalid.valid?
assert tuning_peg_valid.valid?
assert_not guitar.valid?
- assert_equal [{error: :not_a_number, value: nil}] , guitar.errors.details["tuning_pegs[1].pitch"]
+ assert_equal [{ error: :not_a_number, value: nil }] , guitar.errors.details["tuning_pegs[1].pitch"]
assert_equal [], guitar.errors.details["tuning_pegs.pitch"]
end
@@ -474,7 +474,7 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociationWithAcceptsNestedAttrib
assert_not invalid_electron.valid?
assert valid_electron.valid?
assert_not molecule.valid?
- assert_equal [{error: :blank}], molecule.errors.details["electrons[1].name"]
+ assert_equal [{ error: :blank }], molecule.errors.details["electrons[1].name"]
assert_equal [], molecule.errors.details["electrons.name"]
ensure
ActiveRecord::Base.index_nested_attribute_errors = old_attribute_config
@@ -610,7 +610,7 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCa
def test_build_many_before_save
company = companies(:first_firm)
- assert_no_queries(ignore_none: false) { company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) }
+ assert_no_queries(ignore_none: false) { company.clients_of_firm.build([{ "name" => "Another Client" }, { "name" => "Another Client II" }]) }
company.name += "-changed"
assert_queries(3) { assert company.save }
@@ -619,7 +619,7 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCa
def test_build_via_block_before_save
company = companies(:first_firm)
- new_client = assert_no_queries(ignore_none: false) { company.clients_of_firm.build {|client| client.name = "Another Client" } }
+ new_client = assert_no_queries(ignore_none: false) { company.clients_of_firm.build { |client| client.name = "Another Client" } }
assert !company.clients_of_firm.loaded?
company.name += "-changed"
@@ -631,7 +631,7 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCa
def test_build_many_via_block_before_save
company = companies(:first_firm)
assert_no_queries(ignore_none: false) do
- company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) do |client|
+ company.clients_of_firm.build([{ "name" => "Another Client" }, { "name" => "Another Client II" }]) do |client|
client.name = "changed"
end
end
@@ -1407,9 +1407,9 @@ module AutosaveAssociationOnACollectionAssociationTests
end
def test_should_default_invalid_error_from_i18n
- I18n.backend.store_translations(:en, activerecord: {errors: { models:
+ I18n.backend.store_translations(:en, activerecord: { errors: { models:
{ @associated_model_name.to_s.to_sym => { blank: "cannot be blank" } }
- }})
+ } })
@pirate.send(@association_name).build(name: "")
diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb
index 73ca83f21b..c03c3f9546 100644
--- a/activerecord/test/cases/base_test.rb
+++ b/activerecord/test/cases/base_test.rb
@@ -115,6 +115,13 @@ class BasicsTest < ActiveRecord::TestCase
end
end
+ def test_many_mutations
+ car = Car.new name: "<3<3<3"
+ car.engines_count = 0
+ 20_000.times { car.engines_count += 1 }
+ assert car.save
+ end
+
def test_limit_without_comma
assert_equal 1, Topic.limit("1").to_a.length
assert_equal 1, Topic.limit(1).to_a.length
@@ -279,7 +286,8 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_initialize_with_attributes
- topic = Topic.new( "title" => "initialized from attributes", "written_on" => "2003-12-12 23:23")
+ topic = Topic.new(
+ "title" => "initialized from attributes", "written_on" => "2003-12-12 23:23")
assert_equal("initialized from attributes", topic.title)
end
@@ -299,7 +307,7 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_create_after_initialize_with_block
- cb = CustomBulb.create {|c| c.name = "Dude" }
+ cb = CustomBulb.create { |c| c.name = "Dude" }
assert_equal("Dude", cb.name)
assert_equal(true, cb.frickinawesome)
end
@@ -656,7 +664,7 @@ class BasicsTest < ActiveRecord::TestCase
Weird.reset_column_information
- assert_equal ["EUC-JP"], Weird.columns.map {|c| c.name.encoding.name }.uniq
+ assert_equal ["EUC-JP"], Weird.columns.map { |c| c.name.encoding.name }.uniq
ensure
silence_warnings { Encoding.default_internal = old_default_internal }
Weird.reset_column_information
@@ -1270,7 +1278,7 @@ class BasicsTest < ActiveRecord::TestCase
ActiveSupport::Dependencies.remove_unloadable_constants!
assert_nil ActiveRecord::Scoping::ScopeRegistry.value_for(:current_scope, klass)
ensure
- Object.class_eval{ remove_const :UnloadablePost } if defined?(UnloadablePost)
+ Object.class_eval { remove_const :UnloadablePost } if defined?(UnloadablePost)
end
def test_marshal_round_trip
diff --git a/activerecord/test/cases/batches_test.rb b/activerecord/test/cases/batches_test.rb
index 077e6d0bc0..f7e21faf0f 100644
--- a/activerecord/test/cases/batches_test.rb
+++ b/activerecord/test/cases/batches_test.rb
@@ -21,7 +21,7 @@ class EachTest < ActiveRecord::TestCase
def test_each_should_not_return_query_chain_and_execute_only_one_query
assert_queries(1) do
- result = Post.find_each(batch_size: 100000){ }
+ result = Post.find_each(batch_size: 100000) {}
assert_nil result
end
end
@@ -135,11 +135,11 @@ class EachTest < ActiveRecord::TestCase
def test_find_in_batches_shouldnt_execute_query_unless_needed
assert_queries(2) do
- Post.find_in_batches(batch_size: @total) {|batch| assert_kind_of Array, batch }
+ Post.find_in_batches(batch_size: @total) { |batch| assert_kind_of Array, batch }
end
assert_queries(1) do
- Post.find_in_batches(batch_size: @total + 1) {|batch| assert_kind_of Array, batch }
+ Post.find_in_batches(batch_size: @total + 1) { |batch| assert_kind_of Array, batch }
end
end
@@ -156,7 +156,7 @@ class EachTest < ActiveRecord::TestCase
def test_find_in_batches_should_not_use_records_after_yielding_them_in_case_original_array_is_modified
not_a_post = "not a post"
def not_a_post.id; end
- not_a_post.stub(:id, ->{ raise StandardError.new("not_a_post had #id called on it") }) do
+ not_a_post.stub(:id, -> { raise StandardError.new("not_a_post had #id called on it") }) do
assert_nothing_raised do
Post.find_in_batches(batch_size: 1) do |batch|
assert_kind_of Array, batch
@@ -182,7 +182,7 @@ class EachTest < ActiveRecord::TestCase
def test_find_in_batches_should_error_on_ignore_the_order
assert_raise(ArgumentError) do
- PostWithDefaultScope.find_in_batches(error_on_ignore: true){}
+ PostWithDefaultScope.find_in_batches(error_on_ignore: true) {}
end
end
@@ -191,7 +191,7 @@ class EachTest < ActiveRecord::TestCase
prev = ActiveRecord::Base.error_on_ignored_order
ActiveRecord::Base.error_on_ignored_order = true
assert_nothing_raised do
- PostWithDefaultScope.find_in_batches(error_on_ignore: false){}
+ PostWithDefaultScope.find_in_batches(error_on_ignore: false) {}
end
ensure
# Set back to default
@@ -203,7 +203,7 @@ class EachTest < ActiveRecord::TestCase
prev = ActiveRecord::Base.error_on_ignored_order
ActiveRecord::Base.error_on_ignored_order = true
assert_raise(ArgumentError) do
- PostWithDefaultScope.find_in_batches(){}
+ PostWithDefaultScope.find_in_batches() {}
end
ensure
# Set back to default
@@ -212,7 +212,7 @@ class EachTest < ActiveRecord::TestCase
def test_find_in_batches_should_not_error_by_default
assert_nothing_raised do
- PostWithDefaultScope.find_in_batches(){}
+ PostWithDefaultScope.find_in_batches() {}
end
end
@@ -227,7 +227,7 @@ class EachTest < ActiveRecord::TestCase
def test_find_in_batches_should_not_modify_passed_options
assert_nothing_raised do
- Post.find_in_batches({ batch_size: 42, start: 1 }.freeze){}
+ Post.find_in_batches({ batch_size: 42, start: 1 }.freeze) {}
end
end
@@ -445,7 +445,7 @@ class EachTest < ActiveRecord::TestCase
def test_in_batches_should_not_modify_passed_options
assert_nothing_raised do
- Post.in_batches({ of: 42, start: 1 }.freeze){}
+ Post.in_batches({ of: 42, start: 1 }.freeze) {}
end
end
diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb
index 13f9a47980..bacf93d275 100644
--- a/activerecord/test/cases/calculations_test.rb
+++ b/activerecord/test/cases/calculations_test.rb
@@ -381,7 +381,7 @@ class CalculationsTest < ActiveRecord::TestCase
end
def test_should_perform_joined_include_when_referencing_included_tables
- joined_count = Account.includes(:firm).where(companies: {name: "37signals"}).count
+ joined_count = Account.includes(:firm).where(companies: { name: "37signals" }).count
assert_equal 1, joined_count
end
@@ -604,7 +604,7 @@ class CalculationsTest < ActiveRecord::TestCase
def test_pluck_with_serialization
t = Topic.create!(content: { foo: :bar })
- assert_equal [{foo: :bar}], Topic.where(id: t.id).pluck(:content)
+ assert_equal [{ foo: :bar }], Topic.where(id: t.id).pluck(:content)
end
def test_pluck_with_qualified_column_name
diff --git a/activerecord/test/cases/callbacks_test.rb b/activerecord/test/cases/callbacks_test.rb
index 51bf51b28d..4b517e9d70 100644
--- a/activerecord/test/cases/callbacks_test.rb
+++ b/activerecord/test/cases/callbacks_test.rb
@@ -16,7 +16,7 @@ class CallbackDeveloper < ActiveRecord::Base
def define_callback_method(callback_method)
define_method(callback_method) do
- self.history << [callback_method, :method]
+ history << [callback_method, :method]
end
send(callback_method, :"#{callback_method}")
end
@@ -57,7 +57,7 @@ end
class ParentDeveloper < ActiveRecord::Base
self.table_name = "developers"
attr_accessor :after_save_called
- before_validation {|record| record.after_save_called = true}
+ before_validation { |record| record.after_save_called = true }
end
class ChildDeveloper < ParentDeveloper
@@ -95,16 +95,16 @@ class OnCallbacksDeveloper < ActiveRecord::Base
self.table_name = "developers"
before_validation { history << :before_validation }
- before_validation(on: :create){ history << :before_validation_on_create }
- before_validation(on: :update){ history << :before_validation_on_update }
+ before_validation(on: :create) { history << :before_validation_on_create }
+ before_validation(on: :update) { history << :before_validation_on_update }
validate do
history << :validate
end
after_validation { history << :after_validation }
- after_validation(on: :create){ history << :after_validation_on_create }
- after_validation(on: :update){ history << :after_validation_on_update }
+ after_validation(on: :create) { history << :after_validation_on_create }
+ after_validation(on: :update) { history << :after_validation_on_update }
def history
@history ||= []
@@ -143,7 +143,7 @@ class CallbackCancellationDeveloper < ActiveRecord::Base
attr_reader :after_save_called, :after_create_called, :after_update_called, :after_destroy_called
attr_accessor :cancel_before_save, :cancel_before_create, :cancel_before_update, :cancel_before_destroy
- before_save {defined?(@cancel_before_save) ? !@cancel_before_save : false}
+ before_save { defined?(@cancel_before_save) ? !@cancel_before_save : false }
before_create { !@cancel_before_create }
before_update { !@cancel_before_update }
before_destroy { !@cancel_before_destroy }
diff --git a/activerecord/test/cases/column_alias_test.rb b/activerecord/test/cases/column_alias_test.rb
index ae64c99f33..9893ba9580 100644
--- a/activerecord/test/cases/column_alias_test.rb
+++ b/activerecord/test/cases/column_alias_test.rb
@@ -6,9 +6,9 @@ class TestColumnAlias < ActiveRecord::TestCase
QUERY = if "Oracle" == ActiveRecord::Base.connection.adapter_name
"SELECT id AS pk FROM topics WHERE ROWNUM < 2"
- else
- "SELECT id AS pk FROM topics"
- end
+ else
+ "SELECT id AS pk FROM topics"
+ end
def test_column_alias
records = Topic.connection.select_all(QUERY)
diff --git a/activerecord/test/cases/column_definition_test.rb b/activerecord/test/cases/column_definition_test.rb
index 31e618664f..989beaa5c8 100644
--- a/activerecord/test/cases/column_definition_test.rb
+++ b/activerecord/test/cases/column_definition_test.rb
@@ -6,7 +6,7 @@ module ActiveRecord
def setup
@adapter = AbstractAdapter.new(nil)
def @adapter.native_database_types
- {string: "varchar"}
+ { string: "varchar" }
end
@viz = @adapter.schema_creation
end
diff --git a/activerecord/test/cases/connection_adapters/connection_handler_test.rb b/activerecord/test/cases/connection_adapters/connection_handler_test.rb
index d9bcc0c130..d5d16e7568 100644
--- a/activerecord/test/cases/connection_adapters/connection_handler_test.rb
+++ b/activerecord/test/cases/connection_adapters/connection_handler_test.rb
@@ -10,7 +10,7 @@ module ActiveRecord
end
def test_establish_connection_uses_spec_name
- config = {"readonly" => {"adapter" => "sqlite3"}}
+ config = { "readonly" => { "adapter" => "sqlite3" } }
resolver = ConnectionAdapters::ConnectionSpecification::Resolver.new(config)
spec = resolver.spec(:readonly)
@handler.establish_connection(spec.to_hash)
diff --git a/activerecord/test/cases/connection_adapters/merge_and_resolve_default_url_config_test.rb b/activerecord/test/cases/connection_adapters/merge_and_resolve_default_url_config_test.rb
index b1ba6f11f2..4bb5c4f2e2 100644
--- a/activerecord/test/cases/connection_adapters/merge_and_resolve_default_url_config_test.rb
+++ b/activerecord/test/cases/connection_adapters/merge_and_resolve_default_url_config_test.rb
@@ -224,7 +224,7 @@ module ActiveRecord
def test_merge_no_conflicts_with_database_url
ENV["DATABASE_URL"] = "postgres://localhost/foo"
- config = {"default_env" => { "pool" => "5" } }
+ config = { "default_env" => { "pool" => "5" } }
actual = resolve_config(config)
expected = { "default_env" =>
{ "adapter" => "postgresql",
@@ -239,7 +239,7 @@ module ActiveRecord
def test_merge_conflicts_with_database_url
ENV["DATABASE_URL"] = "postgres://localhost/foo"
- config = {"default_env" => { "adapter" => "NOT-POSTGRES", "database" => "NOT-FOO", "pool" => "5" } }
+ config = { "default_env" => { "adapter" => "NOT-POSTGRES", "database" => "NOT-FOO", "pool" => "5" } }
actual = resolve_config(config)
expected = { "default_env" =>
{ "adapter" => "postgresql",
diff --git a/activerecord/test/cases/connection_management_test.rb b/activerecord/test/cases/connection_management_test.rb
index 88620f9f09..d1e946d401 100644
--- a/activerecord/test/cases/connection_management_test.rb
+++ b/activerecord/test/cases/connection_management_test.rb
@@ -104,7 +104,7 @@ module ActiveRecord
def middleware(app)
lambda do |env|
a, b, c = executor.wrap { app.call(env) }
- [a, b, Rack::BodyProxy.new(c) { }]
+ [a, b, Rack::BodyProxy.new(c) {}]
end
end
end
diff --git a/activerecord/test/cases/connection_specification/resolver_test.rb b/activerecord/test/cases/connection_specification/resolver_test.rb
index 4bfec47124..0f62c73f8f 100644
--- a/activerecord/test/cases/connection_specification/resolver_test.rb
+++ b/activerecord/test/cases/connection_specification/resolver_test.rb
@@ -29,27 +29,27 @@ module ActiveRecord
"adapter" => "abstract",
"host" => "foo",
"encoding" => "utf8",
- "name" => "production"}, spec)
+ "name" => "production" }, spec)
end
def test_url_sub_key
- spec = resolve :production, "production" => {"url" => "abstract://foo?encoding=utf8"}
+ spec = resolve :production, "production" => { "url" => "abstract://foo?encoding=utf8" }
assert_equal({
"adapter" => "abstract",
"host" => "foo",
"encoding" => "utf8",
- "name" => "production"}, spec)
+ "name" => "production" }, spec)
end
def test_url_sub_key_merges_correctly
- hash = {"url" => "abstract://foo?encoding=utf8&", "adapter" => "sqlite3", "host" => "bar", "pool" => "3"}
+ hash = { "url" => "abstract://foo?encoding=utf8&", "adapter" => "sqlite3", "host" => "bar", "pool" => "3" }
spec = resolve :production, "production" => hash
assert_equal({
"adapter" => "abstract",
"host" => "foo",
"encoding" => "utf8",
"pool" => "3",
- "name" => "production"}, spec)
+ "name" => "production" }, spec)
end
def test_url_host_no_db
@@ -112,16 +112,16 @@ module ActiveRecord
end
def test_url_sub_key_for_sqlite3
- spec = resolve :production, "production" => {"url" => "sqlite3:foo?encoding=utf8"}
+ spec = resolve :production, "production" => { "url" => "sqlite3:foo?encoding=utf8" }
assert_equal({
"adapter" => "sqlite3",
"database" => "foo",
"encoding" => "utf8",
- "name" => "production"}, spec)
+ "name" => "production" }, spec)
end
def test_spec_name_on_key_lookup
- spec = spec(:readonly, "readonly" => {"adapter" => "sqlite3"})
+ spec = spec(:readonly, "readonly" => { "adapter" => "sqlite3" })
assert_equal "readonly", spec.name
end
diff --git a/activerecord/test/cases/database_statements_test.rb b/activerecord/test/cases/database_statements_test.rb
index ac9912d4d1..bb16076fd2 100644
--- a/activerecord/test/cases/database_statements_test.rb
+++ b/activerecord/test/cases/database_statements_test.rb
@@ -5,6 +5,13 @@ class DatabaseStatementsTest < ActiveRecord::TestCase
@connection = ActiveRecord::Base.connection
end
+ unless current_adapter?(:OracleAdapter)
+ def test_exec_insert
+ result = @connection.exec_insert("INSERT INTO accounts (firm_id,credit_limit) VALUES (42,5000)", nil, [])
+ assert_not_nil @connection.send(:last_inserted_id, result)
+ end
+ end
+
def test_insert_should_return_the_inserted_id
assert_not_nil return_the_inserted_id(method: :insert)
end
diff --git a/activerecord/test/cases/dirty_test.rb b/activerecord/test/cases/dirty_test.rb
index 417383211d..6a7d333766 100644
--- a/activerecord/test/cases/dirty_test.rb
+++ b/activerecord/test/cases/dirty_test.rb
@@ -134,7 +134,6 @@ class DirtyTest < ActiveRecord::TestCase
end
end
-
def test_aliased_attribute_changes
# the actual attribute here is name, title is an
# alias setup via alias_attribute
@@ -281,7 +280,7 @@ class DirtyTest < ActiveRecord::TestCase
assert pirate.changed?
assert_nil pirate.catchphrase_was
assert_equal %w(catchphrase), pirate.changed
- assert_equal({"catchphrase" => [nil, "arrr"]}, pirate.changes)
+ assert_equal({ "catchphrase" => [nil, "arrr"] }, pirate.changes)
pirate.save
assert !pirate.changed?
@@ -315,7 +314,7 @@ class DirtyTest < ActiveRecord::TestCase
assert !topic.approved_changed?
# Coming from web form.
- params = {topic: {approved: 1}}
+ params = { topic: { approved: 1 } }
# In the controller.
topic.attributes = params[:topic]
assert topic.approved?
@@ -408,7 +407,6 @@ class DirtyTest < ActiveRecord::TestCase
assert !pirate.changed?
end
-
def test_reverted_changes_are_not_dirty_going_from_nil_to_value_and_back
pirate = Pirate.create!(catchphrase: "Yar!")
@@ -425,7 +423,7 @@ class DirtyTest < ActiveRecord::TestCase
def test_save_should_store_serialized_attributes_even_with_partial_writes
with_partial_writes(Topic) do
- topic = Topic.create!(content: {a: "a"})
+ topic = Topic.create!(content: { a: "a" })
assert_not topic.changed?
@@ -446,7 +444,7 @@ class DirtyTest < ActiveRecord::TestCase
def test_save_always_should_update_timestamps_when_serialized_attributes_are_present
with_partial_writes(Topic) do
- topic = Topic.create!(content: {a: "a"})
+ topic = Topic.create!(content: { a: "a" })
topic.save!
updated_at = topic.updated_at
@@ -462,7 +460,7 @@ class DirtyTest < ActiveRecord::TestCase
def test_save_should_not_save_serialized_attribute_with_partial_writes_if_not_present
with_partial_writes(Topic) do
- Topic.create!(author_name: "Bill", content: {a: "a"})
+ Topic.create!(author_name: "Bill", content: { a: "a" })
topic = Topic.select("id, author_name").first
topic.update_columns author_name: "John"
topic = Topic.first
diff --git a/activerecord/test/cases/explain_test.rb b/activerecord/test/cases/explain_test.rb
index 43f1d401dd..86fe90ae51 100644
--- a/activerecord/test/cases/explain_test.rb
+++ b/activerecord/test/cases/explain_test.rb
@@ -40,7 +40,7 @@ if ActiveRecord::Base.connection.supports_explain?
queries = sqls.zip(binds)
stub_explain_for_query_plans do
- expected = sqls.map {|sql| "EXPLAIN for: #{sql}\nquery plan #{sql}"}.join("\n")
+ expected = sqls.map { |sql| "EXPLAIN for: #{sql}\nquery plan #{sql}" }.join("\n")
assert_equal expected, base.exec_explain(queries)
end
end
@@ -75,7 +75,7 @@ if ActiveRecord::Base.connection.supports_explain?
def stub_explain_for_query_plans(query_plans = ["query plan foo", "query plan bar"])
explain_called = 0
- connection.stub(:explain, proc{ explain_called += 1; query_plans[explain_called - 1] }) do
+ connection.stub(:explain, proc { explain_called += 1; query_plans[explain_called - 1] }) do
yield
end
end
diff --git a/activerecord/test/cases/finder_respond_to_test.rb b/activerecord/test/cases/finder_respond_to_test.rb
index a7af8ac0ea..3eaa993d45 100644
--- a/activerecord/test/cases/finder_respond_to_test.rb
+++ b/activerecord/test/cases/finder_respond_to_test.rb
@@ -10,7 +10,7 @@ class FinderRespondToTest < ActiveRecord::TestCase
end
def test_should_preserve_normal_respond_to_behaviour_and_respond_to_newly_added_method
- class << Topic; self; end.send(:define_method, :method_added_for_finder_respond_to_test) { }
+ class << Topic; self; end.send(:define_method, :method_added_for_finder_respond_to_test) {}
assert_respond_to Topic, :method_added_for_finder_respond_to_test
ensure
class << Topic; self; end.send(:remove_method, :method_added_for_finder_respond_to_test)
diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb
index 64251c5d11..31bc4fa1f2 100644
--- a/activerecord/test/cases/finder_test.rb
+++ b/activerecord/test/cases/finder_test.rb
@@ -22,13 +22,13 @@ class FinderTest < ActiveRecord::TestCase
fixtures :companies, :topics, :entrants, :developers, :developers_projects, :posts, :comments, :accounts, :authors, :author_addresses, :customers, :categories, :categorizations, :cars
def test_find_by_id_with_hash
- assert_raises(ActiveRecord::StatementInvalid) do
+ assert_nothing_raised do
Post.find_by_id(limit: 1)
end
end
def test_find_by_title_and_id_with_hash
- assert_raises(ActiveRecord::StatementInvalid) do
+ assert_nothing_raised do
Post.find_by_title_and_id("foo", limit: 1)
end
end
@@ -127,7 +127,7 @@ class FinderTest < ActiveRecord::TestCase
gc_disabled = GC.disable
Post.where("author_id" => nil) # warm up
x = Symbol.all_symbols.count
- Post.where("title" => {"xxxqqqq" => "bar"})
+ Post.where("title" => { "xxxqqqq" => "bar" })
assert_equal x, Symbol.all_symbols.count
ensure
GC.enable if gc_disabled == false
@@ -562,9 +562,9 @@ class FinderTest < ActiveRecord::TestCase
end
def test_take_and_first_and_last_with_integer_should_use_sql_limit
- assert_sql(/LIMIT|ROWNUM <=/) { Topic.take(3).entries }
- assert_sql(/LIMIT|ROWNUM <=/) { Topic.first(2).entries }
- assert_sql(/LIMIT|ROWNUM <=/) { Topic.last(5).entries }
+ assert_sql(/LIMIT|ROWNUM <=|FETCH FIRST/) { Topic.take(3).entries }
+ assert_sql(/LIMIT|ROWNUM <=|FETCH FIRST/) { Topic.first(2).entries }
+ assert_sql(/LIMIT|ROWNUM <=|FETCH FIRST/) { Topic.last(5).entries }
end
def test_last_with_integer_and_order_should_keep_the_order
@@ -627,8 +627,8 @@ class FinderTest < ActiveRecord::TestCase
def test_find_only_some_columns
topic = Topic.select("author_name").find(1)
- assert_raise(ActiveModel::MissingAttributeError) {topic.title}
- assert_raise(ActiveModel::MissingAttributeError) {topic.title?}
+ assert_raise(ActiveModel::MissingAttributeError) { topic.title }
+ assert_raise(ActiveModel::MissingAttributeError) { topic.title? }
assert_nil topic.read_attribute("title")
assert_equal "David", topic.author_name
assert !topic.attribute_present?("title")
@@ -864,7 +864,7 @@ class FinderTest < ActiveRecord::TestCase
def test_named_bind_variables_with_quotes
Company.create("name" => "37signals' go'es agains")
- assert Company.where(["name = :name", {name: "37signals' go'es agains"}]).first
+ assert Company.where(["name = :name", { name: "37signals' go'es agains" }]).first
end
def test_named_bind_variables
@@ -874,11 +874,6 @@ class FinderTest < ActiveRecord::TestCase
assert_kind_of Time, Topic.where(["id = :id", { id: 1 }]).first.written_on
end
- def test_string_sanitation
- assert_not_equal "'something ' 1=1'", ActiveRecord::Base.sanitize("something ' 1=1")
- assert_equal "'something; select table'", ActiveRecord::Base.sanitize("something; select table")
- end
-
def test_count_by_sql
assert_equal(0, Entrant.count_by_sql("SELECT COUNT(*) FROM entrants WHERE id > 3"))
assert_equal(1, Entrant.count_by_sql(["SELECT COUNT(*) FROM entrants WHERE id > ?", 2]))
@@ -1075,9 +1070,9 @@ class FinderTest < ActiveRecord::TestCase
[["1", "1", nil, "37signals"],
["2", "1", "2", "Summit"],
["3", "1", "1", "Microsoft"]],
- Company.connection.select_rows("SELECT id, firm_id, client_of, name FROM companies WHERE id IN (1,2,3) ORDER BY id").map! {|i| i.map! {|j| j.to_s unless j.nil?}})
+ Company.connection.select_rows("SELECT id, firm_id, client_of, name FROM companies WHERE id IN (1,2,3) ORDER BY id").map! { |i| i.map! { |j| j.to_s unless j.nil? } })
assert_equal [["1", "37signals"], ["2", "Summit"], ["3", "Microsoft"]],
- Company.connection.select_rows("SELECT id, name FROM companies WHERE id IN (1,2,3) ORDER BY id").map! {|i| i.map! {|j| j.to_s unless j.nil?}}
+ Company.connection.select_rows("SELECT id, name FROM companies WHERE id IN (1,2,3) ORDER BY id").map! { |i| i.map! { |j| j.to_s unless j.nil? } }
end
def test_find_with_order_on_included_associations_with_construct_finder_sql_for_association_limiting_and_is_distinct
@@ -1119,6 +1114,16 @@ class FinderTest < ActiveRecord::TestCase
assert_equal [0, 1, 1], posts.map(&:author_id).sort
end
+ def test_find_one_message_on_primary_key
+ e = assert_raises(ActiveRecord::RecordNotFound) do
+ Car.find(0)
+ end
+ assert_equal 0, e.id
+ assert_equal "id", e.primary_key
+ assert_equal "Car", e.model
+ assert_equal "Couldn't find Car with 'id'=0", e.message
+ end
+
def test_find_one_message_with_custom_primary_key
table_with_custom_primary_key do |model|
model.primary_key = :name
diff --git a/activerecord/test/cases/fixture_set/file_test.rb b/activerecord/test/cases/fixture_set/file_test.rb
index e69c9f303a..cf2a73595a 100644
--- a/activerecord/test/cases/fixture_set/file_test.rb
+++ b/activerecord/test/cases/fixture_set/file_test.rb
@@ -77,7 +77,7 @@ module ActiveRecord
yaml = "one:\n name: <%= fixture_helper %>\n"
tmp_yaml ["curious", "yml"], yaml do |t|
golden =
- [["one", {"name" => "Fixture helper"}]]
+ [["one", { "name" => "Fixture helper" }]]
assert_equal golden, File.open(t.path) { |fh| fh.to_a }
end
ActiveRecord::FixtureSet.context_class.class_eval do
diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb
index 234e99919c..24a9894f19 100644
--- a/activerecord/test/cases/fixtures_test.rb
+++ b/activerecord/test/cases/fixtures_test.rb
@@ -280,7 +280,7 @@ class FixturesTest < ActiveRecord::TestCase
end
end
-class HasManyThroughFixture < ActiveSupport::TestCase
+class HasManyThroughFixture < ActiveRecord::TestCase
def make_model(name)
Class.new(ActiveRecord::Base) { define_singleton_method(:name) { name } }
end
@@ -479,7 +479,6 @@ class SetupSubclassTest < SetupTest
end
end
-
class OverlappingFixturesTest < ActiveRecord::TestCase
fixtures :topics, :developers
fixtures :developers, :accounts
@@ -1005,10 +1004,10 @@ class FixtureClassNamesTest < ActiveRecord::TestCase
end
def teardown
- self.fixture_class_names.replace(@saved_cache)
+ fixture_class_names.replace(@saved_cache)
end
test "fixture_class_names returns nil for unregistered identifier" do
- assert_nil self.fixture_class_names["unregistered_identifier"]
+ assert_nil fixture_class_names["unregistered_identifier"]
end
end
diff --git a/activerecord/test/cases/forbidden_attributes_protection_test.rb b/activerecord/test/cases/forbidden_attributes_protection_test.rb
index b17daafe01..75c3493527 100644
--- a/activerecord/test/cases/forbidden_attributes_protection_test.rb
+++ b/activerecord/test/cases/forbidden_attributes_protection_test.rb
@@ -140,7 +140,7 @@ class ForbiddenAttributesProtectionTest < ActiveRecord::TestCase
def test_where_not_works_with_permitted_params
params = ProtectedParams.new(first_name: "Guille").permit!
Person.create!(params)
- assert_empty Person.where.not(params).select {|p| p.first_name == "Guille" }
+ assert_empty Person.where.not(params).select { |p| p.first_name == "Guille" }
end
def test_strong_params_style_objects_work_with_singular_associations
diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb
index ebd4437a87..f1d69a215a 100644
--- a/activerecord/test/cases/helper.rb
+++ b/activerecord/test/cases/helper.rb
@@ -1,7 +1,5 @@
require "config"
-require "active_support/testing/autorun"
-require "active_support/testing/method_call_assertions"
require "stringio"
require "active_record"
@@ -134,21 +132,6 @@ def disable_extension!(extension, connection)
connection.reconnect!
end
-require "cases/validations_repair_helper"
-class ActiveSupport::TestCase
- include ActiveRecord::TestFixtures
- include ActiveRecord::ValidationsRepairHelper
- include ActiveSupport::Testing::MethodCallAssertions
-
- self.fixture_path = FIXTURES_ROOT
- self.use_instantiated_fixtures = false
- self.use_transactional_tests = true
-
- def create_fixtures(*fixture_set_names, &block)
- ActiveRecord::FixtureSet.create_fixtures(ActiveSupport::TestCase.fixture_path, fixture_set_names, fixture_class_names, &block)
- end
-end
-
def load_schema
# silence verbose schema loading
original_stdout = $stdout
diff --git a/activerecord/test/cases/i18n_test.rb b/activerecord/test/cases/i18n_test.rb
index ab3a1132e8..7f03c5b23d 100644
--- a/activerecord/test/cases/i18n_test.rb
+++ b/activerecord/test/cases/i18n_test.rb
@@ -8,37 +8,37 @@ class ActiveRecordI18nTests < ActiveRecord::TestCase
end
def test_translated_model_attributes
- I18n.backend.store_translations "en", activerecord: {attributes: {topic: {title: "topic title attribute"} } }
+ I18n.backend.store_translations "en", activerecord: { attributes: { topic: { title: "topic title attribute" } } }
assert_equal "topic title attribute", Topic.human_attribute_name("title")
end
def test_translated_model_attributes_with_symbols
- I18n.backend.store_translations "en", activerecord: {attributes: {topic: {title: "topic title attribute"} } }
+ I18n.backend.store_translations "en", activerecord: { attributes: { topic: { title: "topic title attribute" } } }
assert_equal "topic title attribute", Topic.human_attribute_name(:title)
end
def test_translated_model_attributes_with_sti
- I18n.backend.store_translations "en", activerecord: {attributes: {reply: {title: "reply title attribute"} } }
+ I18n.backend.store_translations "en", activerecord: { attributes: { reply: { title: "reply title attribute" } } }
assert_equal "reply title attribute", Reply.human_attribute_name("title")
end
def test_translated_model_attributes_with_sti_fallback
- I18n.backend.store_translations "en", activerecord: {attributes: {topic: {title: "topic title attribute"} } }
+ I18n.backend.store_translations "en", activerecord: { attributes: { topic: { title: "topic title attribute" } } }
assert_equal "topic title attribute", Reply.human_attribute_name("title")
end
def test_translated_model_names
- I18n.backend.store_translations "en", activerecord: {models: {topic: "topic model"} }
+ I18n.backend.store_translations "en", activerecord: { models: { topic: "topic model" } }
assert_equal "topic model", Topic.model_name.human
end
def test_translated_model_names_with_sti
- I18n.backend.store_translations "en", activerecord: {models: {reply: "reply model"} }
+ I18n.backend.store_translations "en", activerecord: { models: { reply: "reply model" } }
assert_equal "reply model", Reply.model_name.human
end
def test_translated_model_names_with_sti_fallback
- I18n.backend.store_translations "en", activerecord: {models: {topic: "topic model"} }
+ I18n.backend.store_translations "en", activerecord: { models: { topic: "topic model" } }
assert_equal "topic model", Reply.model_name.human
end
end
diff --git a/activerecord/test/cases/inheritance_test.rb b/activerecord/test/cases/inheritance_test.rb
index 9090184622..9ad4664567 100644
--- a/activerecord/test/cases/inheritance_test.rb
+++ b/activerecord/test/cases/inheritance_test.rb
@@ -70,7 +70,7 @@ class InheritanceTest < ActiveRecord::TestCase
end
def test_compute_type_no_method_error
- ActiveSupport::Dependencies.stub(:safe_constantize, proc{ raise NoMethodError }) do
+ ActiveSupport::Dependencies.stub(:safe_constantize, proc { raise NoMethodError }) do
assert_raises NoMethodError do
ActiveRecord::Base.send :compute_type, "InvalidModel"
end
@@ -87,7 +87,7 @@ class InheritanceTest < ActiveRecord::TestCase
error = e
end
- ActiveSupport::Dependencies.stub(:safe_constantize, proc{ raise e }) do
+ ActiveSupport::Dependencies.stub(:safe_constantize, proc { raise e }) do
exception = assert_raises NameError do
ActiveRecord::Base.send :compute_type, "InvalidModel"
@@ -97,7 +97,7 @@ class InheritanceTest < ActiveRecord::TestCase
end
def test_compute_type_argument_error
- ActiveSupport::Dependencies.stub(:safe_constantize, proc{ raise ArgumentError }) do
+ ActiveSupport::Dependencies.stub(:safe_constantize, proc { raise ArgumentError }) do
assert_raises ArgumentError do
ActiveRecord::Base.send :compute_type, "InvalidModel"
end
diff --git a/activerecord/test/cases/invertible_migration_test.rb b/activerecord/test/cases/invertible_migration_test.rb
index 81e8b0000a..9d5aace7db 100644
--- a/activerecord/test/cases/invertible_migration_test.rb
+++ b/activerecord/test/cases/invertible_migration_test.rb
@@ -225,7 +225,7 @@ module ActiveRecord
InvertibleMigration.new.migrate :up
received = []
migration = InvertibleByPartsMigration.new
- migration.test = ->(dir){
+ migration.test = ->(dir) {
ActiveSupport::Deprecation.silence do
assert migration.connection.table_exists?("horses")
assert migration.connection.table_exists?("new_horses")
@@ -305,7 +305,7 @@ module ActiveRecord
end
def test_revert_order
- block = Proc.new{|t| t.string :name }
+ block = Proc.new { |t| t.string :name }
recorder = ActiveRecord::Migration::CommandRecorder.new(ActiveRecord::Base.connection)
recorder.instance_eval do
create_table("apples", &block)
diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb
index 84f252d5d1..5c55584ff7 100644
--- a/activerecord/test/cases/locking_test.rb
+++ b/activerecord/test/cases/locking_test.rb
@@ -374,7 +374,6 @@ class OptimisticLockingWithSchemaChangeTest < ActiveRecord::TestCase
end
end
-
# TODO: test against the generated SQL since testing locking behavior itself
# is so cumbersome. Will deadlock Ruby threads if the underlying db.execute
# blocks, so separate script called by Kernel#system is needed.
diff --git a/activerecord/test/cases/migration/change_schema_test.rb b/activerecord/test/cases/migration/change_schema_test.rb
index 0191c9d03b..bdb90eaa74 100644
--- a/activerecord/test/cases/migration/change_schema_test.rb
+++ b/activerecord/test/cases/migration/change_schema_test.rb
@@ -200,8 +200,8 @@ module ActiveRecord
end
created_columns = connection.columns(table_name)
- created_at_column = created_columns.detect {|c| c.name == "created_at" }
- updated_at_column = created_columns.detect {|c| c.name == "updated_at" }
+ created_at_column = created_columns.detect { |c| c.name == "created_at" }
+ updated_at_column = created_columns.detect { |c| c.name == "updated_at" }
assert !created_at_column.null
assert !updated_at_column.null
@@ -213,8 +213,8 @@ module ActiveRecord
end
created_columns = connection.columns(table_name)
- created_at_column = created_columns.detect {|c| c.name == "created_at" }
- updated_at_column = created_columns.detect {|c| c.name == "updated_at" }
+ created_at_column = created_columns.detect { |c| c.name == "created_at" }
+ updated_at_column = created_columns.detect { |c| c.name == "updated_at" }
assert created_at_column.null
assert updated_at_column.null
@@ -246,7 +246,7 @@ module ActiveRecord
con = connection
connection.execute "insert into testings (#{con.quote_column_name('id')}, #{con.quote_column_name('foo')}) values (1, 'hello')"
- assert_nothing_raised {connection.add_column :testings, :bar, :string, null: false, default: "default" }
+ assert_nothing_raised { connection.add_column :testings, :bar, :string, null: false, default: "default" }
assert_raises(ActiveRecord::StatementInvalid) do
connection.execute "insert into testings (#{con.quote_column_name('id')}, #{con.quote_column_name('foo')}, #{con.quote_column_name('bar')}) values (2, 'hello', NULL)"
@@ -298,9 +298,9 @@ module ActiveRecord
assert_equal false, person_klass.columns_hash["wealth"].null
# Oracle needs primary key value from sequence
if current_adapter?(:OracleAdapter)
- assert_nothing_raised {person_klass.connection.execute("insert into testings (id, title) values (testings_seq.nextval, 'tester')")}
+ assert_nothing_raised { person_klass.connection.execute("insert into testings (id, title) values (testings_seq.nextval, 'tester')") }
else
- assert_nothing_raised {person_klass.connection.execute("insert into testings (title) values ('tester')")}
+ assert_nothing_raised { person_klass.connection.execute("insert into testings (title) values ('tester')") }
end
# change column default to see that column doesn't lose its not null definition
@@ -346,9 +346,9 @@ module ActiveRecord
end
notnull_migration.new.suppress_messages do
notnull_migration.migrate(:up)
- assert_equal false, connection.columns(:testings).find{ |c| c.name == "foo"}.null
+ assert_equal false, connection.columns(:testings).find { |c| c.name == "foo" }.null
notnull_migration.migrate(:down)
- assert connection.columns(:testings).find{ |c| c.name == "foo"}.null
+ assert connection.columns(:testings).find { |c| c.name == "foo" }.null
end
end
end
diff --git a/activerecord/test/cases/migration/change_table_test.rb b/activerecord/test/cases/migration/change_table_test.rb
index 87da9c90fe..ec817a579b 100644
--- a/activerecord/test/cases/migration/change_table_test.rb
+++ b/activerecord/test/cases/migration/change_table_test.rb
@@ -157,7 +157,7 @@ module ActiveRecord
def test_column_creates_column_with_options
with_change_table do |t|
- @connection.expect :add_column, nil, [:delete_me, :bar, :integer, {null: false}]
+ @connection.expect :add_column, nil, [:delete_me, :bar, :integer, { null: false }]
t.column :bar, :integer, null: false
end
end
@@ -171,7 +171,7 @@ module ActiveRecord
def test_index_creates_index_with_options
with_change_table do |t|
- @connection.expect :add_index, nil, [:delete_me, :bar, {unique: true}]
+ @connection.expect :add_index, nil, [:delete_me, :bar, { unique: true }]
t.index :bar, unique: true
end
end
@@ -185,7 +185,7 @@ module ActiveRecord
def test_index_exists_with_options
with_change_table do |t|
- @connection.expect :index_exists?, nil, [:delete_me, :bar, {unique: true}]
+ @connection.expect :index_exists?, nil, [:delete_me, :bar, { unique: true }]
t.index_exists?(:bar, unique: true)
end
end
@@ -206,7 +206,7 @@ module ActiveRecord
def test_change_changes_column_with_options
with_change_table do |t|
- @connection.expect :change_column, nil, [:delete_me, :bar, :string, {null: true}]
+ @connection.expect :change_column, nil, [:delete_me, :bar, :string, { null: true }]
t.change :bar, :string, null: true
end
end
@@ -234,7 +234,7 @@ module ActiveRecord
def test_remove_index_removes_index_with_options
with_change_table do |t|
- @connection.expect :remove_index, nil, [:delete_me, {unique: true}]
+ @connection.expect :remove_index, nil, [:delete_me, { unique: true }]
t.remove_index unique: true
end
end
diff --git a/activerecord/test/cases/migration/columns_test.rb b/activerecord/test/cases/migration/columns_test.rb
index baf0a0eb9f..70d40ed87a 100644
--- a/activerecord/test/cases/migration/columns_test.rb
+++ b/activerecord/test/cases/migration/columns_test.rb
@@ -75,9 +75,10 @@ module ActiveRecord
def test_rename_nonexistent_column
exception = if current_adapter?(:PostgreSQLAdapter, :OracleAdapter)
ActiveRecord::StatementInvalid
- else
- ActiveRecord::ActiveRecordError
- end
+ else
+ ActiveRecord::ActiveRecordError
+ end
+
assert_raise(exception) do
rename_column "test_models", "nonexistent", "should_fail"
end
diff --git a/activerecord/test/cases/migration/command_recorder_test.rb b/activerecord/test/cases/migration/command_recorder_test.rb
index 39f3fd99c7..802a969cb7 100644
--- a/activerecord/test/cases/migration/command_recorder_test.rb
+++ b/activerecord/test/cases/migration/command_recorder_test.rb
@@ -44,7 +44,7 @@ module ActiveRecord
def test_irreversible_commands_raise_exception
assert_raises(ActiveRecord::IrreversibleMigration) do
- @recorder.revert{ @recorder.execute "some sql" }
+ @recorder.revert { @recorder.execute "some sql" }
end
end
@@ -58,12 +58,12 @@ module ActiveRecord
@recorder.record :create_table, [:hello]
@recorder.record :create_table, [:world]
end
- tables = @recorder.commands.map{|_cmd, args, _block| args}
+ tables = @recorder.commands.map { |_cmd, args, _block| args }
assert_equal [[:world], [:hello]], tables
end
def test_revert_order
- block = Proc.new{|t| t.string :name }
+ block = Proc.new { |t| t.string :name }
@recorder.instance_eval do
create_table("apples", &block)
revert do
@@ -115,13 +115,13 @@ module ActiveRecord
end
def test_invert_create_table_with_options_and_block
- block = Proc.new{}
+ block = Proc.new {}
drop_table = @recorder.inverse_of :create_table, [:people_reminders, id: false], &block
assert_equal [:drop_table, [:people_reminders, id: false], block], drop_table
end
def test_invert_drop_table
- block = Proc.new{}
+ block = Proc.new {}
create_table = @recorder.inverse_of :drop_table, [:people_reminders, id: false], &block
assert_equal [:create_table, [:people_reminders, id: false], block], create_table
end
@@ -143,7 +143,7 @@ module ActiveRecord
end
def test_invert_drop_join_table
- block = Proc.new{}
+ block = Proc.new {}
create_join_table = @recorder.inverse_of :drop_join_table, [:musics, :artists, table_name: :catalog], &block
assert_equal [:create_join_table, [:musics, :artists, table_name: :catalog], block], create_join_table
end
@@ -203,17 +203,17 @@ module ActiveRecord
def test_invert_add_index
remove = @recorder.inverse_of :add_index, [:table, [:one, :two]]
- assert_equal [:remove_index, [:table, {column: [:one, :two]}]], remove
+ assert_equal [:remove_index, [:table, { column: [:one, :two] }]], remove
end
def test_invert_add_index_with_name
remove = @recorder.inverse_of :add_index, [:table, [:one, :two], name: "new_index"]
- assert_equal [:remove_index, [:table, {name: "new_index"}]], remove
+ assert_equal [:remove_index, [:table, { name: "new_index" }]], remove
end
def test_invert_add_index_with_no_options
remove = @recorder.inverse_of :add_index, [:table, [:one, :two]]
- assert_equal [:remove_index, [:table, {column: [:one, :two]}]], remove
+ assert_equal [:remove_index, [:table, { column: [:one, :two] }]], remove
end
def test_invert_remove_index
@@ -222,17 +222,17 @@ module ActiveRecord
end
def test_invert_remove_index_with_column
- add = @recorder.inverse_of :remove_index, [:table, {column: [:one, :two], options: true}]
+ add = @recorder.inverse_of :remove_index, [:table, { column: [:one, :two], options: true }]
assert_equal [:add_index, [:table, [:one, :two], options: true]], add
end
def test_invert_remove_index_with_name
- add = @recorder.inverse_of :remove_index, [:table, {column: [:one, :two], name: "new_index"}]
+ add = @recorder.inverse_of :remove_index, [:table, { column: [:one, :two], name: "new_index" }]
assert_equal [:add_index, [:table, [:one, :two], name: "new_index"]], add
end
def test_invert_remove_index_with_no_special_options
- add = @recorder.inverse_of :remove_index, [:table, {column: [:one, :two]}]
+ add = @recorder.inverse_of :remove_index, [:table, { column: [:one, :two] }]
assert_equal [:add_index, [:table, [:one, :two], {}]], add
end
@@ -254,7 +254,7 @@ module ActiveRecord
def test_invert_remove_timestamps
add = @recorder.inverse_of :remove_timestamps, [:table, { null: true }]
- assert_equal [:add_timestamps, [:table, {null: true }], nil], add
+ assert_equal [:add_timestamps, [:table, { null: true }], nil], add
end
def test_invert_add_reference
diff --git a/activerecord/test/cases/migration/create_join_table_test.rb b/activerecord/test/cases/migration/create_join_table_test.rb
index 372ec40a04..f14d68f12b 100644
--- a/activerecord/test/cases/migration/create_join_table_test.rb
+++ b/activerecord/test/cases/migration/create_join_table_test.rb
@@ -61,7 +61,7 @@ module ActiveRecord
end
def test_create_join_table_with_column_options
- connection.create_join_table :artists, :musics, column_options: {null: true}
+ connection.create_join_table :artists, :musics, column_options: { null: true }
assert_equal [true, true], connection.columns(:artists_musics).map(&:null)
end
@@ -116,8 +116,8 @@ module ActiveRecord
end
def test_drop_join_table_with_column_options
- connection.create_join_table :artists, :musics, column_options: {null: true}
- connection.drop_join_table :artists, :musics, column_options: {null: true}
+ connection.create_join_table :artists, :musics, column_options: { null: true }
+ connection.drop_join_table :artists, :musics, column_options: { null: true }
ActiveSupport::Deprecation.silence { assert !connection.table_exists?("artists_musics") }
end
diff --git a/activerecord/test/cases/migration/index_test.rb b/activerecord/test/cases/migration/index_test.rb
index 0ac6df4a3d..0f975026b8 100644
--- a/activerecord/test/cases/migration/index_test.rb
+++ b/activerecord/test/cases/migration/index_test.rb
@@ -49,7 +49,6 @@ module ActiveRecord
assert connection.index_name_exists?(table_name, "old_idx", false)
end
-
def test_double_add_index
connection.add_index(table_name, [:foo], name: "some_idx")
assert_raises(ArgumentError) {
@@ -144,7 +143,7 @@ module ActiveRecord
end
def test_add_index_attribute_length_limit
- connection.add_index :testings, [:foo, :bar], length: {foo: 10, bar: nil}
+ connection.add_index :testings, [:foo, :bar], length: { foo: 10, bar: nil }
assert connection.index_exists?(:testings, [:foo, :bar])
end
@@ -170,13 +169,13 @@ module ActiveRecord
connection.add_index("testings", ["last_name"], length: 10)
connection.remove_index("testings", "last_name")
- connection.add_index("testings", ["last_name"], length: {last_name: 10})
+ connection.add_index("testings", ["last_name"], length: { last_name: 10 })
connection.remove_index("testings", ["last_name"])
connection.add_index("testings", ["last_name", "first_name"], length: 10)
connection.remove_index("testings", ["last_name", "first_name"])
- connection.add_index("testings", ["last_name", "first_name"], length: {last_name: 10, first_name: 20})
+ connection.add_index("testings", ["last_name", "first_name"], length: { last_name: 10, first_name: 20 })
connection.remove_index("testings", ["last_name", "first_name"])
connection.add_index("testings", ["key"], name: "key_idx", unique: true)
@@ -187,11 +186,11 @@ module ActiveRecord
# Selected adapters support index sort order
if current_adapter?(:SQLite3Adapter, :Mysql2Adapter, :PostgreSQLAdapter)
- connection.add_index("testings", ["last_name"], order: {last_name: :desc})
+ connection.add_index("testings", ["last_name"], order: { last_name: :desc })
connection.remove_index("testings", ["last_name"])
- connection.add_index("testings", ["last_name", "first_name"], order: {last_name: :desc})
+ connection.add_index("testings", ["last_name", "first_name"], order: { last_name: :desc })
connection.remove_index("testings", ["last_name", "first_name"])
- connection.add_index("testings", ["last_name", "first_name"], order: {last_name: :desc, first_name: :asc})
+ connection.add_index("testings", ["last_name", "first_name"], order: { last_name: :desc, first_name: :asc })
connection.remove_index("testings", ["last_name", "first_name"])
connection.add_index("testings", ["last_name", "first_name"], order: :desc)
connection.remove_index("testings", ["last_name", "first_name"])
diff --git a/activerecord/test/cases/migration/references_foreign_key_test.rb b/activerecord/test/cases/migration/references_foreign_key_test.rb
index 8436435170..528811db49 100644
--- a/activerecord/test/cases/migration/references_foreign_key_test.rb
+++ b/activerecord/test/cases/migration/references_foreign_key_test.rb
@@ -59,7 +59,7 @@ if ActiveRecord::Base.connection.supports_foreign_keys?
end
fks = @connection.foreign_keys("testings")
assert_equal([["testings", "testing_parents", "parent_id"]],
- fks.map {|fk| [fk.from_table, fk.to_table, fk.column] })
+ fks.map { |fk| [fk.from_table, fk.to_table, fk.column] })
end
test "foreign keys cannot be added to polymorphic relations when creating the table" do
@@ -186,7 +186,7 @@ if ActiveRecord::Base.connection.supports_foreign_keys?
fks = @connection.foreign_keys("testings")
- fk_definitions = fks.map {|fk| [fk.from_table, fk.to_table, fk.column] }
+ fk_definitions = fks.map { |fk| [fk.from_table, fk.to_table, fk.column] }
assert_equal([["testings", "testing_parents", "col_1"],
["testings", "testing_parents", "col_2"]], fk_definitions)
end
diff --git a/activerecord/test/cases/migration/references_index_test.rb b/activerecord/test/cases/migration/references_index_test.rb
index 0d0b0a193b..2866cabab6 100644
--- a/activerecord/test/cases/migration/references_index_test.rb
+++ b/activerecord/test/cases/migration/references_index_test.rb
@@ -41,8 +41,8 @@ module ActiveRecord
def test_creates_index_with_options
connection.create_table table_name do |t|
- t.references :foo, index: {name: :index_testings_on_yo_momma}
- t.references :bar, index: {unique: true}
+ t.references :foo, index: { name: :index_testings_on_yo_momma }
+ t.references :bar, index: { unique: true }
end
assert connection.index_exists?(table_name, :foo_id, name: :index_testings_on_yo_momma)
diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb
index b8ffc8a154..76a4592ac5 100644
--- a/activerecord/test/cases/migration_test.rb
+++ b/activerecord/test/cases/migration_test.rb
@@ -313,7 +313,7 @@ class MigrationTest < ActiveRecord::TestCase
assert_no_column Person, :last_name
migration = Class.new(ActiveRecord::Migration::Current) {
- self.disable_ddl_transaction!
+ disable_ddl_transaction!
def version; 101 end
def migrate(x)
@@ -401,7 +401,6 @@ class MigrationTest < ActiveRecord::TestCase
ENV["RACK_ENV"] = original_rack_env
end
-
def test_migration_sets_internal_metadata_even_when_fully_migrated
current_env = ActiveRecord::ConnectionHandling::DEFAULT_ENV.call
migrations_path = MIGRATIONS_ROOT + "/valid"
@@ -760,7 +759,7 @@ if ActiveRecord::Base.connection.supports_bulk_alter?
class BulkAlterTableMigrationsTest < ActiveRecord::TestCase
def setup
@connection = Person.connection
- @connection.create_table(:delete_me, force: true) {|t| }
+ @connection.create_table(:delete_me, force: true) { |t| }
Person.reset_column_information
Person.reset_sequence_name
end
@@ -781,7 +780,7 @@ if ActiveRecord::Base.connection.supports_bulk_alter?
end
assert_equal 8, columns.size
- [:name, :qualification, :experience].each {|s| assert_equal :string, column(s).type }
+ [:name, :qualification, :experience].each { |s| assert_equal :string, column(s).type }
assert_equal "0", column(:age).default
end
@@ -790,7 +789,7 @@ if ActiveRecord::Base.connection.supports_bulk_alter?
t.string :qualification, :experience
end
- [:qualification, :experience].each {|c| assert column(c) }
+ [:qualification, :experience].each { |c| assert column(c) }
assert_queries(1) do
with_bulk_change_table do |t|
@@ -799,7 +798,7 @@ if ActiveRecord::Base.connection.supports_bulk_alter?
end
end
- [:qualification, :experience].each {|c| assert ! column(c) }
+ [:qualification, :experience].each { |c| assert ! column(c) }
assert column(:qualification_experience)
end
@@ -883,7 +882,7 @@ if ActiveRecord::Base.connection.supports_bulk_alter?
end
def column(name)
- columns.detect {|c| c.name == name.to_s }
+ columns.detect { |c| c.name == name.to_s }
end
def columns
@@ -891,7 +890,7 @@ if ActiveRecord::Base.connection.supports_bulk_alter?
end
def index(name)
- indexes.detect {|i| i.name == name.to_s }
+ indexes.detect { |i| i.name == name.to_s }
end
def indexes
diff --git a/activerecord/test/cases/modules_test.rb b/activerecord/test/cases/modules_test.rb
index 1b7720e4f8..f8a7bab35f 100644
--- a/activerecord/test/cases/modules_test.rb
+++ b/activerecord/test/cases/modules_test.rb
@@ -73,7 +73,7 @@ class ModulesTest < ActiveRecord::TestCase
clients = []
assert_nothing_raised do
- clients << MyApplication::Business::Client.references(:accounts).merge!(includes: {firm: :account}, where: "accounts.id IS NOT NULL").find(3)
+ clients << MyApplication::Business::Client.references(:accounts).merge!(includes: { firm: :account }, where: "accounts.id IS NOT NULL").find(3)
clients << MyApplication::Business::Client.includes(firm: :account).find(3)
end
diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb
index f0cf02ce54..a9c3733c20 100644
--- a/activerecord/test/cases/nested_attributes_test.rb
+++ b/activerecord/test/cases/nested_attributes_test.rb
@@ -31,7 +31,7 @@ class TestNestedAttributesInGeneral < ActiveRecord::TestCase
def test_should_not_build_a_new_record_using_reject_all_even_if_destroy_is_given
pirate = Pirate.create!(catchphrase: "Don' botharrr talkin' like one, savvy?")
- pirate.birds_with_reject_all_blank_attributes = [{name: "", color: "", _destroy: "0"}]
+ pirate.birds_with_reject_all_blank_attributes = [{ name: "", color: "", _destroy: "0" }]
pirate.save!
assert pirate.birds_with_reject_all_blank.empty?
@@ -39,7 +39,7 @@ class TestNestedAttributesInGeneral < ActiveRecord::TestCase
def test_should_not_build_a_new_record_if_reject_all_blank_returns_false
pirate = Pirate.create!(catchphrase: "Don' botharrr talkin' like one, savvy?")
- pirate.birds_with_reject_all_blank_attributes = [{name: "", color: ""}]
+ pirate.birds_with_reject_all_blank_attributes = [{ name: "", color: "" }]
pirate.save!
assert pirate.birds_with_reject_all_blank.empty?
@@ -47,7 +47,7 @@ class TestNestedAttributesInGeneral < ActiveRecord::TestCase
def test_should_build_a_new_record_if_reject_all_blank_does_not_return_false
pirate = Pirate.create!(catchphrase: "Don' botharrr talkin' like one, savvy?")
- pirate.birds_with_reject_all_blank_attributes = [{name: "Tweetie", color: ""}]
+ pirate.birds_with_reject_all_blank_attributes = [{ name: "Tweetie", color: "" }]
pirate.save!
assert_equal 1, pirate.birds_with_reject_all_blank.count
@@ -108,7 +108,7 @@ class TestNestedAttributesInGeneral < ActiveRecord::TestCase
end
def test_reject_if_with_indifferent_keys
- Pirate.accepts_nested_attributes_for :ship, reject_if: proc {|attributes| attributes[:name].blank? }
+ Pirate.accepts_nested_attributes_for :ship, reject_if: proc { |attributes| attributes[:name].blank? }
pirate = Pirate.new(catchphrase: "Stop wastin' me time")
pirate.ship_attributes = { name: "Hello Pearl" }
@@ -116,7 +116,7 @@ class TestNestedAttributesInGeneral < ActiveRecord::TestCase
end
def test_reject_if_with_a_proc_which_returns_true_always_for_has_one
- Pirate.accepts_nested_attributes_for :ship, reject_if: proc {|attributes| true }
+ Pirate.accepts_nested_attributes_for :ship, reject_if: proc { |attributes| true }
pirate = Pirate.new(catchphrase: "Stop wastin' me time")
ship = pirate.create_ship(name: "s1")
pirate.update(ship_attributes: { name: "s2", id: ship.id })
@@ -138,7 +138,7 @@ class TestNestedAttributesInGeneral < ActiveRecord::TestCase
end
def test_reject_if_with_a_proc_which_returns_true_always_for_has_many
- Man.accepts_nested_attributes_for :interests, reject_if: proc {|attributes| true }
+ Man.accepts_nested_attributes_for :interests, reject_if: proc { |attributes| true }
man = Man.create(name: "John")
interest = man.interests.create(topic: "photography")
man.update(interests_attributes: { topic: "gardening", id: interest.id })
@@ -146,7 +146,7 @@ class TestNestedAttributesInGeneral < ActiveRecord::TestCase
end
def test_destroy_works_independent_of_reject_if
- Man.accepts_nested_attributes_for :interests, reject_if: proc {|attributes| true }, allow_destroy: true
+ Man.accepts_nested_attributes_for :interests, reject_if: proc { |attributes| true }, allow_destroy: true
man = Man.create(name: "Jon")
interest = man.interests.create(topic: "the ladies")
man.update(interests_attributes: { _destroy: "1", id: interest.id })
@@ -170,13 +170,13 @@ class TestNestedAttributesInGeneral < ActiveRecord::TestCase
Man.accepts_nested_attributes_for(:interests)
man = Man.create(name: "John")
interest = man.interests.create(topic: "photography")
- man.update(interests_attributes: {topic: "gardening", id: interest.id})
+ man.update(interests_attributes: { topic: "gardening", id: interest.id })
assert_equal "gardening", interest.reload.topic
end
def test_reject_if_with_blank_nested_attributes_id
# When using a select list to choose an existing 'ship' id, with include_blank: true
- Pirate.accepts_nested_attributes_for :ship, reject_if: proc {|attributes| attributes[:id].blank? }
+ Pirate.accepts_nested_attributes_for :ship, reject_if: proc { |attributes| attributes[:id].blank? }
pirate = Pirate.new(catchphrase: "Stop wastin' me time")
pirate.ship_attributes = { id: "" }
@@ -188,7 +188,7 @@ class TestNestedAttributesInGeneral < ActiveRecord::TestCase
man = Man.create(name: "John")
interest = man.interests.create topic: "gardening"
man = Man.find man.id
- man.interests_attributes = [{id: interest.id, topic: "gardening"}]
+ man.interests_attributes = [{ id: interest.id, topic: "gardening" }]
assert_equal man.interests.first.topic, man.interests[0].topic
end
@@ -225,7 +225,7 @@ class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
def test_should_raise_argument_error_if_trying_to_build_polymorphic_belongs_to
exception = assert_raise ArgumentError do
- Treasure.new(name: "pearl", looter_attributes: {catchphrase: "Arrr"})
+ Treasure.new(name: "pearl", looter_attributes: { catchphrase: "Arrr" })
end
assert_equal "Cannot build association `looter'. Are you trying to build a polymorphic one-to-one association?", exception.message
end
@@ -596,7 +596,8 @@ module NestedAttributesOnACollectionAssociationTests
end
def test_should_save_only_one_association_on_create
- pirate = Pirate.create!( :catchphrase => "Arr",
+ pirate = Pirate.create!(
+ :catchphrase => "Arr",
association_getter => { "foo" => { name: "Grace OMalley" } })
assert_equal 1, pirate.reload.send(@association_name).count
@@ -699,7 +700,7 @@ module NestedAttributesOnACollectionAssociationTests
def test_should_automatically_build_new_associated_models_for_each_entry_in_a_hash_where_the_id_is_missing
@pirate.send(@association_name).destroy_all
@pirate.reload.attributes = {
- association_getter => { "foo" => { name: "Grace OMalley" }, "bar" => { name: "Privateers Greed" }}
+ association_getter => { "foo" => { name: "Grace OMalley" }, "bar" => { name: "Privateers Greed" } }
}
assert !@pirate.send(@association_name).first.persisted?
@@ -756,7 +757,7 @@ module NestedAttributesOnACollectionAssociationTests
def test_should_work_with_update_as_well
@pirate.update(catchphrase: "Arr",
- association_getter => { "foo" => { id: @child_1.id, name: "Grace OMalley" }})
+ association_getter => { "foo" => { id: @child_1.id, name: "Grace OMalley" } })
assert_equal "Grace OMalley", @child_1.reload.name
end
@@ -812,7 +813,7 @@ module NestedAttributesOnACollectionAssociationTests
assert_difference "Man.count" do
assert_difference "Interest.count", 2 do
man = Man.create!(name: "John",
- interests_attributes: [{topic: "Cars"}, {topic: "Sports"}])
+ interests_attributes: [{ topic: "Cars" }, { topic: "Sports" }])
assert_equal 2, man.interests.count
end
end
@@ -910,7 +911,7 @@ module NestedAttributesLimitTests
assert_raises(ActiveRecord::NestedAttributes::TooManyRecords) do
@pirate.attributes = { parrots_attributes: { "foo" => { name: "Lovely Day" },
"bar" => { name: "Blown Away" },
- "car" => { name: "The Happening" }} }
+ "car" => { name: "The Happening" } } }
end
end
end
@@ -970,10 +971,10 @@ class TestNestedAttributesWithNonStandardPrimaryKeys < ActiveRecord::TestCase
def test_attr_accessor_of_child_should_be_value_provided_during_update
@owner = owners(:ashley)
@pet1 = pets(:chew)
- attributes = {pets_attributes: { "1"=> { id: @pet1.id,
+ attributes = { pets_attributes: { "1"=> { id: @pet1.id,
name: "Foo2",
current_user: "John",
- _destroy: true }}}
+ _destroy: true } } }
@owner.update(attributes)
assert_equal "John", Pet.after_destroy_output
end
@@ -996,18 +997,18 @@ class TestHasOneAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveRe
end
test "when great-grandchild changed via attributes, saving parent should save great-grandchild" do
- @pirate.attributes = {ship_attributes: {id: @ship.id, parts_attributes: [{id: @part.id, trinkets_attributes: [{id: @trinket.id, name: "changed"}]}]}}
+ @pirate.attributes = { ship_attributes: { id: @ship.id, parts_attributes: [{ id: @part.id, trinkets_attributes: [{ id: @trinket.id, name: "changed" }] }] } }
@pirate.save
assert_equal "changed", @trinket.reload.name
end
test "when great-grandchild marked_for_destruction via attributes, saving parent should destroy great-grandchild" do
- @pirate.attributes = {ship_attributes: {id: @ship.id, parts_attributes: [{id: @part.id, trinkets_attributes: [{id: @trinket.id, _destroy: true}]}]}}
+ @pirate.attributes = { ship_attributes: { id: @ship.id, parts_attributes: [{ id: @part.id, trinkets_attributes: [{ id: @trinket.id, _destroy: true }] }] } }
assert_difference("@part.trinkets.count", -1) { @pirate.save }
end
test "when great-grandchild added via attributes, saving parent should create great-grandchild" do
- @pirate.attributes = {ship_attributes: {id: @ship.id, parts_attributes: [{id: @part.id, trinkets_attributes: [{name: "created"}]}]}}
+ @pirate.attributes = { ship_attributes: { id: @ship.id, parts_attributes: [{ id: @part.id, trinkets_attributes: [{ name: "created" }] }] } }
assert_difference("@part.trinkets.count", 1) { @pirate.save }
end
@@ -1029,13 +1030,13 @@ class TestHasManyAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveR
end
test "if association is not loaded and association record is saved and then in memory record attributes should be saved" do
- @ship.parts_attributes=[{id: @part.id,name: "Deck"}]
+ @ship.parts_attributes=[{ id: @part.id,name: "Deck" }]
assert_equal 1, @ship.association(:parts).target.size
assert_equal "Deck", @ship.parts[0].name
end
test "if association is not loaded and child doesn't change and I am saving a grandchild then in memory record should be used" do
- @ship.parts_attributes=[{id: @part.id,trinkets_attributes: [{id: @trinket.id, name: "Ruby"}]}]
+ @ship.parts_attributes=[{ id: @part.id,trinkets_attributes: [{ id: @trinket.id, name: "Ruby" }] }]
assert_equal 1, @ship.association(:parts).target.size
assert_equal "Mast", @ship.parts[0].name
assert_no_difference("@ship.parts[0].association(:trinkets).target.size") do
@@ -1053,18 +1054,18 @@ class TestHasManyAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveR
end
test "when grandchild changed via attributes, saving parent should save grandchild" do
- @ship.attributes = {parts_attributes: [{id: @part.id, trinkets_attributes: [{id: @trinket.id, name: "changed"}]}]}
+ @ship.attributes = { parts_attributes: [{ id: @part.id, trinkets_attributes: [{ id: @trinket.id, name: "changed" }] }] }
@ship.save
assert_equal "changed", @trinket.reload.name
end
test "when grandchild marked_for_destruction via attributes, saving parent should destroy grandchild" do
- @ship.attributes = {parts_attributes: [{id: @part.id, trinkets_attributes: [{id: @trinket.id, _destroy: true}]}]}
+ @ship.attributes = { parts_attributes: [{ id: @part.id, trinkets_attributes: [{ id: @trinket.id, _destroy: true }] }] }
assert_difference("@part.trinkets.count", -1) { @ship.save }
end
test "when grandchild added via attributes, saving parent should create grandchild" do
- @ship.attributes = {parts_attributes: [{id: @part.id, trinkets_attributes: [{name: "created"}]}]}
+ @ship.attributes = { parts_attributes: [{ id: @part.id, trinkets_attributes: [{ name: "created" }] }] }
assert_difference("@part.trinkets.count", 1) { @ship.save }
end
diff --git a/activerecord/test/cases/nested_attributes_with_callbacks_test.rb b/activerecord/test/cases/nested_attributes_with_callbacks_test.rb
index d606a6c12d..8954e8c7e3 100644
--- a/activerecord/test/cases/nested_attributes_with_callbacks_test.rb
+++ b/activerecord/test/cases/nested_attributes_with_callbacks_test.rb
@@ -21,7 +21,7 @@ class NestedAttributesWithCallbacksTest < ActiveRecord::TestCase
@@add_callback_called = []
@pirate = Pirate.new.tap do |pirate|
pirate.catchphrase = "Don't call me!"
- pirate.birds_attributes = [{name: "Bird1"},{name: "Bird2"}]
+ pirate.birds_attributes = [{ name: "Bird1" },{ name: "Bird2" }]
pirate.save!
end
@birds = @pirate.birds.to_a
@@ -46,17 +46,17 @@ class NestedAttributesWithCallbacksTest < ActiveRecord::TestCase
end
def new_bird_attributes
- [{"name" => "New Bird"}]
+ [{ "name" => "New Bird" }]
end
def destroy_bird_attributes
- [{"id" => bird_to_destroy.id.to_s, "_destroy" => true}]
+ [{ "id" => bird_to_destroy.id.to_s, "_destroy" => true }]
end
def update_new_and_destroy_bird_attributes
- [{"id" => @birds[0].id.to_s, "name" => "New Name"},
- {"name" => "New Bird"},
- {"id" => bird_to_destroy.id.to_s, "_destroy" => true}]
+ [{ "id" => @birds[0].id.to_s, "name" => "New Name" },
+ { "name" => "New Bird" },
+ { "id" => bird_to_destroy.id.to_s, "_destroy" => true }]
end
# Characterizing when :before_add callback is called
@@ -136,9 +136,9 @@ class NestedAttributesWithCallbacksTest < ActiveRecord::TestCase
def assert_assignment_affects_records_in_target(association_name)
association = @pirate.send(association_name)
- assert association.detect {|b| b == bird_to_update }.name_changed?,
+ assert association.detect { |b| b == bird_to_update }.name_changed?,
"Update record not updated"
- assert association.detect {|b| b == bird_to_destroy }.marked_for_destruction?,
+ assert association.detect { |b| b == bird_to_destroy }.marked_for_destruction?,
"Destroy record not marked for destruction"
end
end
diff --git a/activerecord/test/cases/persistence_test.rb b/activerecord/test/cases/persistence_test.rb
index 57dc963b62..d83360e327 100644
--- a/activerecord/test/cases/persistence_test.rb
+++ b/activerecord/test/cases/persistence_test.rb
@@ -83,7 +83,7 @@ class PersistenceTest < ActiveRecord::TestCase
end
def test_delete_all_with_joins_and_where_part_is_hash
- where_args = {toys: {name: "Bone"}}
+ where_args = { toys: { name: "Bone" } }
count = Pet.joins(:toys).where(where_args).count
assert_equal count, 1
@@ -967,7 +967,8 @@ class PersistenceTest < ActiveRecord::TestCase
self.table_name = :widgets
end
- instance = widget.create!( name: "Bob",
+ instance = widget.create!(
+ name: "Bob",
created_at: 1.day.ago,
updated_at: 1.day.ago)
diff --git a/activerecord/test/cases/readonly_test.rb b/activerecord/test/cases/readonly_test.rb
index 151bb31fbd..a93061b516 100644
--- a/activerecord/test/cases/readonly_test.rb
+++ b/activerecord/test/cases/readonly_test.rb
@@ -35,7 +35,6 @@ class ReadOnlyTest < ActiveRecord::TestCase
assert_equal "Developer is marked as readonly", e.message
end
-
def test_find_with_readonly_option
Developer.all.each { |d| assert !d.readonly? }
Developer.readonly(false).each { |d| assert !d.readonly? }
diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb
index d71b30af69..cb47237e4b 100644
--- a/activerecord/test/cases/reflection_test.rb
+++ b/activerecord/test/cases/reflection_test.rb
@@ -124,7 +124,7 @@ class ReflectionTest < ActiveRecord::TestCase
)
reflection_for_gps_location = AggregateReflection.new(
- :gps_location, nil, { }, Customer
+ :gps_location, nil, {}, Customer
)
assert Customer.reflect_on_all_aggregations.include?(reflection_for_gps_location)
diff --git a/activerecord/test/cases/relation/mutation_test.rb b/activerecord/test/cases/relation/mutation_test.rb
index 14de5ae337..e7dc06c106 100644
--- a/activerecord/test/cases/relation/mutation_test.rb
+++ b/activerecord/test/cases/relation/mutation_test.rb
@@ -2,7 +2,7 @@ require "cases/helper"
require "models/post"
module ActiveRecord
- class RelationMutationTest < ActiveSupport::TestCase
+ class RelationMutationTest < ActiveRecord::TestCase
class FakeKlass < Struct.new(:table_name, :name)
extend ActiveRecord::Delegation::DelegateCache
inherited self
@@ -132,7 +132,6 @@ module ActiveRecord
assert_equal "title DESC", relation.order_values.first
assert_equal "comments_count ASC", relation.order_values.last
-
relation.reverse_order!
assert_equal "title ASC", relation.order_values.first
@@ -141,7 +140,7 @@ module ActiveRecord
test "create_with!" do
assert relation.create_with!(foo: "bar").equal?(relation)
- assert_equal({foo: "bar"}, relation.create_with_value)
+ assert_equal({ foo: "bar" }, relation.create_with_value)
end
test "test_merge!" do
diff --git a/activerecord/test/cases/relation/or_test.rb b/activerecord/test/cases/relation/or_test.rb
index 4efc742d5a..2796595523 100644
--- a/activerecord/test/cases/relation/or_test.rb
+++ b/activerecord/test/cases/relation/or_test.rb
@@ -61,8 +61,8 @@ module ActiveRecord
def test_or_when_grouping
groups = Post.where("id < 10").group("body").select("body, COUNT(*) AS c")
- expected = groups.having("COUNT(*) > 1 OR body like 'Such%'").to_a.map {|o| [o.body, o.c] }
- assert_equal expected, groups.having("COUNT(*) > 1").or(groups.having("body like 'Such%'")).to_a.map {|o| [o.body, o.c] }
+ expected = groups.having("COUNT(*) > 1 OR body like 'Such%'").to_a.map { |o| [o.body, o.c] }
+ assert_equal expected, groups.having("COUNT(*) > 1").or(groups.having("body like 'Such%'")).to_a.map { |o| [o.body, o.c] }
end
def test_or_with_named_scope
diff --git a/activerecord/test/cases/relation/where_chain_test.rb b/activerecord/test/cases/relation/where_chain_test.rb
index 3d93cb7bce..a96d1ae5b5 100644
--- a/activerecord/test/cases/relation/where_chain_test.rb
+++ b/activerecord/test/cases/relation/where_chain_test.rb
@@ -26,7 +26,7 @@ module ActiveRecord
def test_association_not_eq
expected = Arel::Nodes::Grouping.new(Comment.arel_table[@name].not_eq(Arel::Nodes::BindParam.new))
- relation = Post.joins(:comments).where.not(comments: {title: "hello"})
+ relation = Post.joins(:comments).where.not(comments: { title: "hello" })
assert_equal(expected.to_sql, relation.where_clause.ast.to_sql)
end
diff --git a/activerecord/test/cases/relation/where_test.rb b/activerecord/test/cases/relation/where_test.rb
index ad9008ea4d..ce4e041793 100644
--- a/activerecord/test/cases/relation/where_test.rb
+++ b/activerecord/test/cases/relation/where_test.rb
@@ -196,7 +196,7 @@ module ActiveRecord
end
def test_where_error
- assert_raises(ActiveRecord::StatementInvalid) do
+ assert_nothing_raised do
Post.where(id: { "posts.author_id" => 10 }).first
end
end
diff --git a/activerecord/test/cases/relation_test.rb b/activerecord/test/cases/relation_test.rb
index 0802afac5a..103075d09c 100644
--- a/activerecord/test/cases/relation_test.rb
+++ b/activerecord/test/cases/relation_test.rb
@@ -70,7 +70,7 @@ module ActiveRecord
def test_has_values
relation = Relation.new(Post, Post.arel_table, Post.predicate_builder)
relation.where! relation.table[:id].eq(10)
- assert_equal({id: 10}, relation.where_values_hash)
+ assert_equal({ id: 10 }, relation.where_values_hash)
end
def test_values_wrong_table
@@ -108,8 +108,8 @@ module ActiveRecord
def test_create_with_value_with_wheres
relation = Relation.new(Post, Post.arel_table, Post.predicate_builder)
relation.where! relation.table[:id].eq(10)
- relation.create_with_value = {hello: "world"}
- assert_equal({hello: "world", id: 10}, relation.scope_for_create)
+ relation.create_with_value = { hello: "world" }
+ assert_equal({ hello: "world", id: 10 }, relation.scope_for_create)
end
# FIXME: is this really wanted or expected behavior?
@@ -120,7 +120,7 @@ module ActiveRecord
relation.where! relation.table[:id].eq(10)
assert_equal({}, relation.scope_for_create)
- relation.create_with_value = {hello: "world"}
+ relation.create_with_value = { hello: "world" }
assert_equal({}, relation.scope_for_create)
end
@@ -156,9 +156,9 @@ module ActiveRecord
test "merging a hash into a relation" do
relation = Relation.new(Post, Post.arel_table, Post.predicate_builder)
- relation = relation.merge where: {name: :lol}, readonly: true
+ relation = relation.merge where: { name: :lol }, readonly: true
- assert_equal({"name"=>:lol}, relation.where_clause.to_h)
+ assert_equal({ "name"=>:lol }, relation.where_clause.to_h)
assert_equal true, relation.readonly_value
end
@@ -223,7 +223,7 @@ module ActiveRecord
def test_relation_merging_with_merged_joins_as_symbols
special_comments_with_ratings = SpecialComment.joins(:ratings)
posts_with_special_comments_with_ratings = Post.group("posts.id").joins(:special_comments).merge(special_comments_with_ratings)
- assert_equal 3, authors(:david).posts.merge(posts_with_special_comments_with_ratings).count.length
+ assert_equal({ 2=>1, 4=>3, 5=>1 }, authors(:david).posts.merge(posts_with_special_comments_with_ratings).count)
end
def test_relation_merging_with_joins_as_join_dependency_pick_proper_parent
@@ -273,7 +273,7 @@ module ActiveRecord
join_string = "LEFT OUTER JOIN #{Rating.quoted_table_name} ON #{SpecialComment.quoted_table_name}.id = #{Rating.quoted_table_name}.comment_id"
special_comments_with_ratings = SpecialComment.joins join_string
posts_with_special_comments_with_ratings = Post.group("posts.id").joins(:special_comments).merge(special_comments_with_ratings)
- assert_equal 3, authors(:david).posts.merge(posts_with_special_comments_with_ratings).count.length
+ assert_equal({ 2=>1, 4=>3, 5=>1 }, authors(:david).posts.merge(posts_with_special_comments_with_ratings).count)
end
class EnsureRoundTripTypeCasting < ActiveRecord::Type::Value
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index 74a5b79dfd..3efaace69d 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -240,6 +240,15 @@ class RelationTest < ActiveRecord::TestCase
assert_raises(ActiveRecord::IrreversibleOrderError) do
Topic.order("concat(author_name, title)").reverse_order
end
+ assert_raises(ActiveRecord::IrreversibleOrderError) do
+ Topic.order("concat(lower(author_name), title)").reverse_order
+ end
+ assert_raises(ActiveRecord::IrreversibleOrderError) do
+ Topic.order("concat(author_name, lower(title))").reverse_order
+ end
+ assert_raises(ActiveRecord::IrreversibleOrderError) do
+ Topic.order("concat(lower(author_name), title, length(title)").reverse_order
+ end
end
def test_reverse_order_with_nulls_first_or_last
@@ -384,7 +393,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_select_with_block
- even_ids = Developer.all.select {|d| d.id % 2 == 0 }.map(&:id)
+ even_ids = Developer.all.select { |d| d.id % 2 == 0 }.map(&:id)
assert_equal [2, 4, 6, 8, 10], even_ids.sort
end
@@ -526,7 +535,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_find_on_hash_conditions
- assert_equal Topic.all.merge!(where: {approved: false}).to_a, Topic.where(approved: false).to_a
+ assert_equal Topic.all.merge!(where: { approved: false }).to_a, Topic.where(approved: false).to_a
end
def test_joins_with_string_array
@@ -953,7 +962,6 @@ class RelationTest < ActiveRecord::TestCase
}
end
-
def test_find_all_using_where_with_relation_with_select_to_build_subquery
david = authors(:david)
assert_queries(1) {
@@ -1226,8 +1234,8 @@ class RelationTest < ActiveRecord::TestCase
assert posts.any? # Uses COUNT()
assert ! posts.where(id: nil).any?
- assert posts.any? {|p| p.id > 0 }
- assert ! posts.any? {|p| p.id <= 0 }
+ assert posts.any? { |p| p.id > 0 }
+ assert ! posts.any? { |p| p.id <= 0 }
end
assert posts.loaded?
@@ -1238,8 +1246,8 @@ class RelationTest < ActiveRecord::TestCase
assert_queries(2) do
assert posts.many? # Uses COUNT()
- assert posts.many? {|p| p.id > 0 }
- assert ! posts.many? {|p| p.id < 2 }
+ assert posts.many? { |p| p.id > 0 }
+ assert ! posts.many? { |p| p.id < 2 }
end
assert posts.loaded?
@@ -1261,8 +1269,8 @@ class RelationTest < ActiveRecord::TestCase
assert ! posts.loaded?
assert_queries(1) do
- assert posts.none? {|p| p.id < 0 }
- assert ! posts.none? {|p| p.id == 1 }
+ assert posts.none? { |p| p.id < 0 }
+ assert ! posts.none? { |p| p.id == 1 }
end
assert posts.loaded?
@@ -1277,8 +1285,8 @@ class RelationTest < ActiveRecord::TestCase
assert ! posts.loaded?
assert_queries(1) do
- assert ! posts.one? {|p| p.id < 3 }
- assert posts.one? {|p| p.id == 1 }
+ assert ! posts.one? { |p| p.id < 3 }
+ assert posts.one? { |p| p.id == 1 }
end
assert posts.loaded?
@@ -1364,11 +1372,11 @@ class RelationTest < ActiveRecord::TestCase
end
def test_first_or_create_with_array
- several_green_birds = Bird.where(color: "green").first_or_create([{name: "parrot"}, {name: "parakeet"}])
+ several_green_birds = Bird.where(color: "green").first_or_create([{ name: "parrot" }, { name: "parakeet" }])
assert_kind_of Array, several_green_birds
several_green_birds.each { |bird| assert bird.persisted? }
- same_parrot = Bird.where(color: "green").first_or_create([{name: "hummingbird"}, {name: "macaw"}])
+ same_parrot = Bird.where(color: "green").first_or_create([{ name: "hummingbird" }, { name: "macaw" }])
assert_kind_of Bird, same_parrot
assert_equal several_green_birds.first, same_parrot
end
@@ -1412,17 +1420,17 @@ class RelationTest < ActiveRecord::TestCase
end
def test_first_or_create_with_valid_array
- several_green_birds = Bird.where(color: "green").first_or_create!([{name: "parrot"}, {name: "parakeet"}])
+ several_green_birds = Bird.where(color: "green").first_or_create!([{ name: "parrot" }, { name: "parakeet" }])
assert_kind_of Array, several_green_birds
several_green_birds.each { |bird| assert bird.persisted? }
- same_parrot = Bird.where(color: "green").first_or_create!([{name: "hummingbird"}, {name: "macaw"}])
+ same_parrot = Bird.where(color: "green").first_or_create!([{ name: "hummingbird" }, { name: "macaw" }])
assert_kind_of Bird, same_parrot
assert_equal several_green_birds.first, same_parrot
end
def test_first_or_create_with_invalid_array
- assert_raises(ActiveRecord::RecordInvalid) { Bird.where(color: "green").first_or_create!([ {name: "parrot"}, {pirate_id: 1} ]) }
+ assert_raises(ActiveRecord::RecordInvalid) { Bird.where(color: "green").first_or_create!([ { name: "parrot" }, { pirate_id: 1 } ]) }
end
def test_first_or_initialize
@@ -1556,8 +1564,8 @@ class RelationTest < ActiveRecord::TestCase
end
def test_unscoped_block_style
- assert_equal "honda", CoolCar.unscoped { CoolCar.order_using_new_style.limit(1).first.name}
- assert_equal "honda", FastCar.unscoped { FastCar.order_using_new_style.limit(1).first.name}
+ assert_equal "honda", CoolCar.unscoped { CoolCar.order_using_new_style.limit(1).first.name }
+ assert_equal "honda", FastCar.unscoped { FastCar.order_using_new_style.limit(1).first.name }
end
def test_intersection_with_array
diff --git a/activerecord/test/cases/result_test.rb b/activerecord/test/cases/result_test.rb
index 8bbd4b3bc5..949086fda0 100644
--- a/activerecord/test/cases/result_test.rb
+++ b/activerecord/test/cases/result_test.rb
@@ -16,20 +16,20 @@ module ActiveRecord
test "to_hash returns row_hashes" do
assert_equal [
- {"col_1" => "row 1 col 1", "col_2" => "row 1 col 2"},
- {"col_1" => "row 2 col 1", "col_2" => "row 2 col 2"},
- {"col_1" => "row 3 col 1", "col_2" => "row 3 col 2"},
+ { "col_1" => "row 1 col 1", "col_2" => "row 1 col 2" },
+ { "col_1" => "row 2 col 1", "col_2" => "row 2 col 2" },
+ { "col_1" => "row 3 col 1", "col_2" => "row 3 col 2" },
], result.to_hash
end
test "first returns first row as a hash" do
assert_equal(
- {"col_1" => "row 1 col 1", "col_2" => "row 1 col 2"}, result.first)
+ { "col_1" => "row 1 col 1", "col_2" => "row 1 col 2" }, result.first)
end
test "last returns last row as a hash" do
assert_equal(
- {"col_1" => "row 3 col 1", "col_2" => "row 3 col 2"}, result.last)
+ { "col_1" => "row 3 col 1", "col_2" => "row 3 col 2" }, result.last)
end
test "each with block returns row hashes" do
diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb
index 2ad3da94e4..33baf84ef2 100644
--- a/activerecord/test/cases/schema_dumper_test.rb
+++ b/activerecord/test/cases/schema_dumper_test.rb
@@ -76,11 +76,11 @@ class SchemaDumperTest < ActiveRecord::TestCase
assert matches.all? if required
matches.compact!
return assert(true) if matches.empty?
- assert_equal 1, matches.map{ |match| match.offset(0).first }.uniq.length
+ assert_equal 1, matches.map { |match| match.offset(0).first }.uniq.length
end
def column_definition_lines(output = standard_dump)
- output.scan(/^( *)create_table.*?\n(.*?)^\1end/m).map{ |m| m.last.split(/\n/) }
+ output.scan(/^( *)create_table.*?\n(.*?)^\1end/m).map { |m| m.last.split(/\n/) }
end
def test_types_line_up
diff --git a/activerecord/test/cases/scoping/default_scoping_test.rb b/activerecord/test/cases/scoping/default_scoping_test.rb
index effecfd294..6cfe4b9581 100644
--- a/activerecord/test/cases/scoping/default_scoping_test.rb
+++ b/activerecord/test/cases/scoping/default_scoping_test.rb
@@ -132,7 +132,7 @@ class DefaultScopingTest < ActiveRecord::TestCase
assert_equal expected, received
expected_2 = Developer.order("salary DESC").collect(&:name)
- received_2 = DeveloperOrderedBySalary.select("id").where("name" => "Jamis").unscope({where: :name}, :select).collect(&:name)
+ received_2 = DeveloperOrderedBySalary.select("id").where("name" => "Jamis").unscope({ where: :name }, :select).collect(&:name)
assert_equal expected_2, received_2
expected_3 = Developer.order("salary DESC").collect(&:name)
diff --git a/activerecord/test/cases/scoping/named_scoping_test.rb b/activerecord/test/cases/scoping/named_scoping_test.rb
index 4e799d6dc0..2f328e6e70 100644
--- a/activerecord/test/cases/scoping/named_scoping_test.rb
+++ b/activerecord/test/cases/scoping/named_scoping_test.rb
@@ -69,9 +69,9 @@ class NamedScopingTest < ActiveRecord::TestCase
end
def test_scopes_with_options_limit_finds_to_those_matching_the_criteria_specified
- assert !Topic.all.merge!(where: {approved: true}).to_a.empty?
+ assert !Topic.all.merge!(where: { approved: true }).to_a.empty?
- assert_equal Topic.all.merge!(where: {approved: true}).to_a, Topic.approved
+ assert_equal Topic.all.merge!(where: { approved: true }).to_a, Topic.approved
assert_equal Topic.where(approved: true).count, Topic.approved.count
end
@@ -82,7 +82,7 @@ class NamedScopingTest < ActiveRecord::TestCase
end
def test_scopes_are_composable
- assert_equal((approved = Topic.all.merge!(where: {approved: true}).to_a), Topic.approved)
+ assert_equal((approved = Topic.all.merge!(where: { approved: true }).to_a), Topic.approved)
assert_equal((replied = Topic.all.merge!(where: "replies_count > 0").to_a), Topic.replied)
assert !(approved == replied)
assert !(approved & replied).empty?
@@ -327,12 +327,12 @@ class NamedScopingTest < ActiveRecord::TestCase
conflicts.each do |name|
e = assert_raises(ArgumentError, "scope `#{name}` should not be allowed") do
- klass.class_eval { scope name, ->{ where(approved: true) } }
+ klass.class_eval { scope name, -> { where(approved: true) } }
end
assert_match(/You tried to define a scope named \"#{name}\" on the model/, e.message)
e = assert_raises(ArgumentError, "scope `#{name}` should not be allowed") do
- subklass.class_eval { scope name, ->{ where(approved: true) } }
+ subklass.class_eval { scope name, -> { where(approved: true) } }
end
assert_match(/You tried to define a scope named \"#{name}\" on the model/, e.message)
end
@@ -340,12 +340,12 @@ class NamedScopingTest < ActiveRecord::TestCase
non_conflicts.each do |name|
assert_nothing_raised do
silence_warnings do
- klass.class_eval { scope name, ->{ where(approved: true) } }
+ klass.class_eval { scope name, -> { where(approved: true) } }
end
end
assert_nothing_raised do
- subklass.class_eval { scope name, ->{ where(approved: true) } }
+ subklass.class_eval { scope name, -> { where(approved: true) } }
end
end
end
@@ -431,12 +431,12 @@ class NamedScopingTest < ActiveRecord::TestCase
assert_equal 4, Topic.approved.count
assert_queries(5) do
- Topic.approved.find_each(batch_size: 1) {|t| assert t.approved? }
+ Topic.approved.find_each(batch_size: 1) { |t| assert t.approved? }
end
assert_queries(3) do
Topic.approved.find_in_batches(batch_size: 2) do |group|
- group.each {|t| assert t.approved? }
+ group.each { |t| assert t.approved? }
end
end
end
@@ -462,7 +462,7 @@ class NamedScopingTest < ActiveRecord::TestCase
[:public_method, :protected_method, :private_method].each do |reserved_method|
assert Topic.respond_to?(reserved_method, true)
ActiveRecord::Base.logger.expects(:warn)
- silence_warnings { Topic.scope(reserved_method, -> { }) }
+ silence_warnings { Topic.scope(reserved_method, -> {}) }
end
end
diff --git a/activerecord/test/cases/scoping/relation_scoping_test.rb b/activerecord/test/cases/scoping/relation_scoping_test.rb
index 0428e1640e..a46123f451 100644
--- a/activerecord/test/cases/scoping/relation_scoping_test.rb
+++ b/activerecord/test/cases/scoping/relation_scoping_test.rb
@@ -246,7 +246,7 @@ class NestedRelationScopingTest < ActiveRecord::TestCase
devs = Developer.all
sql = devs.to_sql
assert_match "(salary = 80000)", sql
- assert_match "LIMIT 10", sql
+ assert_match(/LIMIT 10|ROWNUM <= 10|FETCH FIRST 10 ROWS ONLY/, sql)
end
end
end
diff --git a/activerecord/test/cases/serialized_attribute_test.rb b/activerecord/test/cases/serialized_attribute_test.rb
index ceb0d5441b..bebd856faf 100644
--- a/activerecord/test/cases/serialized_attribute_test.rb
+++ b/activerecord/test/cases/serialized_attribute_test.rb
@@ -157,6 +157,13 @@ class SerializedAttributeTest < ActiveRecord::TestCase
assert_equal(settings, Topic.find(topic.id).content)
end
+ def test_where_by_serialized_attribute_with_hash
+ settings = { "color" => "green" }
+ Topic.serialize(:content, Hash)
+ topic = Topic.create!(content: settings)
+ assert_equal topic, Topic.where(content: settings).take
+ end
+
def test_serialized_default_class
Topic.serialize(:content, Hash)
topic = Topic.new
diff --git a/activerecord/test/cases/statement_cache_test.rb b/activerecord/test/cases/statement_cache_test.rb
index df75dd3247..f45f63c68e 100644
--- a/activerecord/test/cases/statement_cache_test.rb
+++ b/activerecord/test/cases/statement_cache_test.rb
@@ -25,7 +25,6 @@ module ActiveRecord
assert_equal "my other book", b[0].name
end
-
def test_statement_cache_id
b1 = Book.create(name: "my book")
b2 = Book.create(name: "my other book")
diff --git a/activerecord/test/cases/suppressor_test.rb b/activerecord/test/cases/suppressor_test.rb
index 64f39d8574..a7d16b7cdb 100644
--- a/activerecord/test/cases/suppressor_test.rb
+++ b/activerecord/test/cases/suppressor_test.rb
@@ -64,7 +64,7 @@ class SuppressorTest < ActiveRecord::TestCase
def test_suppresses_when_nested_multiple_times
assert_no_difference -> { Notification.count } do
Notification.suppress do
- Notification.suppress { }
+ Notification.suppress {}
Notification.create
Notification.create!
Notification.new.save
diff --git a/activerecord/test/cases/tasks/database_tasks_test.rb b/activerecord/test/cases/tasks/database_tasks_test.rb
index 0519c70ac7..079db3fe8b 100644
--- a/activerecord/test/cases/tasks/database_tasks_test.rb
+++ b/activerecord/test/cases/tasks/database_tasks_test.rb
@@ -64,12 +64,12 @@ module ActiveRecord
instance.expects(:structure_dump).with("awesome-file.sql")
ActiveRecord::Tasks::DatabaseTasks.register_task(/foo/, klazz)
- ActiveRecord::Tasks::DatabaseTasks.structure_dump({"adapter" => :foo}, "awesome-file.sql")
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump({ "adapter" => :foo }, "awesome-file.sql")
end
def test_unregistered_task
assert_raise(ActiveRecord::Tasks::DatabaseNotSupported) do
- ActiveRecord::Tasks::DatabaseTasks.structure_dump({"adapter" => :bar}, "awesome-file.sql")
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump({ "adapter" => :bar }, "awesome-file.sql")
end
end
end
@@ -87,7 +87,7 @@ module ActiveRecord
class DatabaseTasksCreateAllTest < ActiveRecord::TestCase
def setup
- @configurations = {"development" => {"database" => "my-db"}}
+ @configurations = { "development" => { "database" => "my-db" } }
ActiveRecord::Base.stubs(:configurations).returns(@configurations)
end
@@ -145,9 +145,9 @@ module ActiveRecord
class DatabaseTasksCreateCurrentTest < ActiveRecord::TestCase
def setup
@configurations = {
- "development" => {"database" => "dev-db"},
- "test" => {"database" => "test-db"},
- "production" => {"database" => "prod-db"}
+ "development" => { "database" => "dev-db" },
+ "test" => { "database" => "test-db" },
+ "production" => { "database" => "prod-db" }
}
ActiveRecord::Base.stubs(:configurations).returns(@configurations)
@@ -213,7 +213,7 @@ module ActiveRecord
class DatabaseTasksDropAllTest < ActiveRecord::TestCase
def setup
- @configurations = {development: {"database" => "my-db"}}
+ @configurations = { development: { "database" => "my-db" } }
ActiveRecord::Base.stubs(:configurations).returns(@configurations)
end
@@ -271,9 +271,9 @@ module ActiveRecord
class DatabaseTasksDropCurrentTest < ActiveRecord::TestCase
def setup
@configurations = {
- "development" => {"database" => "dev-db"},
- "test" => {"database" => "test-db"},
- "production" => {"database" => "prod-db"}
+ "development" => { "database" => "dev-db" },
+ "test" => { "database" => "test-db" },
+ "production" => { "database" => "prod-db" }
}
ActiveRecord::Base.stubs(:configurations).returns(@configurations)
@@ -358,9 +358,9 @@ module ActiveRecord
class DatabaseTasksPurgeCurrentTest < ActiveRecord::TestCase
def test_purges_current_environment_database
configurations = {
- "development" => {"database" => "dev-db"},
- "test" => {"database" => "test-db"},
- "production" => {"database" => "prod-db"}
+ "development" => { "database" => "dev-db" },
+ "test" => { "database" => "test-db" },
+ "production" => { "database" => "prod-db" }
}
ActiveRecord::Base.stubs(:configurations).returns(configurations)
@@ -374,7 +374,7 @@ module ActiveRecord
class DatabaseTasksPurgeAllTest < ActiveRecord::TestCase
def test_purge_all_local_configurations
- configurations = {development: {"database" => "my-db"}}
+ configurations = { development: { "database" => "my-db" } }
ActiveRecord::Base.stubs(:configurations).returns(configurations)
ActiveRecord::Tasks::DatabaseTasks.expects(:purge).
@@ -412,7 +412,7 @@ module ActiveRecord
ADAPTERS_TASKS.each do |k, v|
define_method("test_#{k}_structure_dump") do
eval("@#{v}").expects(:structure_dump).with("awesome-file.sql")
- ActiveRecord::Tasks::DatabaseTasks.structure_dump({"adapter" => k}, "awesome-file.sql")
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump({ "adapter" => k }, "awesome-file.sql")
end
end
end
@@ -423,7 +423,7 @@ module ActiveRecord
ADAPTERS_TASKS.each do |k, v|
define_method("test_#{k}_structure_load") do
eval("@#{v}").expects(:structure_load).with("awesome-file.sql")
- ActiveRecord::Tasks::DatabaseTasks.structure_load({"adapter" => k}, "awesome-file.sql")
+ ActiveRecord::Tasks::DatabaseTasks.structure_load({ "adapter" => k }, "awesome-file.sql")
end
end
end
@@ -443,7 +443,7 @@ module ActiveRecord
end
class DatabaseTasksCheckSchemaFileSpecifiedFormatsTest < ActiveRecord::TestCase
- {ruby: "schema.rb", sql: "structure.sql"}.each_pair do |fmt, filename|
+ { ruby: "schema.rb", sql: "structure.sql" }.each_pair do |fmt, filename|
define_method("test_check_schema_file_for_#{fmt}_format") do
ActiveRecord::Tasks::DatabaseTasks.stubs(:db_dir).returns("/tmp")
assert_equal "/tmp/#{filename}", ActiveRecord::Tasks::DatabaseTasks.schema_file(fmt)
diff --git a/activerecord/test/cases/test_case.rb b/activerecord/test/cases/test_case.rb
index b0f5b5ca4a..60ac3e08a1 100644
--- a/activerecord/test/cases/test_case.rb
+++ b/activerecord/test/cases/test_case.rb
@@ -1,13 +1,29 @@
require "active_support/test_case"
+require "active_support/testing/autorun"
+require "active_support/testing/method_call_assertions"
require "active_support/testing/stream"
require "active_support/core_ext/regexp"
+require "active_record/fixtures"
+
+require "cases/validations_repair_helper"
module ActiveRecord
# = Active Record Test Case
#
# Defines some test assertions to test against SQL queries.
class TestCase < ActiveSupport::TestCase #:nodoc:
+ include ActiveSupport::Testing::MethodCallAssertions
include ActiveSupport::Testing::Stream
+ include ActiveRecord::TestFixtures
+ include ActiveRecord::ValidationsRepairHelper
+
+ self.fixture_path = FIXTURES_ROOT
+ self.use_instantiated_fixtures = false
+ self.use_transactional_tests = true
+
+ def create_fixtures(*fixture_set_names, &block)
+ ActiveRecord::FixtureSet.create_fixtures(ActiveRecord::TestCase.fixture_path, fixture_set_names, fixture_class_names, &block)
+ end
def teardown
SQLCounter.clear_log
@@ -24,7 +40,7 @@ module ActiveRecord
ensure
failed_patterns = []
patterns_to_match.each do |pattern|
- failed_patterns << pattern unless SQLCounter.log_all.any?{ |sql| pattern === sql }
+ failed_patterns << pattern unless SQLCounter.log_all.any? { |sql| pattern === sql }
end
assert failed_patterns.empty?, "Query pattern(s) #{failed_patterns.map(&:inspect).join(', ')} not found.#{SQLCounter.log.size == 0 ? '' : "\nQueries:\n#{SQLCounter.log.join("\n")}"}"
end
@@ -86,7 +102,7 @@ module ActiveRecord
def clear_log; self.log = []; self.log_all = []; end
end
- self.clear_log
+ clear_log
self.ignored_sql = [/^PRAGMA/, /^SELECT currval/, /^SELECT CAST/, /^SELECT @@IDENTITY/, /^SELECT @@ROWCOUNT/, /^SAVEPOINT/, /^ROLLBACK TO SAVEPOINT/, /^RELEASE SAVEPOINT/, /^SHOW max_identifier_length/, /^BEGIN/, /^COMMIT/]
diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb
index 519d9db601..cd83518e84 100644
--- a/activerecord/test/cases/timestamp_test.rb
+++ b/activerecord/test/cases/timestamp_test.rb
@@ -462,7 +462,7 @@ class TimestampTest < ActiveRecord::TestCase
def test_index_is_created_for_both_timestamps
ActiveRecord::Base.connection.create_table(:foos, force: true) do |t|
- t.timestamps(:foos, null: true, index: true)
+ t.timestamps null: true, index: true
end
indexes = ActiveRecord::Base.connection.indexes("foos")
diff --git a/activerecord/test/cases/touch_later_test.rb b/activerecord/test/cases/touch_later_test.rb
index 697447a4f3..d1e8c649d9 100644
--- a/activerecord/test/cases/touch_later_test.rb
+++ b/activerecord/test/cases/touch_later_test.rb
@@ -24,6 +24,15 @@ class TouchLaterTest < ActiveRecord::TestCase
assert_not invoice.changed?
end
+ def test_touch_later_respects_no_touching_policy
+ time = Time.now.utc - 25.days
+ topic = Topic.create!(updated_at: time, created_at: time)
+ Topic.no_touching do
+ topic.touch_later
+ end
+ assert_equal time.to_i, topic.updated_at.to_i
+ end
+
def test_touch_later_update_the_attributes
time = Time.now.utc - 25.days
topic = Topic.create!(updated_at: time, created_at: time)
diff --git a/activerecord/test/cases/transaction_callbacks_test.rb b/activerecord/test/cases/transaction_callbacks_test.rb
index efb420b403..bd50fe55e9 100644
--- a/activerecord/test/cases/transaction_callbacks_test.rb
+++ b/activerecord/test/cases/transaction_callbacks_test.rb
@@ -17,7 +17,7 @@ class TransactionCallbacksTest < ActiveRecord::TestCase
attr_accessor :save_on_after_create
after_create do
- self.save! if save_on_after_create
+ save! if save_on_after_create
end
def history
@@ -68,17 +68,17 @@ class TransactionCallbacksTest < ActiveRecord::TestCase
def do_before_commit(on)
blocks = @before_commit[on] if defined?(@before_commit)
- blocks.each{|b| b.call(self)} if blocks
+ blocks.each { |b| b.call(self) } if blocks
end
def do_after_commit(on)
blocks = @after_commit[on] if defined?(@after_commit)
- blocks.each{|b| b.call(self)} if blocks
+ blocks.each { |b| b.call(self) } if blocks
end
def do_after_rollback(on)
blocks = @after_rollback[on] if defined?(@after_rollback)
- blocks.each{|b| b.call(self)} if blocks
+ blocks.each { |b| b.call(self) } if blocks
end
end
@@ -101,8 +101,8 @@ class TransactionCallbacksTest < ActiveRecord::TestCase
end
def test_call_after_commit_after_transaction_commits
- @first.after_commit_block{|r| r.history << :after_commit}
- @first.after_rollback_block{|r| r.history << :after_rollback}
+ @first.after_commit_block { |r| r.history << :after_commit }
+ @first.after_rollback_block { |r| r.history << :after_rollback }
@first.save!
assert_equal [:after_commit], @first.history
@@ -155,7 +155,7 @@ class TransactionCallbacksTest < ActiveRecord::TestCase
end
def test_only_call_after_commit_on_top_level_transactions
- @first.after_commit_block{|r| r.history << :after_commit}
+ @first.after_commit_block { |r| r.history << :after_commit }
assert @first.history.empty?
@first.transaction do
@@ -168,8 +168,8 @@ class TransactionCallbacksTest < ActiveRecord::TestCase
end
def test_call_after_rollback_after_transaction_rollsback
- @first.after_commit_block{|r| r.history << :after_commit}
- @first.after_rollback_block{|r| r.history << :after_rollback}
+ @first.after_commit_block { |r| r.history << :after_commit }
+ @first.after_rollback_block { |r| r.history << :after_rollback }
Topic.transaction do
@first.save!
@@ -245,14 +245,14 @@ class TransactionCallbacksTest < ActiveRecord::TestCase
def test_only_call_after_rollback_on_records_rolled_back_to_a_savepoint
def @first.rollbacks(i=0); @rollbacks ||= 0; @rollbacks += i if i; end
def @first.commits(i=0); @commits ||= 0; @commits += i if i; end
- @first.after_rollback_block{|r| r.rollbacks(1)}
- @first.after_commit_block{|r| r.commits(1)}
+ @first.after_rollback_block { |r| r.rollbacks(1) }
+ @first.after_commit_block { |r| r.commits(1) }
second = TopicWithCallbacks.find(3)
def second.rollbacks(i=0); @rollbacks ||= 0; @rollbacks += i if i; end
def second.commits(i=0); @commits ||= 0; @commits += i if i; end
- second.after_rollback_block{|r| r.rollbacks(1)}
- second.after_commit_block{|r| r.commits(1)}
+ second.after_rollback_block { |r| r.rollbacks(1) }
+ second.after_commit_block { |r| r.commits(1) }
Topic.transaction do
@first.save!
@@ -272,8 +272,8 @@ class TransactionCallbacksTest < ActiveRecord::TestCase
def @first.rollbacks(i=0); @rollbacks ||= 0; @rollbacks += i if i; end
def @first.commits(i=0); @commits ||= 0; @commits += i if i; end
- @first.after_rollback_block{|r| r.rollbacks(1)}
- @first.after_commit_block{|r| r.commits(1)}
+ @first.after_rollback_block { |r| r.rollbacks(1) }
+ @first.after_commit_block { |r| r.commits(1) }
Topic.transaction do
@first.save
@@ -292,7 +292,7 @@ class TransactionCallbacksTest < ActiveRecord::TestCase
end
def test_after_commit_callback_should_not_swallow_errors
- @first.after_commit_block{ fail "boom" }
+ @first.after_commit_block { fail "boom" }
assert_raises(RuntimeError) do
Topic.transaction do
@first.save!
@@ -303,8 +303,8 @@ class TransactionCallbacksTest < ActiveRecord::TestCase
def test_after_commit_callback_when_raise_should_not_restore_state
first = TopicWithCallbacks.new
second = TopicWithCallbacks.new
- first.after_commit_block{ fail "boom" }
- second.after_commit_block{ fail "boom" }
+ first.after_commit_block { fail "boom" }
+ second.after_commit_block { fail "boom" }
begin
Topic.transaction do
@@ -322,7 +322,7 @@ class TransactionCallbacksTest < ActiveRecord::TestCase
def test_after_rollback_callback_should_not_swallow_errors_when_set_to_raise
error_class = Class.new(StandardError)
- @first.after_rollback_block{ raise error_class }
+ @first.after_rollback_block { raise error_class }
assert_raises(error_class) do
Topic.transaction do
@first.save!
@@ -336,8 +336,8 @@ class TransactionCallbacksTest < ActiveRecord::TestCase
first = TopicWithCallbacks.new
second = TopicWithCallbacks.new
- first.after_rollback_block{ raise error_class }
- second.after_rollback_block{ raise error_class }
+ first.after_rollback_block { raise error_class }
+ second.after_rollback_block { raise error_class }
begin
Topic.transaction do
@@ -449,7 +449,6 @@ class CallbacksOnMultipleActionsTest < ActiveRecord::TestCase
end
end
-
class TransactionEnrollmentCallbacksTest < ActiveRecord::TestCase
class TopicWithoutTransactionalEnrollmentCallbacks < ActiveRecord::Base
self.table_name = :topics
diff --git a/activerecord/test/cases/transaction_isolation_test.rb b/activerecord/test/cases/transaction_isolation_test.rb
index f177f0644a..58abfadaf4 100644
--- a/activerecord/test/cases/transaction_isolation_test.rb
+++ b/activerecord/test/cases/transaction_isolation_test.rb
@@ -9,7 +9,7 @@ unless ActiveRecord::Base.connection.supports_transaction_isolation?
test "setting the isolation level raises an error" do
assert_raises(ActiveRecord::TransactionIsolationError) do
- Tag.transaction(isolation: :serializable) { }
+ Tag.transaction(isolation: :serializable) {}
end
end
end
@@ -90,7 +90,7 @@ if ActiveRecord::Base.connection.supports_transaction_isolation?
test "setting isolation when joining a transaction raises an error" do
Tag.transaction do
assert_raises(ActiveRecord::TransactionIsolationError) do
- Tag.transaction(isolation: :serializable) { }
+ Tag.transaction(isolation: :serializable) {}
end
end
end
@@ -98,7 +98,7 @@ if ActiveRecord::Base.connection.supports_transaction_isolation?
test "setting isolation when starting a nested transaction raises error" do
Tag.transaction do
assert_raises(ActiveRecord::TransactionIsolationError) do
- Tag.transaction(requires_new: true, isolation: :serializable) { }
+ Tag.transaction(requires_new: true, isolation: :serializable) {}
end
end
end
diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb
index c8963ada63..8f0b2bd313 100644
--- a/activerecord/test/cases/transactions_test.rb
+++ b/activerecord/test/cases/transactions_test.rb
@@ -493,7 +493,7 @@ class TransactionTest < ActiveRecord::TestCase
def test_rollback_when_commit_raises
assert_called(Topic.connection, :begin_db_transaction) do
- Topic.connection.stub(:commit_db_transaction, ->{ raise("OH NOES") }) do
+ Topic.connection.stub(:commit_db_transaction, -> { raise("OH NOES") }) do
assert_called(Topic.connection, :rollback_db_transaction) do
e = assert_raise RuntimeError do
@@ -692,7 +692,7 @@ class TransactionTest < ActiveRecord::TestCase
klass = Class.new(ActiveRecord::Base) do
self.table_name = "transaction_without_primary_keys"
- after_commit { } # necessary to trigger the has_transactional_callbacks branch
+ after_commit {} # necessary to trigger the has_transactional_callbacks branch
end
assert_no_difference(-> { klass.count }) do
diff --git a/activerecord/test/cases/validations/i18n_generate_message_validation_test.rb b/activerecord/test/cases/validations/i18n_generate_message_validation_test.rb
index d73d287073..a57065ba75 100644
--- a/activerecord/test/cases/validations/i18n_generate_message_validation_test.rb
+++ b/activerecord/test/cases/validations/i18n_generate_message_validation_test.rb
@@ -47,7 +47,7 @@ class I18nGenerateMessageValidationTest < ActiveRecord::TestCase
test "RecordInvalid exception translation falls back to the :errors namespace" do
reset_i18n_load_path do
- I18n.backend.store_translations "en", errors: {messages: {record_invalid: "fallback message"}}
+ I18n.backend.store_translations "en", errors: { messages: { record_invalid: "fallback message" } }
topic = Topic.new
topic.errors.add(:title, :blank)
assert_equal "fallback message", ActiveRecord::RecordInvalid.new(topic).message
@@ -56,28 +56,28 @@ class I18nGenerateMessageValidationTest < ActiveRecord::TestCase
test "translation for 'taken' can be overridden" do
reset_i18n_load_path do
- I18n.backend.store_translations "en", errors: {attributes: {title: {taken: "Custom taken message" }}}
+ I18n.backend.store_translations "en", errors: { attributes: { title: { taken: "Custom taken message" } } }
assert_equal "Custom taken message", @topic.errors.generate_message(:title, :taken, value: "title")
end
end
test "translation for 'taken' can be overridden in activerecord scope" do
reset_i18n_load_path do
- I18n.backend.store_translations "en", activerecord: {errors: {messages: {taken: "Custom taken message" }}}
+ I18n.backend.store_translations "en", activerecord: { errors: { messages: { taken: "Custom taken message" } } }
assert_equal "Custom taken message", @topic.errors.generate_message(:title, :taken, value: "title")
end
end
test "translation for 'taken' can be overridden in activerecord model scope" do
reset_i18n_load_path do
- I18n.backend.store_translations "en", activerecord: {errors: {models: {topic: {taken: "Custom taken message" }}}}
+ I18n.backend.store_translations "en", activerecord: { errors: { models: { topic: { taken: "Custom taken message" } } } }
assert_equal "Custom taken message", @topic.errors.generate_message(:title, :taken, value: "title")
end
end
test "translation for 'taken' can be overridden in activerecord attributes scope" do
reset_i18n_load_path do
- I18n.backend.store_translations "en", activerecord: {errors: {models: {topic: {attributes: {title: {taken: "Custom taken message" }}}}}}
+ I18n.backend.store_translations "en", activerecord: { errors: { models: { topic: { attributes: { title: { taken: "Custom taken message" } } } } } }
assert_equal "Custom taken message", @topic.errors.generate_message(:title, :taken, value: "title")
end
end
diff --git a/activerecord/test/cases/validations/i18n_validation_test.rb b/activerecord/test/cases/validations/i18n_validation_test.rb
index cbb5362f3f..bdae806f7c 100644
--- a/activerecord/test/cases/validations/i18n_validation_test.rb
+++ b/activerecord/test/cases/validations/i18n_validation_test.rb
@@ -12,7 +12,7 @@ class I18nValidationTest < ActiveRecord::TestCase
@old_load_path, @old_backend = I18n.load_path.dup, I18n.backend
I18n.load_path.clear
I18n.backend = I18n::Backend::Simple.new
- I18n.backend.store_translations("en", errors: {messages: {custom: nil}})
+ I18n.backend.store_translations("en", errors: { messages: { custom: nil } })
end
teardown do
@@ -38,11 +38,11 @@ class I18nValidationTest < ActiveRecord::TestCase
COMMON_CASES = [
# [ case, validation_options, generate_message_options]
[ "given no options", {}, {}],
- [ "given custom message", {message: "custom"}, {message: "custom"}],
- [ "given if condition", {if: lambda { true }}, {}],
- [ "given unless condition", {unless: lambda { false }}, {}],
- [ "given option that is not reserved", {format: "jpg"}, {format: "jpg" }],
- [ "given on condition", {on: [:create, :update] }, {}]
+ [ "given custom message", { message: "custom" }, { message: "custom" }],
+ [ "given if condition", { if: lambda { true } }, {}],
+ [ "given unless condition", { unless: lambda { false } }, {}],
+ [ "given option that is not reserved", { format: "jpg" }, { format: "jpg" }],
+ [ "given on condition", { on: [:create, :update] }, {}]
]
COMMON_CASES.each do |name, validation_options, generate_message_options|
@@ -65,8 +65,8 @@ class I18nValidationTest < ActiveRecord::TestCase
end
def test_validates_associated_finds_custom_model_key_translation
- I18n.backend.store_translations "en", activerecord: {errors: {models: {topic: {attributes: {replies: {invalid: "custom message"}}}}}}
- I18n.backend.store_translations "en", activerecord: {errors: {messages: {invalid: "global message"}}}
+ I18n.backend.store_translations "en", activerecord: { errors: { models: { topic: { attributes: { replies: { invalid: "custom message" } } } } } }
+ I18n.backend.store_translations "en", activerecord: { errors: { messages: { invalid: "global message" } } }
Topic.validates_associated :replies
replied_topic.valid?
@@ -74,7 +74,7 @@ class I18nValidationTest < ActiveRecord::TestCase
end
def test_validates_associated_finds_global_default_translation
- I18n.backend.store_translations "en", activerecord: {errors: {messages: {invalid: "global message"}}}
+ I18n.backend.store_translations "en", activerecord: { errors: { messages: { invalid: "global message" } } }
Topic.validates_associated :replies
replied_topic.valid?
diff --git a/activerecord/test/cases/validations/length_validation_test.rb b/activerecord/test/cases/validations/length_validation_test.rb
index 08dd740b01..ba45c6dcc1 100644
--- a/activerecord/test/cases/validations/length_validation_test.rb
+++ b/activerecord/test/cases/validations/length_validation_test.rb
@@ -12,7 +12,6 @@ class LengthValidationTest < ActiveRecord::TestCase
end
end
-
def test_validates_size_of_association
assert_nothing_raised { @owner.validates_size_of :pets, minimum: 1 }
o = @owner.new("name" => "nopets")
@@ -55,7 +54,7 @@ class LengthValidationTest < ActiveRecord::TestCase
assert owner.save
pet_count = Pet.count
- assert_not owner.update_attributes pets_attributes: [ {_destroy: 1, id: pet.id} ]
+ assert_not owner.update_attributes pets_attributes: [ { _destroy: 1, id: pet.id } ]
assert_not owner.valid?
assert owner.errors[:pets].any?
assert_equal pet_count, Pet.count
diff --git a/activerecord/test/cases/validations_test.rb b/activerecord/test/cases/validations_test.rb
index 76510cb80d..5d9aa99497 100644
--- a/activerecord/test/cases/validations_test.rb
+++ b/activerecord/test/cases/validations_test.rb
@@ -156,17 +156,15 @@ class ValidationsTest < ActiveRecord::TestCase
end
def test_numericality_validation_with_mutation
- Topic.class_eval do
+ klass = Class.new(Topic) do
attribute :wibble, :string
validates_numericality_of :wibble, only_integer: true
end
- topic = Topic.new(wibble: "123-4567")
+ topic = klass.new(wibble: "123-4567")
topic.wibble.gsub!("-", "")
assert topic.valid?
- ensure
- Topic.reset_column_information
end
def test_acceptance_validator_doesnt_require_db_connection
diff --git a/activerecord/test/cases/view_test.rb b/activerecord/test/cases/view_test.rb
index 5f85c5ff8b..aa3ff6160c 100644
--- a/activerecord/test/cases/view_test.rb
+++ b/activerecord/test/cases/view_test.rb
@@ -60,7 +60,7 @@ module ViewBehavior
end
def test_attributes
- assert_equal({"id" => 2, "name" => "Ruby for Rails", "status" => 0},
+ assert_equal({ "id" => 2, "name" => "Ruby for Rails", "status" => 0 },
Ebook.first.attributes)
end
@@ -135,7 +135,7 @@ if ActiveRecord::Base.connection.supports_views?
end
def test_attributes
- assert_equal({"name" => "Agile Web Development with Rails", "status" => 2},
+ assert_equal({ "name" => "Agile Web Development with Rails", "status" => 2 },
Paperback.first.attributes)
end
diff --git a/activerecord/test/cases/yaml_serialization_test.rb b/activerecord/test/cases/yaml_serialization_test.rb
index ade6e6095b..5192e5050a 100644
--- a/activerecord/test/cases/yaml_serialization_test.rb
+++ b/activerecord/test/cases/yaml_serialization_test.rb
@@ -22,8 +22,8 @@ class YamlSerializationTest < ActiveRecord::TestCase
end
def test_roundtrip_serialized_column
- topic = Topic.new(content: {omg: :lol})
- assert_equal({omg: :lol}, YAML.load(YAML.dump(topic)).content)
+ topic = Topic.new(content: { omg: :lol })
+ assert_equal({ omg: :lol }, YAML.load(YAML.dump(topic)).content)
end
def test_psych_roundtrip
diff --git a/activerecord/test/models/author.rb b/activerecord/test/models/author.rb
index 8633504d54..fab613afd1 100644
--- a/activerecord/test/models/author.rb
+++ b/activerecord/test/models/author.rb
@@ -67,13 +67,13 @@ class Author < ActiveRecord::Base
before_remove: :log_before_removing,
after_remove: :log_after_removing
has_many :posts_with_proc_callbacks, class_name: "Post",
- before_add: Proc.new {|o, r| o.post_log << "before_adding#{r.id || '<new>'}"},
- after_add: Proc.new {|o, r| o.post_log << "after_adding#{r.id || '<new>'}"},
- before_remove: Proc.new {|o, r| o.post_log << "before_removing#{r.id}"},
- after_remove: Proc.new {|o, r| o.post_log << "after_removing#{r.id}"}
+ before_add: Proc.new { |o, r| o.post_log << "before_adding#{r.id || '<new>'}" },
+ after_add: Proc.new { |o, r| o.post_log << "after_adding#{r.id || '<new>'}" },
+ before_remove: Proc.new { |o, r| o.post_log << "before_removing#{r.id}" },
+ after_remove: Proc.new { |o, r| o.post_log << "after_removing#{r.id}" }
has_many :posts_with_multiple_callbacks, class_name: "Post",
- before_add: [:log_before_adding, Proc.new {|o, r| o.post_log << "before_adding_proc#{r.id || '<new>'}"}],
- after_add: [:log_after_adding, Proc.new {|o, r| o.post_log << "after_adding_proc#{r.id || '<new>'}"}]
+ before_add: [:log_before_adding, Proc.new { |o, r| o.post_log << "before_adding_proc#{r.id || '<new>'}" }],
+ after_add: [:log_after_adding, Proc.new { |o, r| o.post_log << "after_adding_proc#{r.id || '<new>'}" }]
has_many :unchangeable_posts, class_name: "Post", before_add: :raise_exception, after_add: :log_after_adding
has_many :categorizations
diff --git a/activerecord/test/models/book.rb b/activerecord/test/models/book.rb
index edd0281127..4c275fdebb 100644
--- a/activerecord/test/models/book.rb
+++ b/activerecord/test/models/book.rb
@@ -8,7 +8,7 @@ class Book < ActiveRecord::Base
has_many :subscribers, through: :subscriptions
enum status: [:proposed, :written, :published]
- enum read_status: {unread: 0, reading: 2, read: 3}
+ enum read_status: { unread: 0, reading: 2, read: 3 }
enum nullable_status: [:single, :married]
enum language: [:english, :spanish, :french], _prefix: :in
enum author_visibility: [:visible, :invisible], _prefix: true
diff --git a/activerecord/test/models/comment.rb b/activerecord/test/models/comment.rb
index 7315a1af8e..a4b81d56e0 100644
--- a/activerecord/test/models/comment.rb
+++ b/activerecord/test/models/comment.rb
@@ -1,5 +1,5 @@
class Comment < ActiveRecord::Base
- scope :limit_by, lambda {|l| limit(l) }
+ scope :limit_by, lambda { |l| limit(l) }
scope :containing_the_letter_e, -> { where("comments.body LIKE '%e%'") }
scope :not_again, -> { where("comments.body NOT LIKE '%again%'") }
scope :for_first_post, -> { where(post_id: 1) }
@@ -55,6 +55,6 @@ class CommentThatAutomaticallyAltersPostBody < Comment
end
class CommentWithDefaultScopeReferencesAssociation < Comment
- default_scope ->{ includes(:developer).order("developers.name").references(:developer) }
+ default_scope -> { includes(:developer).order("developers.name").references(:developer) }
belongs_to :developer
end
diff --git a/activerecord/test/models/customer.rb b/activerecord/test/models/customer.rb
index 71afd0866e..60af7c2247 100644
--- a/activerecord/test/models/customer.rb
+++ b/activerecord/test/models/customer.rb
@@ -5,7 +5,7 @@ class Customer < ActiveRecord::Base
composed_of :balance, class_name: "Money", mapping: %w(balance amount), converter: Proc.new(&:to_money)
composed_of :gps_location, allow_nil: true
composed_of :non_blank_gps_location, class_name: "GpsLocation", allow_nil: true, mapping: %w(gps_location gps_location),
- converter: lambda { |gps| self.gps_conversion_was_run = true; gps.blank? ? nil : GpsLocation.new(gps)}
+ converter: lambda { |gps| self.gps_conversion_was_run = true; gps.blank? ? nil : GpsLocation.new(gps) }
composed_of :fullname, mapping: %w(name to_s), constructor: Proc.new { |name| Fullname.parse(name) }, converter: :parse
composed_of :fullname_no_converter, mapping: %w(name to_s), class_name: "Fullname"
end
diff --git a/activerecord/test/models/invoice.rb b/activerecord/test/models/invoice.rb
index 44ee717187..4be5a00193 100644
--- a/activerecord/test/models/invoice.rb
+++ b/activerecord/test/models/invoice.rb
@@ -1,4 +1,4 @@
class Invoice < ActiveRecord::Base
has_many :line_items, autosave: true
- before_save {|record| record.balance = record.line_items.map(&:amount).sum }
+ before_save { |record| record.balance = record.line_items.map(&:amount).sum }
end
diff --git a/activerecord/test/models/member.rb b/activerecord/test/models/member.rb
index 93dfc8253f..36f2461b84 100644
--- a/activerecord/test/models/member.rb
+++ b/activerecord/test/models/member.rb
@@ -5,7 +5,7 @@ class Member < ActiveRecord::Base
has_one :club, through: :current_membership
has_one :selected_club, through: :selected_membership, source: :club
has_one :favourite_club, -> { where "memberships.favourite = ?", true }, through: :membership, source: :club
- has_one :hairy_club, -> { where clubs: {name: "Moustache and Eyebrow Fancier Club"} }, through: :membership, source: :club
+ has_one :hairy_club, -> { where clubs: { name: "Moustache and Eyebrow Fancier Club" } }, through: :membership, source: :club
has_one :sponsor, as: :sponsorable
has_one :sponsor_club, through: :sponsor
has_one :member_detail, inverse_of: false
diff --git a/activerecord/test/models/person.rb b/activerecord/test/models/person.rb
index 84ffddb74e..18994d6f18 100644
--- a/activerecord/test/models/person.rb
+++ b/activerecord/test/models/person.rb
@@ -60,7 +60,6 @@ class PersonWithDependentNullifyJobs < ActiveRecord::Base
has_many :jobs, source: :job, through: :references, dependent: :nullify
end
-
class LoosePerson < ActiveRecord::Base
self.table_name = "people"
self.abstract_class = true
diff --git a/activerecord/test/models/pirate.rb b/activerecord/test/models/pirate.rb
index 80a941874b..2dc8f9bd84 100644
--- a/activerecord/test/models/pirate.rb
+++ b/activerecord/test/models/pirate.rb
@@ -9,10 +9,10 @@ class Pirate < ActiveRecord::Base
before_remove: :log_before_remove,
after_remove: :log_after_remove
has_and_belongs_to_many :parrots_with_proc_callbacks, class_name: "Parrot",
- before_add: proc {|p,pa| p.ship_log << "before_adding_proc_parrot_#{pa.id || '<new>'}"},
- after_add: proc {|p,pa| p.ship_log << "after_adding_proc_parrot_#{pa.id || '<new>'}"},
- before_remove: proc {|p,pa| p.ship_log << "before_removing_proc_parrot_#{pa.id}"},
- after_remove: proc {|p,pa| p.ship_log << "after_removing_proc_parrot_#{pa.id}"}
+ before_add: proc { |p,pa| p.ship_log << "before_adding_proc_parrot_#{pa.id || '<new>'}" },
+ after_add: proc { |p,pa| p.ship_log << "after_adding_proc_parrot_#{pa.id || '<new>'}" },
+ before_remove: proc { |p,pa| p.ship_log << "before_removing_proc_parrot_#{pa.id}" },
+ after_remove: proc { |p,pa| p.ship_log << "after_removing_proc_parrot_#{pa.id}" }
has_and_belongs_to_many :autosaved_parrots, class_name: "Parrot", autosave: true
has_many :treasures, as: :looter
@@ -28,10 +28,10 @@ class Pirate < ActiveRecord::Base
before_remove: :log_before_remove,
after_remove: :log_after_remove
has_many :birds_with_proc_callbacks, class_name: "Bird",
- before_add: proc {|p,b| p.ship_log << "before_adding_proc_bird_#{b.id || '<new>'}"},
- after_add: proc {|p,b| p.ship_log << "after_adding_proc_bird_#{b.id || '<new>'}"},
- before_remove: proc {|p,b| p.ship_log << "before_removing_proc_bird_#{b.id}"},
- after_remove: proc {|p,b| p.ship_log << "after_removing_proc_bird_#{b.id}"}
+ before_add: proc { |p,b| p.ship_log << "before_adding_proc_bird_#{b.id || '<new>'}" },
+ after_add: proc { |p,b| p.ship_log << "after_adding_proc_bird_#{b.id || '<new>'}" },
+ before_remove: proc { |p,b| p.ship_log << "before_removing_proc_bird_#{b.id}" },
+ after_remove: proc { |p,b| p.ship_log << "after_removing_proc_bird_#{b.id}" }
has_many :birds_with_reject_all_blank, class_name: "Bird"
has_one :foo_bulb, -> { where name: "foo" }, foreign_key: :car_id, class_name: "Bulb"
diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb
index 8bfd79d907..42eff9cff9 100644
--- a/activerecord/test/models/post.rb
+++ b/activerecord/test/models/post.rb
@@ -21,7 +21,7 @@ class Post < ActiveRecord::Base
scope :titled_with_an_apostrophe, -> { where("title LIKE '%''%'") }
scope :ranked_by_comments, -> { order("comments_count DESC") }
- scope :limit_by, lambda {|l| limit(l) }
+ scope :limit_by, lambda { |l| limit(l) }
belongs_to :author
@@ -34,8 +34,8 @@ class Post < ActiveRecord::Base
has_one :first_comment, -> { order("id ASC") }, class_name: "Comment"
has_one :last_comment, -> { order("id desc") }, class_name: "Comment"
- scope :with_special_comments, -> { joins(:comments).where(comments: {type: "SpecialComment"}) }
- scope :with_very_special_comments, -> { joins(:comments).where(comments: {type: "VerySpecialComment"}) }
+ scope :with_special_comments, -> { joins(:comments).where(comments: { type: "SpecialComment" }) }
+ scope :with_very_special_comments, -> { joins(:comments).where(comments: { type: "VerySpecialComment" }) }
scope :with_post, ->(post_id) { joins(:comments).where(comments: { post_id: post_id }) }
scope :with_comments, -> { preload(:comments) }
@@ -141,10 +141,10 @@ class Post < ActiveRecord::Base
has_many :people, through: :readers
has_many :single_people, through: :readers
has_many :people_with_callbacks, source: :person, through: :readers,
- before_add: lambda {|owner, reader| log(:added, :before, reader.first_name) },
- after_add: lambda {|owner, reader| log(:added, :after, reader.first_name) },
- before_remove: lambda {|owner, reader| log(:removed, :before, reader.first_name) },
- after_remove: lambda {|owner, reader| log(:removed, :after, reader.first_name) }
+ before_add: lambda { |owner, reader| log(:added, :before, reader.first_name) },
+ after_add: lambda { |owner, reader| log(:added, :after, reader.first_name) },
+ before_remove: lambda { |owner, reader| log(:removed, :before, reader.first_name) },
+ after_remove: lambda { |owner, reader| log(:removed, :after, reader.first_name) }
has_many :skimmers, -> { where skimmer: true }, class_name: "Reader"
has_many :impatient_people, through: :skimmers, source: :person
diff --git a/activerecord/test/models/project.rb b/activerecord/test/models/project.rb
index 4d6b269731..5009f8f54b 100644
--- a/activerecord/test/models/project.rb
+++ b/activerecord/test/models/project.rb
@@ -7,10 +7,10 @@ class Project < ActiveRecord::Base
has_and_belongs_to_many :developers_named_david, -> { where("name = 'David'").distinct }, class_name: "Developer"
has_and_belongs_to_many :developers_named_david_with_hash_conditions, -> { where(name: "David").distinct }, class_name: "Developer"
has_and_belongs_to_many :salaried_developers, -> { where "salary > 0" }, class_name: "Developer"
- has_and_belongs_to_many :developers_with_callbacks, class_name: "Developer", before_add: Proc.new {|o, r| o.developers_log << "before_adding#{r.id || '<new>'}"},
- after_add: Proc.new {|o, r| o.developers_log << "after_adding#{r.id || '<new>'}"},
- before_remove: Proc.new {|o, r| o.developers_log << "before_removing#{r.id}"},
- after_remove: Proc.new {|o, r| o.developers_log << "after_removing#{r.id}"}
+ has_and_belongs_to_many :developers_with_callbacks, class_name: "Developer", before_add: Proc.new { |o, r| o.developers_log << "before_adding#{r.id || '<new>'}" },
+ after_add: Proc.new { |o, r| o.developers_log << "after_adding#{r.id || '<new>'}" },
+ before_remove: Proc.new { |o, r| o.developers_log << "before_removing#{r.id}" },
+ after_remove: Proc.new { |o, r| o.developers_log << "after_removing#{r.id}" }
has_and_belongs_to_many :well_payed_salary_groups, -> { group("developers.salary").having("SUM(salary) > 10000").select("SUM(salary) as salary") }, class_name: "Developer"
belongs_to :firm
has_one :lead_developer, through: :firm, inverse_of: :contracted_projects
diff --git a/activerecord/test/models/sponsor.rb b/activerecord/test/models/sponsor.rb
index 175933ccf1..3f142b25fe 100644
--- a/activerecord/test/models/sponsor.rb
+++ b/activerecord/test/models/sponsor.rb
@@ -2,6 +2,6 @@ class Sponsor < ActiveRecord::Base
belongs_to :sponsor_club, class_name: "Club", foreign_key: "club_id"
belongs_to :sponsorable, polymorphic: true
belongs_to :thing, polymorphic: true, foreign_type: :sponsorable_type, foreign_key: :sponsorable_id
- belongs_to :sponsorable_with_conditions, -> { where name: "Ernie"}, polymorphic: true,
+ belongs_to :sponsorable_with_conditions, -> { where name: "Ernie" }, polymorphic: true,
foreign_type: "sponsorable_type", foreign_key: "sponsorable_id"
end
diff --git a/activerecord/test/models/subject.rb b/activerecord/test/models/subject.rb
index f31a33ec7e..29e290825e 100644
--- a/activerecord/test/models/subject.rb
+++ b/activerecord/test/models/subject.rb
@@ -7,7 +7,7 @@ class Subject < ActiveRecord::Base
protected
def set_email_address
- unless self.persisted?
+ unless persisted?
self.author_email_address = "test@test.com"
end
end
diff --git a/activerecord/test/models/topic.rb b/activerecord/test/models/topic.rb
index 00f89a5364..db04735d01 100644
--- a/activerecord/test/models/topic.rb
+++ b/activerecord/test/models/topic.rb
@@ -84,7 +84,7 @@ class Topic < ActiveRecord::Base
end
def set_email_address
- unless self.persisted?
+ unless persisted?
self.author_email_address = "test@test.com"
end
end
diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb
index 558c21b8d2..9997ddee77 100644
--- a/activerecord/test/schema/schema.rb
+++ b/activerecord/test/schema/schema.rb
@@ -899,7 +899,7 @@ ActiveRecord::Schema.define do
end
[:circles, :squares, :triangles, :non_poly_ones, :non_poly_twos].each do |t|
- create_table(t, force: true) { }
+ create_table(t, force: true) {}
end
# NOTE - the following 4 tables are used by models that have :inverse_of options on the associations
diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md
index 047688aba8..30985060fd 100644
--- a/activesupport/CHANGELOG.md
+++ b/activesupport/CHANGELOG.md
@@ -1,3 +1,37 @@
+* Remove unused parameter `options = nil` for `#clear` of
+ `ActiveSupport::Cache::Strategy::LocalCache::LocalStore` and
+ `ActiveSupport::Cache::Strategy::LocalCache`.
+
+ *Yosuke Kabuto*
+
+* Fix `thread_mattr_accessor` subclass no longer overwrites parent.
+
+ Assigning a value to a subclass using `thread_mattr_accessor` no
+ longer changes the value of the parent class. This brings the
+ behavior inline with the documentation.
+
+ Given:
+
+ class Account
+ thread_mattr_accessor :user
+ end
+
+ class Customer < Account
+ end
+
+ Account.user = "DHH"
+ Customer.user = "Rafael"
+
+ Before:
+
+ Account.user # => "Rafael"
+
+ After:
+
+ Account.user # => "DHH"
+
+ *Shinichi Maeshima*
+
* Since weeks are no longer converted to days, add `:weeks` to the list of
parts that `ActiveSupport::TimeWithZone` will recognize as possibly being
of variable duration to take account of DST transitions.
@@ -12,10 +46,10 @@
*Xavier Noria*
-* Allow MessageEncryptor to take advantage of authenticated encryption modes.
+* Allow `MessageEncryptor` to take advantage of authenticated encryption modes.
AEAD modes like `aes-256-gcm` provide both confidentiality and data
- authenticity, eliminating the need to use MessageVerifier to check if the
+ authenticity, eliminating the need to use `MessageVerifier` to check if the
encrypted data has been tampered with. This speeds up encryption/decryption
and results in shorter cipher text.
@@ -119,7 +153,7 @@
*Sean Griffin*
-* Introduce Module#delegate_missing_to.
+* Introduce `Module#delegate_missing_to`.
When building a decorator, a common pattern emerges:
diff --git a/activesupport/bin/test b/activesupport/bin/test
index 404cabba51..84a05bba08 100755
--- a/activesupport/bin/test
+++ b/activesupport/bin/test
@@ -1,4 +1,6 @@
#!/usr/bin/env ruby
-COMPONENT_ROOT = File.expand_path("../../", __FILE__)
+
+COMPONENT_ROOT = File.expand_path("..", __dir__)
require File.expand_path("../tools/test", COMPONENT_ROOT)
+
exit Minitest.run(ARGV)
diff --git a/activesupport/lib/active_support/cache.rb b/activesupport/lib/active_support/cache.rb
index a760915bfd..8ef91fa3f0 100644
--- a/activesupport/lib/active_support/cache.rb
+++ b/activesupport/lib/active_support/cache.rb
@@ -464,7 +464,7 @@ module ActiveSupport
# The options hash is passed to the underlying cache implementation.
#
# All implementations may not support this method.
- def clear(options = nil)
+ def clear
raise NotImplementedError.new("#{self.class.name} does not support clear")
end
@@ -525,12 +525,12 @@ module ActiveSupport
case key
when Array
if key.size > 1
- key = key.collect{|element| expanded_key(element)}
+ key = key.collect { |element| expanded_key(element) }
else
key = key.first
end
when Hash
- key = key.sort_by { |k,_| k.to_s }.collect{|k,v| "#{k}=#{v}"}
+ key = key.sort_by { |k,_| k.to_s }.collect { |k,v| "#{k}=#{v}" }
end
key.to_param
@@ -559,7 +559,7 @@ module ActiveSupport
payload = { key: key }
payload.merge!(options) if options.is_a?(Hash)
- ActiveSupport::Notifications.instrument("cache_#{operation}.active_support", payload){ yield(payload) }
+ ActiveSupport::Notifications.instrument("cache_#{operation}.active_support", payload) { yield(payload) }
end
def log
@@ -584,7 +584,7 @@ module ActiveSupport
end
def get_entry_value(entry, name, options)
- instrument(:fetch_hit, name, options) { }
+ instrument(:fetch_hit, name, options) {}
entry.value
end
diff --git a/activesupport/lib/active_support/cache/file_store.rb b/activesupport/lib/active_support/cache/file_store.rb
index 1132425526..1971ff182e 100644
--- a/activesupport/lib/active_support/cache/file_store.rb
+++ b/activesupport/lib/active_support/cache/file_store.rb
@@ -27,9 +27,9 @@ module ActiveSupport
# Deletes all items from the cache. In this case it deletes all the entries in the specified
# file store directory except for .keep or .gitkeep. Be careful which directory is specified in your
# config file when using +FileStore+ because everything in that directory will be deleted.
- def clear(options = nil)
+ def clear
root_dirs = exclude_from(cache_path, EXCLUDED_DIRS + GITKEEP_FILES)
- FileUtils.rm_r(root_dirs.collect{|f| File.join(cache_path, f)})
+ FileUtils.rm_r(root_dirs.collect { |f| File.join(cache_path, f) })
rescue Errno::ENOENT
end
@@ -80,7 +80,7 @@ module ActiveSupport
def write_entry(key, entry, options)
return false if options[:unless_exist] && File.exist?(key)
ensure_cache_path(File.dirname(key))
- File.atomic_write(key, cache_path) {|f| Marshal.dump(entry, f)}
+ File.atomic_write(key, cache_path) { |f| Marshal.dump(entry, f) }
true
end
diff --git a/activesupport/lib/active_support/cache/mem_cache_store.rb b/activesupport/lib/active_support/cache/mem_cache_store.rb
index e51c6b2f10..cfd5e39bc4 100644
--- a/activesupport/lib/active_support/cache/mem_cache_store.rb
+++ b/activesupport/lib/active_support/cache/mem_cache_store.rb
@@ -85,7 +85,7 @@ module ActiveSupport
@data = addresses.first
else
mem_cache_options = options.dup
- UNIVERSAL_OPTIONS.each{|name| mem_cache_options.delete(name)}
+ UNIVERSAL_OPTIONS.each { |name| mem_cache_options.delete(name) }
@data = self.class.build_mem_cache(*(addresses + [mem_cache_options]))
end
end
@@ -96,7 +96,7 @@ module ActiveSupport
options = names.extract_options!
options = merged_options(options)
- keys_to_names = Hash[names.map{|name| [normalize_key(name, options), name]}]
+ keys_to_names = Hash[names.map { |name| [normalize_key(name, options), name] }]
raw_values = @data.get_multi(keys_to_names.keys, raw: true)
values = {}
raw_values.each do |key, value|
@@ -176,7 +176,7 @@ module ActiveSupport
def normalize_key(key, options)
key = super.dup
key = key.force_encoding(Encoding::ASCII_8BIT)
- key = key.gsub(ESCAPE_KEY_CHARS){ |match| "%#{match.getbyte(0).to_s(16).upcase}" }
+ key = key.gsub(ESCAPE_KEY_CHARS) { |match| "%#{match.getbyte(0).to_s(16).upcase}" }
key = "#{key[0, 213]}:md5:#{Digest::MD5.hexdigest(key)}" if key.size > 250
key
end
diff --git a/activesupport/lib/active_support/cache/memory_store.rb b/activesupport/lib/active_support/cache/memory_store.rb
index d7dc574f5b..dbe55d7ce1 100644
--- a/activesupport/lib/active_support/cache/memory_store.rb
+++ b/activesupport/lib/active_support/cache/memory_store.rb
@@ -40,7 +40,7 @@ module ActiveSupport
def cleanup(options = nil)
options = merged_options(options)
instrument(:cleanup, size: @data.size) do
- keys = synchronize{ @data.keys }
+ keys = synchronize { @data.keys }
keys.each do |key|
entry = @data[key]
delete_entry(key, options) if entry && entry.expired?
@@ -57,7 +57,7 @@ module ActiveSupport
start_time = Time.now
cleanup
instrument(:prune, target_size, from: @cache_size) do
- keys = synchronize{ @key_access.keys.sort{|a,b| @key_access[a].to_f <=> @key_access[b].to_f} }
+ keys = synchronize { @key_access.keys.sort { |a,b| @key_access[a].to_f <=> @key_access[b].to_f } }
keys.each do |key|
delete_entry(key, options)
return if @cache_size <= target_size || (max_time && Time.now - start_time > max_time)
diff --git a/activesupport/lib/active_support/cache/strategy/local_cache.rb b/activesupport/lib/active_support/cache/strategy/local_cache.rb
index 8ed8ab36ab..ec2e96a106 100644
--- a/activesupport/lib/active_support/cache/strategy/local_cache.rb
+++ b/activesupport/lib/active_support/cache/strategy/local_cache.rb
@@ -44,7 +44,7 @@ module ActiveSupport
yield
end
- def clear(options = nil)
+ def clear
@data.clear
end
@@ -78,9 +78,9 @@ module ActiveSupport
local_cache_key)
end
- def clear(options = nil) # :nodoc:
+ def clear # :nodoc:
return super unless cache = local_cache
- cache.clear(options)
+ cache.clear
super
end
@@ -92,14 +92,14 @@ module ActiveSupport
def increment(name, amount = 1, options = nil) # :nodoc:
return super unless local_cache
- value = bypass_local_cache{super}
+ value = bypass_local_cache { super }
write_cache_value(name, value, options)
value
end
def decrement(name, amount = 1, options = nil) # :nodoc:
return super unless local_cache
- value = bypass_local_cache{super}
+ value = bypass_local_cache { super }
write_cache_value(name, value, options)
value
end
diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb
index a450b0e6d4..a33cab0504 100644
--- a/activesupport/lib/active_support/callbacks.rb
+++ b/activesupport/lib/active_support/callbacks.rb
@@ -399,7 +399,7 @@ module ActiveSupport
end
else
scopes = Array(chain_config[:scope])
- method_to_call = scopes.map{ |s| public_send(s) }.join("_")
+ method_to_call = scopes.map { |s| public_send(s) }.join("_")
lambda { |target, _, &blk|
filter.public_send method_to_call, target, &blk
@@ -445,7 +445,7 @@ module ActiveSupport
def around(&around)
CallbackSequence.new do |arg|
around.call(arg) {
- self.call(arg)
+ call(arg)
}
end
end
@@ -624,7 +624,7 @@ module ActiveSupport
# callback is skipped.
#
# class Writer < Person
- # skip_callback :validate, :before, :check_membership, if: -> { self.age > 18 }
+ # skip_callback :validate, :before, :check_membership, if: -> { age > 18 }
# end
#
# An <tt>ArgumentError</tt> will be raised if the callback has not
@@ -635,7 +635,7 @@ module ActiveSupport
__update_callbacks(name) do |target, chain|
filters.each do |filter|
- callback = chain.find {|c| c.matches?(type, filter) }
+ callback = chain.find { |c| c.matches?(type, filter) }
if !callback && options[:raise]
raise ArgumentError, "#{type.to_s.capitalize} #{name} callback #{filter.inspect} has not been defined"
@@ -662,7 +662,7 @@ module ActiveSupport
target.set_callbacks name, chain
end
- self.set_callbacks name, callbacks.dup.clear
+ set_callbacks(name, callbacks.dup.clear)
end
# Define sets of events in the object life cycle that support callbacks.
diff --git a/activesupport/lib/active_support/concurrency/share_lock.rb b/activesupport/lib/active_support/concurrency/share_lock.rb
index e61dadd0cc..8969ebb080 100644
--- a/activesupport/lib/active_support/concurrency/share_lock.rb
+++ b/activesupport/lib/active_support/concurrency/share_lock.rb
@@ -13,7 +13,6 @@ module ActiveSupport
# we need exclusive locks to be reentrant, and we need to be able
# to upgrade share locks to exclusive.
-
def raw_state # :nodoc:
synchronize do
threads = @sleeping.keys | @sharing.keys | @waiting.keys
diff --git a/activesupport/lib/active_support/core_ext/date_and_time/zones.rb b/activesupport/lib/active_support/core_ext/date_and_time/zones.rb
index c5b46c598c..edd724f1d0 100644
--- a/activesupport/lib/active_support/core_ext/date_and_time/zones.rb
+++ b/activesupport/lib/active_support/core_ext/date_and_time/zones.rb
@@ -22,7 +22,7 @@ module DateAndTime
if time_zone
time_with_zone(time, time_zone)
else
- time || self.to_time
+ time || to_time
end
end
diff --git a/activesupport/lib/active_support/core_ext/digest/uuid.rb b/activesupport/lib/active_support/core_ext/digest/uuid.rb
index 23cb105f7c..e6d60e3267 100644
--- a/activesupport/lib/active_support/core_ext/digest/uuid.rb
+++ b/activesupport/lib/active_support/core_ext/digest/uuid.rb
@@ -35,12 +35,12 @@ module Digest
# Convenience method for uuid_from_hash using Digest::MD5.
def self.uuid_v3(uuid_namespace, name)
- self.uuid_from_hash(Digest::MD5, uuid_namespace, name)
+ uuid_from_hash(Digest::MD5, uuid_namespace, name)
end
# Convenience method for uuid_from_hash using Digest::SHA1.
def self.uuid_v5(uuid_namespace, name)
- self.uuid_from_hash(Digest::SHA1, uuid_namespace, name)
+ uuid_from_hash(Digest::SHA1, uuid_namespace, name)
end
# Convenience method for SecureRandom.uuid.
diff --git a/activesupport/lib/active_support/core_ext/hash/compact.rb b/activesupport/lib/active_support/core_ext/hash/compact.rb
index f072530e04..78b3387c3b 100644
--- a/activesupport/lib/active_support/core_ext/hash/compact.rb
+++ b/activesupport/lib/active_support/core_ext/hash/compact.rb
@@ -7,7 +7,7 @@ class Hash
# { c: nil }.compact # => {}
# { c: true }.compact # => { c: true }
def compact
- self.select { |_, value| !value.nil? }
+ select { |_, value| !value.nil? }
end
# Replaces current hash with non +nil+ values.
@@ -18,6 +18,6 @@ class Hash
# hash # => { a: true, b: false }
# { c: true }.compact! # => nil
def compact!
- self.reject! { |_, value| value.nil? }
+ reject! { |_, value| value.nil? }
end
end
diff --git a/activesupport/lib/active_support/core_ext/hash/keys.rb b/activesupport/lib/active_support/core_ext/hash/keys.rb
index 1bfa18aeee..b7089357a8 100644
--- a/activesupport/lib/active_support/core_ext/hash/keys.rb
+++ b/activesupport/lib/active_support/core_ext/hash/keys.rb
@@ -52,14 +52,14 @@ class Hash
# hash.symbolize_keys
# # => {:name=>"Rob", :age=>"28"}
def symbolize_keys
- transform_keys{ |key| key.to_sym rescue key }
+ transform_keys { |key| key.to_sym rescue key }
end
alias_method :to_options, :symbolize_keys
# Destructively converts all keys to symbols, as long as they respond
# to +to_sym+. Same as +symbolize_keys+, but modifies +self+.
def symbolize_keys!
- transform_keys!{ |key| key.to_sym rescue key }
+ transform_keys! { |key| key.to_sym rescue key }
end
alias_method :to_options!, :symbolize_keys!
@@ -128,14 +128,14 @@ class Hash
# hash.deep_symbolize_keys
# # => {:person=>{:name=>"Rob", :age=>"28"}}
def deep_symbolize_keys
- deep_transform_keys{ |key| key.to_sym rescue key }
+ deep_transform_keys { |key| key.to_sym rescue key }
end
# Destructively converts all keys to symbols, as long as they respond
# to +to_sym+. This includes the keys from the root hash and from all
# nested hashes and arrays.
def deep_symbolize_keys!
- deep_transform_keys!{ |key| key.to_sym rescue key }
+ deep_transform_keys! { |key| key.to_sym rescue key }
end
private
@@ -147,7 +147,7 @@ class Hash
result[yield(key)] = _deep_transform_keys_in_object(value, &block)
end
when Array
- object.map {|e| _deep_transform_keys_in_object(e, &block) }
+ object.map { |e| _deep_transform_keys_in_object(e, &block) }
else
object
end
@@ -162,7 +162,7 @@ class Hash
end
object
when Array
- object.map! {|e| _deep_transform_keys_in_object!(e, &block)}
+ object.map! { |e| _deep_transform_keys_in_object!(e, &block) }
else
object
end
diff --git a/activesupport/lib/active_support/core_ext/hash/reverse_merge.rb b/activesupport/lib/active_support/core_ext/hash/reverse_merge.rb
index fbb482435d..db3e7508e7 100644
--- a/activesupport/lib/active_support/core_ext/hash/reverse_merge.rb
+++ b/activesupport/lib/active_support/core_ext/hash/reverse_merge.rb
@@ -16,7 +16,7 @@ class Hash
# Destructive +reverse_merge+.
def reverse_merge!(other_hash)
# right wins if there is no left
- merge!( other_hash ){|key,left,right| left }
+ merge!( other_hash ) { |key,left,right| left }
end
alias_method :reverse_update, :reverse_merge!
end
diff --git a/activesupport/lib/active_support/core_ext/module/aliasing.rb b/activesupport/lib/active_support/core_ext/module/aliasing.rb
index 83b94aa3cc..4a04bdd446 100644
--- a/activesupport/lib/active_support/core_ext/module/aliasing.rb
+++ b/activesupport/lib/active_support/core_ext/module/aliasing.rb
@@ -65,6 +65,9 @@ class Module
# e.subject = "Megastars"
# e.title # => "Megastars"
def alias_attribute(new_name, old_name)
+ # The following reader methods use an explicit `self` receiver in order to
+ # support aliases that start with an uppercase letter. Otherwise, they would
+ # be resolved as constants instead.
module_eval <<-STR, __FILE__, __LINE__ + 1
def #{new_name}; self.#{old_name}; end # def subject; self.title; end
def #{new_name}?; self.#{old_name}?; end # def subject?; self.title?; end
diff --git a/activesupport/lib/active_support/core_ext/module/attr_internal.rb b/activesupport/lib/active_support/core_ext/module/attr_internal.rb
index 48421a8850..5081d5f7a3 100644
--- a/activesupport/lib/active_support/core_ext/module/attr_internal.rb
+++ b/activesupport/lib/active_support/core_ext/module/attr_internal.rb
@@ -1,12 +1,12 @@
class Module
# Declares an attribute reader backed by an internally-named instance variable.
def attr_internal_reader(*attrs)
- attrs.each {|attr_name| attr_internal_define(attr_name, :reader)}
+ attrs.each { |attr_name| attr_internal_define(attr_name, :reader) }
end
# Declares an attribute writer backed by an internally-named instance variable.
def attr_internal_writer(*attrs)
- attrs.each {|attr_name| attr_internal_define(attr_name, :writer)}
+ attrs.each { |attr_name| attr_internal_define(attr_name, :writer) }
end
# Declares an attribute reader and writer backed by an internally-named instance
diff --git a/activesupport/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb b/activesupport/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb
index 1ebae1f4f3..b1e6fe71e0 100644
--- a/activesupport/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb
+++ b/activesupport/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb
@@ -39,16 +39,19 @@ class Module
syms.each do |sym|
raise NameError.new("invalid attribute name: #{sym}") unless /^[_A-Za-z]\w*$/.match?(sym)
+
+ # The following generated method concatenates `name` because we want it
+ # to work with inheritance via polymorphism.
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
def self.#{sym}
- Thread.current[:"attr_#{name}_#{sym}"]
+ Thread.current["attr_" + name + "_#{sym}"]
end
EOS
unless options[:instance_reader] == false || options[:instance_accessor] == false
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
def #{sym}
- Thread.current[:"attr_#{name}_#{sym}"]
+ self.class.#{sym}
end
EOS
end
@@ -78,16 +81,19 @@ class Module
options = syms.extract_options!
syms.each do |sym|
raise NameError.new("invalid attribute name: #{sym}") unless /^[_A-Za-z]\w*$/.match?(sym)
+
+ # The following generated method concatenates `name` because we want it
+ # to work with inheritance via polymorphism.
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
def self.#{sym}=(obj)
- Thread.current[:"attr_#{name}_#{sym}"] = obj
+ Thread.current["attr_" + name + "_#{sym}"] = obj
end
EOS
unless options[:instance_writer] == false || options[:instance_accessor] == false
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
def #{sym}=(obj)
- Thread.current[:"attr_#{name}_#{sym}"] = obj
+ self.class.#{sym} = obj
end
EOS
end
@@ -134,9 +140,9 @@ class Module
#
# Current.new.user = "DHH" # => NoMethodError
# Current.new.user # => NoMethodError
- def thread_mattr_accessor(*syms, &blk)
- thread_mattr_reader(*syms, &blk)
- thread_mattr_writer(*syms, &blk)
+ def thread_mattr_accessor(*syms)
+ thread_mattr_reader(*syms)
+ thread_mattr_writer(*syms)
end
alias :thread_cattr_accessor :thread_mattr_accessor
end
diff --git a/activesupport/lib/active_support/core_ext/object/inclusion.rb b/activesupport/lib/active_support/core_ext/object/inclusion.rb
index d4c17dfb07..98bf820d36 100644
--- a/activesupport/lib/active_support/core_ext/object/inclusion.rb
+++ b/activesupport/lib/active_support/core_ext/object/inclusion.rb
@@ -22,6 +22,6 @@ class Object
#
# @return [Object]
def presence_in(another_object)
- self.in?(another_object) ? self : nil
+ in?(another_object) ? self : nil
end
end
diff --git a/activesupport/lib/active_support/core_ext/string/access.rb b/activesupport/lib/active_support/core_ext/string/access.rb
index b6afd32fb0..caa48e34c5 100644
--- a/activesupport/lib/active_support/core_ext/string/access.rb
+++ b/activesupport/lib/active_support/core_ext/string/access.rb
@@ -76,7 +76,7 @@ class String
if limit == 0
""
elsif limit >= size
- self.dup
+ dup
else
to(limit - 1)
end
@@ -96,7 +96,7 @@ class String
if limit == 0
""
elsif limit >= size
- self.dup
+ dup
else
from(-limit)
end
diff --git a/activesupport/lib/active_support/core_ext/string/indent.rb b/activesupport/lib/active_support/core_ext/string/indent.rb
index 4cc332aa23..e87f72fdbd 100644
--- a/activesupport/lib/active_support/core_ext/string/indent.rb
+++ b/activesupport/lib/active_support/core_ext/string/indent.rb
@@ -38,6 +38,6 @@ class String
# "foo\n\nbar".indent(2, nil, true) # => " foo\n \n bar"
#
def indent(amount, indent_string=nil, indent_empty_lines=false)
- dup.tap {|_| _.indent!(amount, indent_string, indent_empty_lines)}
+ dup.tap { |_| _.indent!(amount, indent_string, indent_empty_lines) }
end
end
diff --git a/activesupport/lib/active_support/core_ext/string/inflections.rb b/activesupport/lib/active_support/core_ext/string/inflections.rb
index bf94b97ceb..7e12700c8c 100644
--- a/activesupport/lib/active_support/core_ext/string/inflections.rb
+++ b/activesupport/lib/active_support/core_ext/string/inflections.rb
@@ -31,7 +31,7 @@ class String
def pluralize(count = nil, locale = :en)
locale = count if count.is_a?(Symbol)
if count == 1
- self.dup
+ dup
else
ActiveSupport::Inflector.pluralize(self, locale)
end
diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb
index 622f637675..158bb402bd 100644
--- a/activesupport/lib/active_support/dependencies.rb
+++ b/activesupport/lib/active_support/dependencies.rb
@@ -547,7 +547,7 @@ module ActiveSupport #:nodoc:
end
name_error = NameError.new("uninitialized constant #{qualified_name}", const_name)
- name_error.set_backtrace(caller.reject {|l| l.starts_with? __FILE__ })
+ name_error.set_backtrace(caller.reject { |l| l.starts_with? __FILE__ })
raise name_error
end
@@ -697,7 +697,7 @@ module ActiveSupport #:nodoc:
if file_path
expanded = File.expand_path(file_path)
expanded.sub!(/\.rb\z/, "")
- self.loaded.delete(expanded)
+ loaded.delete(expanded)
end
if constants.empty?
diff --git a/activesupport/lib/active_support/duration.rb b/activesupport/lib/active_support/duration.rb
index 6c6922749d..6ec0c3a70a 100644
--- a/activesupport/lib/active_support/duration.rb
+++ b/activesupport/lib/active_support/duration.rb
@@ -120,8 +120,8 @@ module ActiveSupport
def inspect #:nodoc:
parts.
reduce(::Hash.new(0)) { |h,(l,r)| h[l] += r; h }.
- sort_by {|unit, _ | [:years, :months, :weeks, :days, :hours, :minutes, :seconds].index(unit)}.
- map {|unit, val| "#{val} #{val == 1 ? unit.to_s.chop : unit.to_s}"}.
+ sort_by { |unit, _ | [:years, :months, :weeks, :days, :hours, :minutes, :seconds].index(unit) }.
+ map { |unit, val| "#{val} #{val == 1 ? unit.to_s.chop : unit.to_s}" }.
to_sentence(locale: ::I18n.default_locale)
end
diff --git a/activesupport/lib/active_support/hash_with_indifferent_access.rb b/activesupport/lib/active_support/hash_with_indifferent_access.rb
index fc0123c956..74a603c05d 100644
--- a/activesupport/lib/active_support/hash_with_indifferent_access.rb
+++ b/activesupport/lib/active_support/hash_with_indifferent_access.rb
@@ -161,7 +161,6 @@ module ActiveSupport
alias_method :has_key?, :key?
alias_method :member?, :key?
-
# Same as <tt>Hash#[]</tt> where the key passed as argument can be
# either a string or a symbol:
#
@@ -217,7 +216,7 @@ module ActiveSupport
# modify the receiver but rather returns a new hash with indifferent
# access with the result of the merge.
def merge(hash, &block)
- self.dup.update(hash, &block)
+ dup.update(hash, &block)
end
# Like +merge+ but the other way around: Merges the receiver into the
diff --git a/activesupport/lib/active_support/inflector/inflections.rb b/activesupport/lib/active_support/inflector/inflections.rb
index b1be84a096..aa68f9ec9e 100644
--- a/activesupport/lib/active_support/inflector/inflections.rb
+++ b/activesupport/lib/active_support/inflector/inflections.rb
@@ -43,8 +43,8 @@ module ActiveSupport
end
def add(words)
- self.concat(words.flatten.map(&:downcase))
- @regex_array += self.map {|word| to_regex(word) }
+ concat(words.flatten.map(&:downcase))
+ @regex_array += map { |word| to_regex(word) }
self
end
diff --git a/activesupport/lib/active_support/lazy_load_hooks.rb b/activesupport/lib/active_support/lazy_load_hooks.rb
index 67b54b45ea..b84c7253a0 100644
--- a/activesupport/lib/active_support/lazy_load_hooks.rb
+++ b/activesupport/lib/active_support/lazy_load_hooks.rb
@@ -28,6 +28,8 @@ module ActiveSupport
end
end
+ # Declares a block that will be executed when a Rails component is fully
+ # loaded.
def on_load(name, options = {}, &block)
@loaded[name].each do |base|
execute_hook(base, options, block)
diff --git a/activesupport/lib/active_support/message_encryptor.rb b/activesupport/lib/active_support/message_encryptor.rb
index c198e4e6f1..ab8b2f8ded 100644
--- a/activesupport/lib/active_support/message_encryptor.rb
+++ b/activesupport/lib/active_support/message_encryptor.rb
@@ -98,7 +98,7 @@ module ActiveSupport
def _decrypt(encrypted_message)
cipher = new_cipher
- encrypted_data, iv, auth_tag = encrypted_message.split("--".freeze).map {|v| ::Base64.strict_decode64(v)}
+ encrypted_data, iv, auth_tag = encrypted_message.split("--".freeze).map { |v| ::Base64.strict_decode64(v) }
# Currently the OpenSSL bindings do not raise an error if auth_tag is
# truncated, which would allow an attacker to easily forge it. See
diff --git a/activesupport/lib/active_support/multibyte/chars.rb b/activesupport/lib/active_support/multibyte/chars.rb
index c690b1b50b..938e4ebb72 100644
--- a/activesupport/lib/active_support/multibyte/chars.rb
+++ b/activesupport/lib/active_support/multibyte/chars.rb
@@ -151,7 +151,7 @@ module ActiveSupport #:nodoc:
# "ÉL QUE SE ENTERÓ".mb_chars.titleize # => "Él Que Se Enteró"
# "日本語".mb_chars.titleize # => "日本語"
def titleize
- chars(downcase.to_s.gsub(/\b('?\S)/u) { Unicode.upcase($1)})
+ chars(downcase.to_s.gsub(/\b('?\S)/u) { Unicode.upcase($1) })
end
alias_method :titlecase, :titleize
diff --git a/activesupport/lib/active_support/multibyte/unicode.rb b/activesupport/lib/active_support/multibyte/unicode.rb
index c194804c08..ee657080b2 100644
--- a/activesupport/lib/active_support/multibyte/unicode.rb
+++ b/activesupport/lib/active_support/multibyte/unicode.rb
@@ -56,7 +56,7 @@ module ActiveSupport
# Returns a regular expression pattern that matches the passed Unicode
# codepoints.
def self.codepoints_to_pattern(array_of_codepoints) #:nodoc:
- array_of_codepoints.collect{ |e| [e].pack "U*".freeze }.join("|".freeze)
+ array_of_codepoints.collect { |e| [e].pack "U*".freeze }.join("|".freeze)
end
TRAILERS_PAT = /(#{codepoints_to_pattern(LEADERS_AND_TRAILERS)})+\Z/u
LEADERS_PAT = /\A(#{codepoints_to_pattern(LEADERS_AND_TRAILERS)})+/u
diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb
index 2d986fe4e0..793bc9e22d 100644
--- a/activesupport/lib/active_support/ordered_hash.rb
+++ b/activesupport/lib/active_support/ordered_hash.rb
@@ -1,7 +1,7 @@
require "yaml"
YAML.add_builtin_type("omap") do |type, val|
- ActiveSupport::OrderedHash[val.map{ |v| v.to_a.first }]
+ ActiveSupport::OrderedHash[val.map { |v| v.to_a.first }]
end
module ActiveSupport
diff --git a/activesupport/lib/active_support/test_case.rb b/activesupport/lib/active_support/test_case.rb
index 5ea3a7010b..a8e98b704a 100644
--- a/activesupport/lib/active_support/test_case.rb
+++ b/activesupport/lib/active_support/test_case.rb
@@ -66,7 +66,6 @@ module ActiveSupport
alias :assert_not_respond_to :refute_respond_to
alias :assert_not_same :refute_same
-
# Assertion that the block should not raise an exception.
#
# Passes if evaluated code in the yielded block raises no exception.
diff --git a/activesupport/lib/active_support/testing/isolation.rb b/activesupport/lib/active_support/testing/isolation.rb
index 23fe47a039..d30b34ecd6 100644
--- a/activesupport/lib/active_support/testing/isolation.rb
+++ b/activesupport/lib/active_support/testing/isolation.rb
@@ -68,7 +68,7 @@ module ActiveSupport
if ENV["ISOLATION_TEST"]
yield
File.open(ENV["ISOLATION_OUTPUT"], "w") do |file|
- file.puts [Marshal.dump(self.dup)].pack("m")
+ file.puts [Marshal.dump(dup)].pack("m")
end
exit!
else
@@ -78,7 +78,7 @@ module ActiveSupport
"ISOLATION_OUTPUT" => tmpfile.path
}
- load_paths = $-I.map {|p| "-I\"#{File.expand_path(p)}\"" }.join(" ")
+ load_paths = $-I.map { |p| "-I\"#{File.expand_path(p)}\"" }.join(" ")
orig_args = ORIG_ARGV.join(" ")
test_opts = "-n#{self.class.name}##{self.name}"
command = "#{Gem.ruby} #{load_paths} #{$0} '#{orig_args}' #{test_opts}"
diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb
index 439d2b86aa..9d1147620c 100644
--- a/activesupport/lib/active_support/time_with_zone.rb
+++ b/activesupport/lib/active_support/time_with_zone.rb
@@ -458,7 +458,7 @@ module ActiveSupport
def method_missing(sym, *args, &block)
wrap_with_time_zone time.__send__(sym, *args, &block)
rescue NoMethodError => e
- raise e, e.message.sub(time.inspect, self.inspect), e.backtrace
+ raise e, e.message.sub(time.inspect, inspect), e.backtrace
end
private
@@ -480,7 +480,7 @@ module ActiveSupport
end
def duration_of_variable_length?(obj)
- ActiveSupport::Duration === obj && obj.parts.any? {|p| [:years, :months, :weeks, :days].include?(p[0]) }
+ ActiveSupport::Duration === obj && obj.parts.any? { |p| [:years, :months, :weeks, :days].include?(p[0]) }
end
def wrap_with_time_zone(time)
diff --git a/activesupport/lib/active_support/values/time_zone.rb b/activesupport/lib/active_support/values/time_zone.rb
index b5a74ddc52..cb97a0e135 100644
--- a/activesupport/lib/active_support/values/time_zone.rb
+++ b/activesupport/lib/active_support/values/time_zone.rb
@@ -260,7 +260,7 @@ module ActiveSupport
private
def zones_map
@zones_map ||= begin
- MAPPING.each_key {|place| self[place]} # load all the zones
+ MAPPING.each_key { |place| self[place] } # load all the zones
@lazy_zones_map
end
end
diff --git a/activesupport/lib/active_support/xml_mini.rb b/activesupport/lib/active_support/xml_mini.rb
index 12a7c61240..70864038e8 100644
--- a/activesupport/lib/active_support/xml_mini.rb
+++ b/activesupport/lib/active_support/xml_mini.rb
@@ -126,7 +126,7 @@ module ActiveSupport
key = rename_key(key.to_s, options)
- attributes = options[:skip_types] || type_name.nil? ? { } : { type: type_name }
+ attributes = options[:skip_types] || type_name.nil? ? {} : { type: type_name }
attributes[:nil] = true if value.nil?
encoding = options[:encoding] || DEFAULT_ENCODINGS[type_name]
diff --git a/activesupport/lib/active_support/xml_mini/jdom.rb b/activesupport/lib/active_support/xml_mini/jdom.rb
index 90f6cc464f..c698780da8 100644
--- a/activesupport/lib/active_support/xml_mini/jdom.rb
+++ b/activesupport/lib/active_support/xml_mini/jdom.rb
@@ -46,7 +46,7 @@ module ActiveSupport
xml_string_reader = StringReader.new(data)
xml_input_source = InputSource.new(xml_string_reader)
doc = @dbf.new_document_builder.parse(xml_input_source)
- merge_element!({CONTENT_KEY => ""}, doc.document_element, XmlMini.depth)
+ merge_element!({ CONTENT_KEY => "" }, doc.document_element, XmlMini.depth)
end
end
diff --git a/activesupport/lib/active_support/xml_mini/rexml.rb b/activesupport/lib/active_support/xml_mini/rexml.rb
index 28da82aeb1..091a15294c 100644
--- a/activesupport/lib/active_support/xml_mini/rexml.rb
+++ b/activesupport/lib/active_support/xml_mini/rexml.rb
@@ -55,7 +55,7 @@ module ActiveSupport
hash = get_attributes(element)
if element.has_elements?
- element.each_element {|child| merge_element!(hash, child, depth - 1) }
+ element.each_element { |child| merge_element!(hash, child, depth - 1) }
merge_texts!(hash, element) unless empty_content?(element)
hash
else
diff --git a/activesupport/test/benchmarkable_test.rb b/activesupport/test/benchmarkable_test.rb
index 6b9eb5aa66..210b9cb9fd 100644
--- a/activesupport/test/benchmarkable_test.rb
+++ b/activesupport/test/benchmarkable_test.rb
@@ -57,13 +57,13 @@ class BenchmarkableTest < ActiveSupport::TestCase
def test_within_level
logger.level = ActiveSupport::Logger::DEBUG
- benchmark("included_debug_run", level: :debug) { }
+ benchmark("included_debug_run", level: :debug) {}
assert_last_logged "included_debug_run"
end
def test_outside_level
logger.level = ActiveSupport::Logger::ERROR
- benchmark("skipped_debug_run", level: :debug) { }
+ benchmark("skipped_debug_run", level: :debug) {}
assert_no_match(/skipped_debug_run/, buffer.last)
ensure
logger.level = ActiveSupport::Logger::DEBUG
diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb
index 072a2530ba..a669d666be 100644
--- a/activesupport/test/caching_test.rb
+++ b/activesupport/test/caching_test.rb
@@ -19,7 +19,7 @@ module ActiveSupport
})
_, _, body = middleware.call({})
assert LocalCacheRegistry.cache_for(key), "should still have a cache"
- body.each { }
+ body.each {}
assert LocalCacheRegistry.cache_for(key), "should still have a cache"
body.close
assert_nil LocalCacheRegistry.cache_for(key)
@@ -135,7 +135,7 @@ class CacheKeyTest < ActiveSupport::TestCase
kv.each { |key, value| old_values[key], ENV[key] = ENV[key], value }
yield
ensure
- old_values.each { |key, value| ENV[key] = value}
+ old_values.each { |key, value| ENV[key] = value }
end
end
@@ -212,7 +212,7 @@ class CacheStoreNamespaceTest < ActiveSupport::TestCase
def test_proc_namespace
test_val = "tester"
- proc = lambda{test_val}
+ proc = lambda { test_val }
cache = ActiveSupport::Cache.lookup_store(:memory_store, namespace: proc)
cache.write("foo", "bar")
assert_equal "bar", cache.read("foo")
@@ -306,7 +306,7 @@ module CacheStoreBehavior
def test_should_read_and_write_hash
assert @cache.write("foo", a: "b")
- assert_equal({a: "b"}, @cache.read("foo"))
+ assert_equal({ a: "b" }, @cache.read("foo"))
end
def test_should_read_and_write_integer
@@ -328,7 +328,7 @@ module CacheStoreBehavior
@cache.write("foo", "bar")
@cache.write("fu", "baz")
@cache.write("fud", "biz")
- assert_equal({"foo" => "bar", "fu" => "baz"}, @cache.read_multi("foo", "fu"))
+ assert_equal({ "foo" => "bar", "fu" => "baz" }, @cache.read_multi("foo", "fu"))
end
def test_read_multi_with_expires
@@ -337,7 +337,7 @@ module CacheStoreBehavior
@cache.write("fu", "baz")
@cache.write("fud", "biz")
Time.stub(:now, time + 11) do
- assert_equal({"fu" => "baz"}, @cache.read_multi("foo", "fu"))
+ assert_equal({ "fu" => "baz" }, @cache.read_multi("foo", "fu"))
end
end
@@ -402,7 +402,7 @@ module CacheStoreBehavior
end
def test_hash_as_cache_key
- @cache.write({foo: 1, fu: 2}, "bar")
+ @cache.write({ foo: 1, fu: 2 }, "bar")
assert_equal "bar", @cache.read("foo=1/fu=2")
end
@@ -520,12 +520,12 @@ module CacheStoreBehavior
def test_really_long_keys
key = ""
- 900.times{key << "x"}
+ 900.times { key << "x" }
assert @cache.write(key, "bar")
assert_equal "bar", @cache.read(key)
assert_equal "bar", @cache.fetch(key)
assert_nil @cache.read("#{key}x")
- assert_equal({key => "bar"}, @cache.read_multi(key))
+ assert_equal({ key => "bar" }, @cache.read_multi(key))
assert @cache.delete(key)
end
@@ -831,11 +831,6 @@ class FileStoreTest < ActiveSupport::TestCase
@cache.clear
end
- def test_long_keys
- @cache.write("a"*10000, 1)
- assert_equal 1, @cache.read("a"*10000)
- end
-
def test_long_uri_encoded_keys
@cache.write("%"*870, 1)
assert_equal 1, @cache.read("%"*870)
@@ -867,7 +862,7 @@ class FileStoreTest < ActiveSupport::TestCase
def test_key_transformation_max_filename_size
key = "#{'A' * ActiveSupport::Cache::FileStore::FILENAME_MAX_SIZE}B"
path = @cache.send(:normalize_key, key, {})
- assert path.split("/").all? { |dir_name| dir_name.size <= ActiveSupport::Cache::FileStore::FILENAME_MAX_SIZE}
+ assert path.split("/").all? { |dir_name| dir_name.size <= ActiveSupport::Cache::FileStore::FILENAME_MAX_SIZE }
assert_equal "B", File.basename(path)
end
@@ -888,7 +883,7 @@ class FileStoreTest < ActiveSupport::TestCase
end
assert File.exist?(cache_dir), "Parent of top level cache dir was deleted!"
assert File.exist?(sub_cache_dir), "Top level cache dir was deleted!"
- assert Dir.entries(sub_cache_dir).reject {|f| ActiveSupport::Cache::FileStore::EXCLUDED_DIRS.include?(f)}.empty?
+ assert Dir.entries(sub_cache_dir).reject { |f| ActiveSupport::Cache::FileStore::EXCLUDED_DIRS.include?(f) }.empty?
end
def test_log_exception_when_cache_read_fails
diff --git a/activesupport/test/callback_inheritance_test.rb b/activesupport/test/callback_inheritance_test.rb
index d1c217177d..9e2f7527e0 100644
--- a/activesupport/test/callback_inheritance_test.rb
+++ b/activesupport/test/callback_inheritance_test.rb
@@ -9,8 +9,8 @@ class GrandParent
end
define_callbacks :dispatch
- set_callback :dispatch, :before, :before1, :before2, if: proc {|c| c.action_name == "index" || c.action_name == "update" }
- set_callback :dispatch, :after, :after1, :after2, if: proc {|c| c.action_name == "update" || c.action_name == "delete" }
+ set_callback :dispatch, :before, :before1, :before2, if: proc { |c| c.action_name == "index" || c.action_name == "update" }
+ set_callback :dispatch, :after, :after1, :after2, if: proc { |c| c.action_name == "update" || c.action_name == "delete" }
def before1
@log << "before1"
@@ -37,12 +37,12 @@ class GrandParent
end
class Parent < GrandParent
- skip_callback :dispatch, :before, :before2, unless: proc {|c| c.action_name == "update" }
- skip_callback :dispatch, :after, :after2, unless: proc {|c| c.action_name == "delete" }
+ skip_callback :dispatch, :before, :before2, unless: proc { |c| c.action_name == "update" }
+ skip_callback :dispatch, :after, :after2, unless: proc { |c| c.action_name == "delete" }
end
class Child < GrandParent
- skip_callback :dispatch, :before, :before2, unless: proc {|c| c.action_name == "update" }, if: :state_open?
+ skip_callback :dispatch, :before, :before2, unless: proc { |c| c.action_name == "update" }, if: :state_open?
def state_open?
@state == :open
diff --git a/activesupport/test/callbacks_test.rb b/activesupport/test/callbacks_test.rb
index 040e9c1cca..b4e98edd84 100644
--- a/activesupport/test/callbacks_test.rb
+++ b/activesupport/test/callbacks_test.rb
@@ -89,7 +89,7 @@ module CallbacksTest
define_callbacks :dispatch
- set_callback :dispatch, :before, :log, unless: proc {|c| c.action_name == :index || c.action_name == :show }
+ set_callback :dispatch, :before, :log, unless: proc { |c| c.action_name == :index || c.action_name == :show }
set_callback :dispatch, :after, :log2
attr_reader :action_name, :logger
@@ -114,7 +114,7 @@ module CallbacksTest
end
class Child < ParentController
- skip_callback :dispatch, :before, :log, if: proc {|c| c.action_name == :update}
+ skip_callback :dispatch, :before, :log, if: proc { |c| c.action_name == :update }
skip_callback :dispatch, :after, :log2
end
@@ -125,10 +125,10 @@ module CallbacksTest
super
end
- before_save Proc.new {|r| r.history << [:before_save, :starts_true, :if] }, if: :starts_true
- before_save Proc.new {|r| r.history << [:before_save, :starts_false, :if] }, if: :starts_false
- before_save Proc.new {|r| r.history << [:before_save, :starts_true, :unless] }, unless: :starts_true
- before_save Proc.new {|r| r.history << [:before_save, :starts_false, :unless] }, unless: :starts_false
+ before_save Proc.new { |r| r.history << [:before_save, :starts_true, :if] }, if: :starts_true
+ before_save Proc.new { |r| r.history << [:before_save, :starts_false, :if] }, if: :starts_false
+ before_save Proc.new { |r| r.history << [:before_save, :starts_true, :unless] }, unless: :starts_true
+ before_save Proc.new { |r| r.history << [:before_save, :starts_false, :unless] }, unless: :starts_false
def starts_true
if @@starts_true
@@ -181,8 +181,6 @@ module CallbacksTest
end
end
-
-
class ConditionalPerson < Record
# proc
before_save Proc.new { |r| r.history << [:before_save, :proc] }, if: Proc.new { |r| true }
@@ -229,7 +227,7 @@ module CallbacksTest
set_callback :save, :before, :nope, unless: :yes
set_callback :save, :after, :tweedle
ActiveSupport::Deprecation.silence { set_callback :save, :before, "tweedle_dee" }
- set_callback :save, :before, proc {|m| m.history << "yup" }
+ set_callback :save, :before, proc { |m| m.history << "yup" }
set_callback :save, :before, :nope, if: proc { false }
set_callback :save, :before, :nope, unless: proc { true }
set_callback :save, :before, :yup, if: proc { true }
@@ -489,8 +487,6 @@ module CallbacksTest
end
end
-
-
class ResetCallbackTest < ActiveSupport::TestCase
def test_save_conditional_person
person = CleanPerson.new
@@ -808,7 +804,7 @@ module CallbacksTest
class WriterSkipper < Person
attr_accessor :age
- skip_callback :save, :before, :before_save_method, if: lambda {self.age > 21}
+ skip_callback :save, :before, :before_save_method, if: -> { age > 21 }
end
class WriterCallbacksTest < ActiveSupport::TestCase
@@ -883,7 +879,7 @@ module CallbacksTest
def test_proc_arity_2
assert_raises(ArgumentError) do
- klass = build_class(->(x,y) { })
+ klass = build_class(->(x,y) {})
klass.new.run
end
end
@@ -962,7 +958,7 @@ module CallbacksTest
def test_proc_arity2
assert_raises(ArgumentError) do
- object = build_class(->(a,b) { }).new
+ object = build_class(->(a,b) {}).new
object.run
end
end
diff --git a/activesupport/test/concern_test.rb b/activesupport/test/concern_test.rb
index 4e74a69f97..4af9ce8163 100644
--- a/activesupport/test/concern_test.rb
+++ b/activesupport/test/concern_test.rb
@@ -72,7 +72,7 @@ class ConcernTest < ActiveSupport::TestCase
def test_class_methods_are_extended
@klass.include(Baz)
assert_equal "baz", @klass.baz
- assert_equal ConcernTest::Baz::ClassMethods, (class << @klass; self.included_modules; end)[0]
+ assert_equal ConcernTest::Baz::ClassMethods, (class << @klass; included_modules; end)[0]
end
def test_class_methods_are_extended_only_on_expected_objects
diff --git a/activesupport/test/core_ext/duration_test.rb b/activesupport/test/core_ext/duration_test.rb
index 64b5bca151..1a2dcba760 100644
--- a/activesupport/test/core_ext/duration_test.rb
+++ b/activesupport/test/core_ext/duration_test.rb
@@ -194,7 +194,7 @@ class DurationTest < ActiveSupport::TestCase
def test_delegation_with_block_works
counter = 0
assert_nothing_raised do
- 1.minute.times {counter += 1}
+ 1.minute.times { counter += 1 }
end
assert_equal counter, 60
end
diff --git a/activesupport/test/core_ext/enumerable_test.rb b/activesupport/test/core_ext/enumerable_test.rb
index 3d63a5fbb6..9072957e0e 100644
--- a/activesupport/test/core_ext/enumerable_test.rb
+++ b/activesupport/test/core_ext/enumerable_test.rb
@@ -75,7 +75,7 @@ class EnumerableTests < ActiveSupport::TestCase
assert_typed_equal(2.0, sum.real, Float)
assert_typed_equal(3.0, sum.imag, Float)
- sum = GenericEnumerable.new([1, 2]).sum(10) {|v| v * 2 }
+ sum = GenericEnumerable.new([1, 2]).sum(10) { |v| v * 2 }
assert_typed_equal(16, sum, Integer)
end
@@ -162,7 +162,7 @@ class EnumerableTests < ActiveSupport::TestCase
assert_typed_equal(2.0, sum.real, Float)
assert_typed_equal(3.0, sum.imag, Float)
- sum = [1, 2].sum(10) {|v| v * 2 }
+ sum = [1, 2].sum(10) { |v| v * 2 }
assert_typed_equal(16, sum, Integer)
end
@@ -184,17 +184,17 @@ class EnumerableTests < ActiveSupport::TestCase
assert_equal false, GenericEnumerable.new([ 1 ] ).many?
assert_equal true, GenericEnumerable.new([ 1, 2 ] ).many?
- assert_equal false, GenericEnumerable.new([] ).many? {|x| x > 1 }
- assert_equal false, GenericEnumerable.new([ 2 ] ).many? {|x| x > 1 }
- assert_equal false, GenericEnumerable.new([ 1, 2 ] ).many? {|x| x > 1 }
- assert_equal true, GenericEnumerable.new([ 1, 2, 2 ]).many? {|x| x > 1 }
+ assert_equal false, GenericEnumerable.new([] ).many? { |x| x > 1 }
+ assert_equal false, GenericEnumerable.new([ 2 ] ).many? { |x| x > 1 }
+ assert_equal false, GenericEnumerable.new([ 1, 2 ] ).many? { |x| x > 1 }
+ assert_equal true, GenericEnumerable.new([ 1, 2, 2 ]).many? { |x| x > 1 }
end
def test_many_iterates_only_on_what_is_needed
infinity = 1.0/0.0
very_long_enum = 0..infinity
assert_equal true, very_long_enum.many?
- assert_equal true, very_long_enum.many?{|x| x > 100}
+ assert_equal true, very_long_enum.many? { |x| x > 100 }
end
def test_exclude?
@@ -206,7 +206,7 @@ class EnumerableTests < ActiveSupport::TestCase
assert_equal [1, 2, 4], GenericEnumerable.new((1..5).to_a).without(3, 5)
assert_equal [1, 2, 4], (1..5).to_a.without(3, 5)
assert_equal [1, 2, 4], (1..5).to_set.without(3, 5)
- assert_equal({foo: 1, baz: 3}, {foo: 1, bar: 2, baz: 3}.without(:bar))
+ assert_equal({ foo: 1, baz: 3 }, { foo: 1, bar: 2, baz: 3 }.without(:bar))
end
def test_pluck
diff --git a/activesupport/test/core_ext/hash/transform_keys_test.rb b/activesupport/test/core_ext/hash/transform_keys_test.rb
index ea34a47b3d..7a11d827f8 100644
--- a/activesupport/test/core_ext/hash/transform_keys_test.rb
+++ b/activesupport/test/core_ext/hash/transform_keys_test.rb
@@ -48,7 +48,7 @@ class TransformKeysTest < ActiveSupport::TestCase
class HashDescendant < ::Hash
def initialize(elements = nil)
super(elements)
- (elements || {}).each_pair{ |key, value| self[key] = value }
+ (elements || {}).each_pair { |key, value| self[key] = value }
end
end
diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb
index 8a9f33ae53..e457cb866d 100644
--- a/activesupport/test/core_ext/hash_ext_test.rb
+++ b/activesupport/test/core_ext/hash_ext_test.rb
@@ -41,9 +41,9 @@ class HashExtTest < ActiveSupport::TestCase
@mixed = { :a => 1, "b" => 2 }
@nested_mixed = { "a" => { b: { "c" => 3 } } }
@integers = { 0 => 1, 1 => 2 }
- @nested_integers = { 0 => { 1 => { 2 => 3} } }
+ @nested_integers = { 0 => { 1 => { 2 => 3 } } }
@illegal_symbols = { [] => 3 }
- @nested_illegal_symbols = { [] => { [] => 3} }
+ @nested_illegal_symbols = { [] => { [] => 3 } }
@upcase_strings = { "A" => 1, "B" => 2 }
@nested_upcase_strings = { "A" => { "B" => { "C" => 3 } } }
@string_array_of_hashes = { "a" => [ { "b" => 2 }, { "c" => 3 }, 4 ] }
@@ -75,57 +75,57 @@ class HashExtTest < ActiveSupport::TestCase
end
def test_transform_keys
- assert_equal @upcase_strings, @strings.transform_keys{ |key| key.to_s.upcase }
- assert_equal @upcase_strings, @symbols.transform_keys{ |key| key.to_s.upcase }
- assert_equal @upcase_strings, @mixed.transform_keys{ |key| key.to_s.upcase }
+ assert_equal @upcase_strings, @strings.transform_keys { |key| key.to_s.upcase }
+ assert_equal @upcase_strings, @symbols.transform_keys { |key| key.to_s.upcase }
+ assert_equal @upcase_strings, @mixed.transform_keys { |key| key.to_s.upcase }
end
def test_transform_keys_not_mutates
transformed_hash = @mixed.dup
- transformed_hash.transform_keys{ |key| key.to_s.upcase }
+ transformed_hash.transform_keys { |key| key.to_s.upcase }
assert_equal @mixed, transformed_hash
end
def test_deep_transform_keys
- assert_equal @nested_upcase_strings, @nested_symbols.deep_transform_keys{ |key| key.to_s.upcase }
- assert_equal @nested_upcase_strings, @nested_strings.deep_transform_keys{ |key| key.to_s.upcase }
- assert_equal @nested_upcase_strings, @nested_mixed.deep_transform_keys{ |key| key.to_s.upcase }
- assert_equal @upcase_array_of_hashes, @string_array_of_hashes.deep_transform_keys{ |key| key.to_s.upcase }
- assert_equal @upcase_array_of_hashes, @symbol_array_of_hashes.deep_transform_keys{ |key| key.to_s.upcase }
- assert_equal @upcase_array_of_hashes, @mixed_array_of_hashes.deep_transform_keys{ |key| key.to_s.upcase }
+ assert_equal @nested_upcase_strings, @nested_symbols.deep_transform_keys { |key| key.to_s.upcase }
+ assert_equal @nested_upcase_strings, @nested_strings.deep_transform_keys { |key| key.to_s.upcase }
+ assert_equal @nested_upcase_strings, @nested_mixed.deep_transform_keys { |key| key.to_s.upcase }
+ assert_equal @upcase_array_of_hashes, @string_array_of_hashes.deep_transform_keys { |key| key.to_s.upcase }
+ assert_equal @upcase_array_of_hashes, @symbol_array_of_hashes.deep_transform_keys { |key| key.to_s.upcase }
+ assert_equal @upcase_array_of_hashes, @mixed_array_of_hashes.deep_transform_keys { |key| key.to_s.upcase }
end
def test_deep_transform_keys_not_mutates
transformed_hash = @nested_mixed.deep_dup
- transformed_hash.deep_transform_keys{ |key| key.to_s.upcase }
+ transformed_hash.deep_transform_keys { |key| key.to_s.upcase }
assert_equal @nested_mixed, transformed_hash
end
def test_transform_keys!
- assert_equal @upcase_strings, @symbols.dup.transform_keys!{ |key| key.to_s.upcase }
- assert_equal @upcase_strings, @strings.dup.transform_keys!{ |key| key.to_s.upcase }
- assert_equal @upcase_strings, @mixed.dup.transform_keys!{ |key| key.to_s.upcase }
+ assert_equal @upcase_strings, @symbols.dup.transform_keys! { |key| key.to_s.upcase }
+ assert_equal @upcase_strings, @strings.dup.transform_keys! { |key| key.to_s.upcase }
+ assert_equal @upcase_strings, @mixed.dup.transform_keys! { |key| key.to_s.upcase }
end
def test_transform_keys_with_bang_mutates
transformed_hash = @mixed.dup
- transformed_hash.transform_keys!{ |key| key.to_s.upcase }
+ transformed_hash.transform_keys! { |key| key.to_s.upcase }
assert_equal @upcase_strings, transformed_hash
assert_equal @mixed, :a => 1, "b" => 2
end
def test_deep_transform_keys!
- assert_equal @nested_upcase_strings, @nested_symbols.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase }
- assert_equal @nested_upcase_strings, @nested_strings.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase }
- assert_equal @nested_upcase_strings, @nested_mixed.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase }
- assert_equal @upcase_array_of_hashes, @string_array_of_hashes.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase }
- assert_equal @upcase_array_of_hashes, @symbol_array_of_hashes.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase }
- assert_equal @upcase_array_of_hashes, @mixed_array_of_hashes.deep_dup.deep_transform_keys!{ |key| key.to_s.upcase }
+ assert_equal @nested_upcase_strings, @nested_symbols.deep_dup.deep_transform_keys! { |key| key.to_s.upcase }
+ assert_equal @nested_upcase_strings, @nested_strings.deep_dup.deep_transform_keys! { |key| key.to_s.upcase }
+ assert_equal @nested_upcase_strings, @nested_mixed.deep_dup.deep_transform_keys! { |key| key.to_s.upcase }
+ assert_equal @upcase_array_of_hashes, @string_array_of_hashes.deep_dup.deep_transform_keys! { |key| key.to_s.upcase }
+ assert_equal @upcase_array_of_hashes, @symbol_array_of_hashes.deep_dup.deep_transform_keys! { |key| key.to_s.upcase }
+ assert_equal @upcase_array_of_hashes, @mixed_array_of_hashes.deep_dup.deep_transform_keys! { |key| key.to_s.upcase }
end
def test_deep_transform_keys_with_bang_mutates
transformed_hash = @nested_mixed.deep_dup
- transformed_hash.deep_transform_keys!{ |key| key.to_s.upcase }
+ transformed_hash.deep_transform_keys! { |key| key.to_s.upcase }
assert_equal @nested_upcase_strings, transformed_hash
assert_equal @nested_mixed, "a" => { b: { "c" => 3 } }
end
@@ -276,7 +276,6 @@ class HashExtTest < ActiveSupport::TestCase
assert_equal @nested_symbols, @nested_mixed.with_indifferent_access.deep_symbolize_keys
end
-
def test_symbolize_keys_bang_for_hash_with_indifferent_access
assert_raise(NoMethodError) { @symbols.with_indifferent_access.dup.symbolize_keys! }
assert_raise(NoMethodError) { @strings.with_indifferent_access.dup.symbolize_keys! }
@@ -535,7 +534,7 @@ class HashExtTest < ActiveSupport::TestCase
end
def test_indifferent_deleting
- get_hash = proc{ { a: "foo" }.with_indifferent_access }
+ get_hash = proc { { a: "foo" }.with_indifferent_access }
hash = get_hash.call
assert_equal hash.delete(:a), "foo"
assert_equal hash.delete(:a), nil
@@ -545,7 +544,7 @@ class HashExtTest < ActiveSupport::TestCase
end
def test_indifferent_select
- hash = ActiveSupport::HashWithIndifferentAccess.new(@strings).select {|k,v| v == 1}
+ hash = ActiveSupport::HashWithIndifferentAccess.new(@strings).select { |k,v| v == 1 }
assert_equal({ "a" => 1 }, hash)
assert_instance_of ActiveSupport::HashWithIndifferentAccess, hash
@@ -557,21 +556,21 @@ class HashExtTest < ActiveSupport::TestCase
end
def test_indifferent_select_returns_a_hash_when_unchanged
- hash = ActiveSupport::HashWithIndifferentAccess.new(@strings).select {|k,v| true}
+ hash = ActiveSupport::HashWithIndifferentAccess.new(@strings).select { |k,v| true }
assert_instance_of ActiveSupport::HashWithIndifferentAccess, hash
end
def test_indifferent_select_bang
indifferent_strings = ActiveSupport::HashWithIndifferentAccess.new(@strings)
- indifferent_strings.select! {|k,v| v == 1}
+ indifferent_strings.select! { |k,v| v == 1 }
assert_equal({ "a" => 1 }, indifferent_strings)
assert_instance_of ActiveSupport::HashWithIndifferentAccess, indifferent_strings
end
def test_indifferent_reject
- hash = ActiveSupport::HashWithIndifferentAccess.new(@strings).reject {|k,v| v != 1}
+ hash = ActiveSupport::HashWithIndifferentAccess.new(@strings).reject { |k,v| v != 1 }
assert_equal({ "a" => 1 }, hash)
assert_instance_of ActiveSupport::HashWithIndifferentAccess, hash
@@ -584,7 +583,7 @@ class HashExtTest < ActiveSupport::TestCase
def test_indifferent_reject_bang
indifferent_strings = ActiveSupport::HashWithIndifferentAccess.new(@strings)
- indifferent_strings.reject! {|k,v| v != 1}
+ indifferent_strings.reject! { |k,v| v != 1 }
assert_equal({ "a" => 1 }, indifferent_strings)
assert_instance_of ActiveSupport::HashWithIndifferentAccess, indifferent_strings
@@ -609,21 +608,21 @@ class HashExtTest < ActiveSupport::TestCase
end
def test_lookup_returns_the_same_object_that_is_stored_in_hash_indifferent_access
- hash = HashWithIndifferentAccess.new {|h, k| h[k] = []}
+ hash = HashWithIndifferentAccess.new { |h, k| h[k] = [] }
hash[:a] << 1
assert_equal [1], hash[:a]
end
def test_with_indifferent_access_has_no_side_effects_on_existing_hash
- hash = {content: [{:foo => :bar, "bar" => "baz"}]}
+ hash = { content: [{ :foo => :bar, "bar" => "baz" }] }
hash.with_indifferent_access
assert_equal [:foo, "bar"], hash[:content].first.keys
end
def test_indifferent_hash_with_array_of_hashes
- hash = { "urls" => { "url" => [ { "address" => "1" }, { "address" => "2" } ] }}.with_indifferent_access
+ hash = { "urls" => { "url" => [ { "address" => "1" }, { "address" => "2" } ] } }.with_indifferent_access
assert_equal "1", hash[:urls][:url].first[:address]
hash = hash.to_hash
@@ -635,14 +634,14 @@ class HashExtTest < ActiveSupport::TestCase
def test_should_preserve_array_subclass_when_value_is_array
array = SubclassingArray.new
array << { "address" => "1" }
- hash = { "urls" => { "url" => array }}.with_indifferent_access
+ hash = { "urls" => { "url" => array } }.with_indifferent_access
assert_equal SubclassingArray, hash[:urls][:url].class
end
def test_should_preserve_array_class_when_hash_value_is_frozen_array
array = SubclassingArray.new
array << { "address" => "1" }
- hash = { "urls" => { "url" => array.freeze }}.with_indifferent_access
+ hash = { "urls" => { "url" => array.freeze } }.with_indifferent_access
assert_equal SubclassingArray, hash[:urls][:url].class
end
@@ -684,11 +683,11 @@ class HashExtTest < ActiveSupport::TestCase
end
def test_indifferent_sub_hashes
- h = {"user" => {"id" => 5}}.with_indifferent_access
- ["user", :user].each {|user| [:id, "id"].each {|id| assert_equal 5, h[user][id], "h[#{user.inspect}][#{id.inspect}] should be 5"}}
+ h = { "user" => { "id" => 5 } }.with_indifferent_access
+ ["user", :user].each { |user| [:id, "id"].each { |id| assert_equal 5, h[user][id], "h[#{user.inspect}][#{id.inspect}] should be 5" } }
- h = {user: {id: 5}}.with_indifferent_access
- ["user", :user].each {|user| [:id, "id"].each {|id| assert_equal 5, h[user][id], "h[#{user.inspect}][#{id.inspect}] should be 5"}}
+ h = { user: { id: 5 } }.with_indifferent_access
+ ["user", :user].each { |user| [:id, "id"].each { |id| assert_equal 5, h[user][id], "h[#{user.inspect}][#{id.inspect}] should be 5" } }
end
def test_indifferent_duplication
@@ -704,7 +703,7 @@ class HashExtTest < ActiveSupport::TestCase
def test_nested_dig_indifferent_access
skip if RUBY_VERSION < "2.3.0"
- data = {"this" => {"views" => 1234}}.with_indifferent_access
+ data = { "this" => { "views" => 1234 } }.with_indifferent_access
assert_equal 1234, data.dig(:this, :views)
end
@@ -741,9 +740,9 @@ class HashExtTest < ActiveSupport::TestCase
end
def test_assorted_keys_not_stringified
- original = {Object.new => 2, 1 => 2, [] => true}
+ original = { Object.new => 2, 1 => 2, [] => true }
indiff = original.with_indifferent_access
- assert(!indiff.keys.any? {|k| k.kind_of? String}, "A key was converted to a string!")
+ assert(!indiff.keys.any? { |k| k.kind_of? String }, "A key was converted to a string!")
end
def test_deep_merge
@@ -892,7 +891,7 @@ class HashExtTest < ActiveSupport::TestCase
end
def test_indifferent_slice_access_with_symbols
- original = {"login" => "bender", "password" => "shiny", "stuff" => "foo"}
+ original = { "login" => "bender", "password" => "shiny", "stuff" => "foo" }
original = original.with_indifferent_access
slice = original.slice(:login, :password)
@@ -920,17 +919,17 @@ class HashExtTest < ActiveSupport::TestCase
end
def test_extract
- original = {a: 1, b: 2, c: 3, d: 4}
- expected = {a: 1, b: 2}
- remaining = {c: 3, d: 4}
+ original = { a: 1, b: 2, c: 3, d: 4 }
+ expected = { a: 1, b: 2 }
+ remaining = { c: 3, d: 4 }
assert_equal expected, original.extract!(:a, :b, :x)
assert_equal remaining, original
end
def test_extract_nils
- original = {a: nil, b: nil}
- expected = {a: nil}
+ original = { a: nil, b: nil }
+ expected = { a: nil }
extracted = original.extract!(:a, :x)
assert_equal expected, extracted
@@ -939,9 +938,9 @@ class HashExtTest < ActiveSupport::TestCase
end
def test_indifferent_extract
- original = {:a => 1, "b" => 2, :c => 3, "d" => 4}.with_indifferent_access
- expected = {a: 1, b: 2}.with_indifferent_access
- remaining = {c: 3, d: 4}.with_indifferent_access
+ original = { :a => 1, "b" => 2, :c => 3, "d" => 4 }.with_indifferent_access
+ expected = { a: 1, b: 2 }.with_indifferent_access
+ remaining = { c: 3, d: 4 }.with_indifferent_access
[["a", "b"], [:a, :b]].each do |keys|
copy = original.dup
@@ -1100,15 +1099,15 @@ class HashExtToParamTests < ActiveSupport::TestCase
assert_equal "", {}.to_param
assert_equal "hello=world", { hello: "world" }.to_param
assert_equal "hello=10", { "hello" => 10 }.to_param
- assert_equal "hello=world&say_bye=true", {:hello => "world", "say_bye" => true}.to_param
+ assert_equal "hello=world&say_bye=true", { :hello => "world", "say_bye" => true }.to_param
end
def test_number_hash
- assert_equal "10=20&30=40&50=60", {10 => 20, 30 => 40, 50 => 60}.to_param
+ assert_equal "10=20&30=40&50=60", { 10 => 20, 30 => 40, 50 => 60 }.to_param
end
def test_to_param_hash
- assert_equal "custom-1=param-1&custom2-1=param2-1", {ToParam.new("custom") => ToParam.new("param"), ToParam.new("custom2") => ToParam.new("param2")}.to_param
+ assert_equal "custom-1=param-1&custom2-1=param2-1", { ToParam.new("custom") => ToParam.new("param"), ToParam.new("custom2") => ToParam.new("param2") }.to_param
end
def test_to_param_hash_escapes_its_keys_and_values
@@ -1438,7 +1437,7 @@ class HashToXmlTest < ActiveSupport::TestCase
<posts type="array"></posts>
</blog>
XML
- expected_blog_hash = {"blog" => {"posts" => []}}
+ expected_blog_hash = { "blog" => { "posts" => [] } }
assert_equal expected_blog_hash, Hash.from_xml(blog_xml)
end
@@ -1449,7 +1448,7 @@ class HashToXmlTest < ActiveSupport::TestCase
</posts>
</blog>
XML
- expected_blog_hash = {"blog" => {"posts" => []}}
+ expected_blog_hash = { "blog" => { "posts" => [] } }
assert_equal expected_blog_hash, Hash.from_xml(blog_xml)
end
@@ -1461,7 +1460,7 @@ class HashToXmlTest < ActiveSupport::TestCase
</posts>
</blog>
XML
- expected_blog_hash = {"blog" => {"posts" => ["a post"]}}
+ expected_blog_hash = { "blog" => { "posts" => ["a post"] } }
assert_equal expected_blog_hash, Hash.from_xml(blog_xml)
end
@@ -1474,7 +1473,7 @@ class HashToXmlTest < ActiveSupport::TestCase
</posts>
</blog>
XML
- expected_blog_hash = {"blog" => {"posts" => ["a post", "another post"]}}
+ expected_blog_hash = { "blog" => { "posts" => ["a post", "another post"] } }
assert_equal expected_blog_hash, Hash.from_xml(blog_xml)
end
@@ -1558,7 +1557,7 @@ class HashToXmlTest < ActiveSupport::TestCase
expected_product_hash = {
weight: 0.5,
- image: {"type" => "ProductImage", "filename" => "image.gif" },
+ image: { "type" => "ProductImage", "filename" => "image.gif" },
}.stringify_keys
assert_equal expected_product_hash, Hash.from_xml(product_xml)["product"]
@@ -1581,17 +1580,17 @@ class HashToXmlTest < ActiveSupport::TestCase
end
def test_from_xml_array_one
- expected = { "numbers" => { "type" => "Array", "value" => "1" }}
+ expected = { "numbers" => { "type" => "Array", "value" => "1" } }
assert_equal expected, Hash.from_xml('<numbers type="Array"><value>1</value></numbers>')
end
def test_from_xml_array_many
- expected = { "numbers" => { "type" => "Array", "value" => [ "1", "2" ] }}
+ expected = { "numbers" => { "type" => "Array", "value" => [ "1", "2" ] } }
assert_equal expected, Hash.from_xml('<numbers type="Array"><value>1</value><value>2</value></numbers>')
end
def test_from_trusted_xml_allows_symbol_and_yaml_types
- expected = { "product" => { "name" => :value }}
+ expected = { "product" => { "name" => :value } }
assert_equal expected, Hash.from_trusted_xml('<product><name type="symbol">value</name></product>')
assert_equal expected, Hash.from_trusted_xml('<product><name type="yaml">:value</name></product>')
end
@@ -1735,10 +1734,10 @@ class HashToXmlTest < ActiveSupport::TestCase
end
def test_to_xml_dups_options
- options = {skip_instruct: true}
+ options = { skip_instruct: true }
{}.to_xml(options)
# :builder, etc, shouldn't be added to options
- assert_equal({skip_instruct: true}, options)
+ assert_equal({ skip_instruct: true }, options)
end
def test_expansion_count_is_limited
diff --git a/activesupport/test/core_ext/load_error_test.rb b/activesupport/test/core_ext/load_error_test.rb
index 4ed83c3415..b50a35b2cb 100644
--- a/activesupport/test/core_ext/load_error_test.rb
+++ b/activesupport/test/core_ext/load_error_test.rb
@@ -1,7 +1,6 @@
require "abstract_unit"
require "active_support/core_ext/load_error"
-
class TestMissingSourceFile < ActiveSupport::TestCase
def test_it_is_deprecated
assert_deprecated do
diff --git a/activesupport/test/core_ext/marshal_test.rb b/activesupport/test/core_ext/marshal_test.rb
index 275002b8a1..a899f98705 100644
--- a/activesupport/test/core_ext/marshal_test.rb
+++ b/activesupport/test/core_ext/marshal_test.rb
@@ -12,7 +12,7 @@ class MarshalTest < ActiveSupport::TestCase
end
test "that Marshal#load still works" do
- sanity_data = ["test", [1, 2, 3], {a: [1, 2, 3]}, ActiveSupport::TestCase]
+ sanity_data = ["test", [1, 2, 3], { a: [1, 2, 3] }, ActiveSupport::TestCase]
sanity_data.each do |obj|
dumped = Marshal.dump(obj)
assert_equal Marshal.method(:load).super_method.call(dumped), Marshal.load(dumped)
diff --git a/activesupport/test/core_ext/module/attribute_accessor_per_thread_test.rb b/activesupport/test/core_ext/module/attribute_accessor_per_thread_test.rb
index cda5a34442..b816fa50e3 100644
--- a/activesupport/test/core_ext/module/attribute_accessor_per_thread_test.rb
+++ b/activesupport/test/core_ext/module/attribute_accessor_per_thread_test.rb
@@ -8,6 +8,12 @@ class ModuleAttributeAccessorPerThreadTest < ActiveSupport::TestCase
thread_mattr_accessor :bar, instance_writer: false
thread_mattr_reader :shaq, instance_reader: false
thread_mattr_accessor :camp, instance_accessor: false
+
+ def self.name; "MyClass" end
+ end
+
+ @subclass = Class.new(@class) do
+ def self.name; "SubMyClass" end
end
@object = @class.new
@@ -112,4 +118,14 @@ class ModuleAttributeAccessorPerThreadTest < ActiveSupport::TestCase
assert_equal @class.foo, @object.foo
end
+
+ def test_should_not_affect_superclass_if_subclass_set_value
+ @class.foo = "super"
+ assert_equal @class.foo, "super"
+ assert_nil @subclass.foo
+
+ @subclass.foo = "sub"
+ assert_equal @class.foo, "super"
+ assert_equal @subclass.foo, "sub"
+ end
end
diff --git a/activesupport/test/core_ext/module/attribute_accessor_test.rb b/activesupport/test/core_ext/module/attribute_accessor_test.rb
index fea6806b9b..464a000d59 100644
--- a/activesupport/test/core_ext/module/attribute_accessor_test.rb
+++ b/activesupport/test/core_ext/module/attribute_accessor_test.rb
@@ -93,7 +93,7 @@ class ModuleAttributeAccessorTest < ActiveSupport::TestCase
def test_should_not_invoke_default_value_block_multiple_times
count = 0
- @module.cattr_accessor(:defcount){ count += 1 }
+ @module.cattr_accessor(:defcount) { count += 1 }
assert_equal 1, count
end
end
diff --git a/activesupport/test/core_ext/module/concerning_test.rb b/activesupport/test/core_ext/module/concerning_test.rb
index 45178e477d..038cbf1f2f 100644
--- a/activesupport/test/core_ext/module/concerning_test.rb
+++ b/activesupport/test/core_ext/module/concerning_test.rb
@@ -3,7 +3,7 @@ require "active_support/core_ext/module/concerning"
class ModuleConcerningTest < ActiveSupport::TestCase
def test_concerning_declares_a_concern_and_includes_it_immediately
- klass = Class.new { concerning(:Foo) { } }
+ klass = Class.new { concerning(:Foo) {} }
assert klass.ancestors.include?(klass::Foo), klass.ancestors.inspect
end
end
diff --git a/activesupport/test/core_ext/module/qualified_const_test.rb b/activesupport/test/core_ext/module/qualified_const_test.rb
index dcfac4ced1..418bc80ab9 100644
--- a/activesupport/test/core_ext/module/qualified_const_test.rb
+++ b/activesupport/test/core_ext/module/qualified_const_test.rb
@@ -68,7 +68,7 @@ class QualifiedConstTest < ActiveSupport::TestCase
assert_equal 1, QualifiedConstTestMod.qualified_const_get("N::X")
assert_equal 2, QualifiedConstTestMod.qualified_const_get("M::C::X")
- assert_raise(NameError) { QualifiedConstTestMod.qualified_const_get("M::C::Y")}
+ assert_raise(NameError) { QualifiedConstTestMod.qualified_const_get("M::C::Y") }
end
end
@@ -98,14 +98,14 @@ class QualifiedConstTest < ActiveSupport::TestCase
test "reject absolute paths" do
assert_deprecated do
- assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_defined?("::X")}
- assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_defined?("::X::Y")}
+ assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_defined?("::X") }
+ assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_defined?("::X::Y") }
- assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_get("::X")}
- assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_get("::X::Y")}
+ assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_get("::X") }
+ assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_get("::X::Y") }
- assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_set("::X", nil)}
- assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_set("::X::Y", nil)}
+ assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_set("::X", nil) }
+ assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_set("::X::Y", nil) }
end
end
diff --git a/activesupport/test/core_ext/module/remove_method_test.rb b/activesupport/test/core_ext/module/remove_method_test.rb
index 6579b2754f..0c627f1e74 100644
--- a/activesupport/test/core_ext/module/remove_method_test.rb
+++ b/activesupport/test/core_ext/module/remove_method_test.rb
@@ -27,24 +27,24 @@ end
class RemoveMethodTest < ActiveSupport::TestCase
def test_remove_method_from_an_object
- RemoveMethodTests::A.class_eval{
- self.remove_possible_method(:do_something)
+ RemoveMethodTests::A.class_eval {
+ remove_possible_method(:do_something)
}
assert !RemoveMethodTests::A.new.respond_to?(:do_something)
end
def test_remove_singleton_method_from_an_object
- RemoveMethodTests::A.class_eval{
- self.remove_possible_singleton_method(:do_something_else)
+ RemoveMethodTests::A.class_eval {
+ remove_possible_singleton_method(:do_something_else)
}
assert !RemoveMethodTests::A.respond_to?(:do_something_else)
end
def test_redefine_method_in_an_object
- RemoveMethodTests::A.class_eval{
- self.redefine_method(:do_something) { return 100 }
- self.redefine_method(:do_something_protected) { return 100 }
- self.redefine_method(:do_something_private) { return 100 }
+ RemoveMethodTests::A.class_eval {
+ redefine_method(:do_something) { return 100 }
+ redefine_method(:do_something_protected) { return 100 }
+ redefine_method(:do_something_private) { return 100 }
}
assert_equal 100, RemoveMethodTests::A.new.do_something
assert_equal 100, RemoveMethodTests::A.new.send(:do_something_protected)
diff --git a/activesupport/test/core_ext/module_test.rb b/activesupport/test/core_ext/module_test.rb
index bfe60e0f5f..36073b28b7 100644
--- a/activesupport/test/core_ext/module_test.rb
+++ b/activesupport/test/core_ext/module_test.rb
@@ -117,7 +117,7 @@ class ParameterSet
delegate :[], :[]=, to: :@params
def initialize
- @params = {foo: "bar"}
+ @params = { foo: "bar" }
end
end
@@ -312,7 +312,7 @@ class ModuleTest < ActiveSupport::TestCase
rescue NoMethodError => e
file_and_line = "#{__FILE__}:#{Someone::FAILED_DELEGATE_LINE}"
# We can't simply check the first line of the backtrace, because JRuby reports the call to __send__ in the backtrace.
- assert e.backtrace.any?{|a| a.include?(file_and_line)},
+ assert e.backtrace.any? { |a| a.include?(file_and_line) },
"[#{e.backtrace.inspect}] did not include [#{file_and_line}]"
end
@@ -322,7 +322,7 @@ class ModuleTest < ActiveSupport::TestCase
rescue NoMethodError => e
file_and_line = "#{__FILE__}:#{Someone::FAILED_DELEGATE_LINE_2}"
# We can't simply check the first line of the backtrace, because JRuby reports the call to __send__ in the backtrace.
- assert e.backtrace.any?{|a| a.include?(file_and_line)},
+ assert e.backtrace.any? { |a| a.include?(file_and_line) },
"[#{e.backtrace.inspect}] did not include [#{file_and_line}]"
end
@@ -509,7 +509,6 @@ class MethodAliasingTest < ActiveSupport::TestCase
assert_respond_to @instance, :quux_with_baz?
assert_respond_to @instance, :quux_with_baz=
-
FooClassWithBarMethod.alias_method_chain :quux!, :baz
assert_equal "quux!_with_baz", @instance.quux!
assert_equal "quux!", @instance.quux_without_baz!
diff --git a/activesupport/test/core_ext/numeric_ext_test.rb b/activesupport/test/core_ext/numeric_ext_test.rb
index fc93a18ab1..5e824747ed 100644
--- a/activesupport/test/core_ext/numeric_ext_test.rb
+++ b/activesupport/test/core_ext/numeric_ext_test.rb
@@ -176,7 +176,6 @@ class NumericExtFormattingTest < ActiveSupport::TestCase
assert_equal("&pound;1234567890,50", 1234567890.50.to_s(:currency, unit: "&pound;", separator: ",", delimiter: ""))
end
-
def test_to_s__rounded
assert_equal("-111.235", -111.2346.to_s(:rounded))
assert_equal("111.235", 111.2346.to_s(:rounded))
@@ -222,7 +221,6 @@ class NumericExtFormattingTest < ActiveSupport::TestCase
assert_equal "12.345.678,05", 12345678.05.to_s(:delimited, delimiter: ".", separator: ",")
end
-
def test_to_s__rounded_with_custom_delimiter_and_separator
assert_equal "31,83", 31.825.to_s(:rounded, precision: 2, separator: ",")
assert_equal "1.231,83", 1231.825.to_s(:rounded, precision: 2, separator: ",", delimiter: ".")
@@ -350,13 +348,13 @@ class NumericExtFormattingTest < ActiveSupport::TestCase
def test_number_to_human_with_custom_units
#Only integers
- volume = {unit: "ml", thousand: "lt", million: "m3"}
+ volume = { unit: "ml", thousand: "lt", million: "m3" }
assert_equal "123 lt", 123456.to_s(:human, units: volume)
assert_equal "12 ml", 12.to_s(:human, units: volume)
assert_equal "1.23 m3", 1234567.to_s(:human, units: volume)
#Including fractionals
- distance = {mili: "mm", centi: "cm", deci: "dm", unit: "m", ten: "dam", hundred: "hm", thousand: "km"}
+ distance = { mili: "mm", centi: "cm", deci: "dm", unit: "m", ten: "dam", hundred: "hm", thousand: "km" }
assert_equal "1.23 mm", 0.00123.to_s(:human, units: distance)
assert_equal "1.23 cm", 0.0123.to_s(:human, units: distance)
assert_equal "1.23 dm", 0.123.to_s(:human, units: distance)
@@ -369,20 +367,20 @@ class NumericExtFormattingTest < ActiveSupport::TestCase
assert_equal "12.3 km", 12300.to_s(:human, units: distance)
#The quantifiers don't need to be a continuous sequence
- gangster = {hundred: "hundred bucks", million: "thousand quids"}
+ gangster = { hundred: "hundred bucks", million: "thousand quids" }
assert_equal "1 hundred bucks", 100.to_s(:human, units: gangster)
assert_equal "25 hundred bucks", 2500.to_s(:human, units: gangster)
assert_equal "25 thousand quids", 25000000.to_s(:human, units: gangster)
assert_equal "12300 thousand quids", 12345000000.to_s(:human, units: gangster)
#Spaces are stripped from the resulting string
- assert_equal "4", 4.to_s(:human, units: {unit: "", ten: "tens "})
- assert_equal "4.5 tens", 45.to_s(:human, units: {unit: "", ten: " tens "})
+ assert_equal "4", 4.to_s(:human, units: { unit: "", ten: "tens " })
+ assert_equal "4.5 tens", 45.to_s(:human, units: { unit: "", ten: " tens " })
end
def test_number_to_human_with_custom_format
assert_equal "123 times Thousand", 123456.to_s(:human, format: "%n times %u")
- volume = {unit: "ml", thousand: "lt", million: "m3"}
+ volume = { unit: "ml", thousand: "lt", million: "m3" }
assert_equal "123.lt", 123456.to_s(:human, units: volume, format: "%n.%u")
end
diff --git a/activesupport/test/core_ext/object/instance_variables_test.rb b/activesupport/test/core_ext/object/instance_variables_test.rb
index 510352595a..5bdb2fbc35 100644
--- a/activesupport/test/core_ext/object/instance_variables_test.rb
+++ b/activesupport/test/core_ext/object/instance_variables_test.rb
@@ -13,7 +13,7 @@ class ObjectInstanceVariableTest < ActiveSupport::TestCase
end
def test_instance_values
- assert_equal({"bar" => "bar", "baz" => "baz"}, @source.instance_values)
+ assert_equal({ "bar" => "bar", "baz" => "baz" }, @source.instance_values)
end
def test_instance_exec_passes_arguments_to_block
diff --git a/activesupport/test/core_ext/object/to_query_test.rb b/activesupport/test/core_ext/object/to_query_test.rb
index 2eff475274..298c8bf373 100644
--- a/activesupport/test/core_ext/object/to_query_test.rb
+++ b/activesupport/test/core_ext/object/to_query_test.rb
@@ -33,17 +33,17 @@ class ToQueryTest < ActiveSupport::TestCase
def test_multiple_nested
assert_query_equal "account%5Bperson%5D%5Bid%5D=20&person%5Bid%5D=10",
- Hash[:account, {person: {id: 20}}, :person, {id: 10}]
+ Hash[:account, { person: { id: 20 } }, :person, { id: 10 }]
end
def test_array_values
assert_query_equal "person%5Bid%5D%5B%5D=10&person%5Bid%5D%5B%5D=20",
- person: {id: [10, 20]}
+ person: { id: [10, 20] }
end
def test_array_values_are_not_sorted
assert_query_equal "person%5Bid%5D%5B%5D=20&person%5Bid%5D%5B%5D=10",
- person: {id: [20, 10]}
+ person: { id: [20, 10] }
end
def test_empty_array
@@ -56,7 +56,7 @@ class ToQueryTest < ActiveSupport::TestCase
assert_query_equal "a=1&b%5Bc%5D=3",
a: 1, b: { c: 3, d: {} }
assert_query_equal "",
- a: {b: {c: {}}}
+ a: { b: { c: {} } }
assert_query_equal "b%5Bc%5D=false&b%5Be%5D=&b%5Bf%5D=&p=12",
p: 12, b: { c: false, e: nil, f: "" }
assert_query_equal "b%5Bc%5D=3&b%5Bf%5D=",
diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb
index 773d2c0fb7..6ab1368e53 100644
--- a/activesupport/test/core_ext/time_with_zone_test.rb
+++ b/activesupport/test/core_ext/time_with_zone_test.rb
@@ -1014,7 +1014,7 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < ActiveSupport::TestCase
def test_use_zone_raises_on_invalid_timezone
Time.zone = "Alaska"
assert_raise ArgumentError do
- Time.use_zone("No such timezone exists") { }
+ Time.use_zone("No such timezone exists") {}
end
assert_equal ActiveSupport::TimeZone["Alaska"], Time.zone
end
@@ -1072,9 +1072,9 @@ class TimeWithZoneMethodsForTimeAndDateTimeTest < ActiveSupport::TestCase
end
def test_time_zone_setter_with_invalid_zone
- assert_raise(ArgumentError){ Time.zone = "No such timezone exists" }
- assert_raise(ArgumentError){ Time.zone = -15.hours }
- assert_raise(ArgumentError){ Time.zone = Object.new }
+ assert_raise(ArgumentError) { Time.zone = "No such timezone exists" }
+ assert_raise(ArgumentError) { Time.zone = -15.hours }
+ assert_raise(ArgumentError) { Time.zone = Object.new }
end
def test_find_zone_without_bang_returns_nil_if_time_zone_can_not_be_found
diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb
index 1ee4d7f63c..e0edb4a086 100644
--- a/activesupport/test/dependencies_test.rb
+++ b/activesupport/test/dependencies_test.rb
@@ -659,7 +659,7 @@ class DependenciesTest < ActiveSupport::TestCase
def test_autoload_once_pathnames_do_not_add_to_autoloaded_constants
with_autoloading_fixtures do
- pathnames = ActiveSupport::Dependencies.autoload_paths.collect{|p| Pathname.new(p)}
+ pathnames = ActiveSupport::Dependencies.autoload_paths.collect { |p| Pathname.new(p) }
ActiveSupport::Dependencies.autoload_paths = pathnames
ActiveSupport::Dependencies.autoload_once_paths = pathnames
@@ -756,15 +756,15 @@ class DependenciesTest < ActiveSupport::TestCase
end
def test_new_contants_in_without_constants
- assert_equal [], (ActiveSupport::Dependencies.new_constants_in(Object) { })
- assert ActiveSupport::Dependencies.constant_watch_stack.all? {|k,v| v.empty? }
+ assert_equal [], (ActiveSupport::Dependencies.new_constants_in(Object) {})
+ assert ActiveSupport::Dependencies.constant_watch_stack.all? { |k,v| v.empty? }
end
def test_new_constants_in_with_a_single_constant
assert_equal ["Hello"], ActiveSupport::Dependencies.new_constants_in(Object) {
Object.const_set :Hello, 10
}.map(&:to_s)
- assert ActiveSupport::Dependencies.constant_watch_stack.all? {|k,v| v.empty? }
+ assert ActiveSupport::Dependencies.constant_watch_stack.all? { |k,v| v.empty? }
ensure
remove_constants(:Hello)
end
@@ -781,7 +781,7 @@ class DependenciesTest < ActiveSupport::TestCase
end
assert_equal ["OuterAfter", "OuterBefore"], outer.sort.map(&:to_s)
- assert ActiveSupport::Dependencies.constant_watch_stack.all? {|k,v| v.empty? }
+ assert ActiveSupport::Dependencies.constant_watch_stack.all? { |k,v| v.empty? }
ensure
remove_constants(:OuterBefore, :Inner, :OuterAfter)
end
@@ -800,7 +800,7 @@ class DependenciesTest < ActiveSupport::TestCase
M.const_set :OuterAfter, 30
end
assert_equal ["M::OuterAfter", "M::OuterBefore"], outer.sort
- assert ActiveSupport::Dependencies.constant_watch_stack.all? {|k,v| v.empty? }
+ assert ActiveSupport::Dependencies.constant_watch_stack.all? { |k,v| v.empty? }
ensure
remove_constants(:M)
end
@@ -818,7 +818,7 @@ class DependenciesTest < ActiveSupport::TestCase
M.const_set :OuterAfter, 30
end
assert_equal ["M::OuterAfter", "M::OuterBefore"], outer.sort
- assert ActiveSupport::Dependencies.constant_watch_stack.all? {|k,v| v.empty? }
+ assert ActiveSupport::Dependencies.constant_watch_stack.all? { |k,v| v.empty? }
ensure
remove_constants(:M)
end
@@ -1036,7 +1036,6 @@ class DependenciesTest < ActiveSupport::TestCase
remove_constants(:A)
end
-
def test_autoload_once_paths_should_behave_when_recursively_loading
old_path = ActiveSupport::Dependencies.autoload_once_paths
with_loading "dependencies", "autoloading_fixtures" do
diff --git a/activesupport/test/deprecation_test.rb b/activesupport/test/deprecation_test.rb
index 36c3a44c31..e2a3331cfa 100644
--- a/activesupport/test/deprecation_test.rb
+++ b/activesupport/test/deprecation_test.rb
@@ -35,7 +35,6 @@ class Deprecatee
A = ActiveSupport::Deprecation::DeprecatedConstantProxy.new("Deprecatee::A", "Deprecatee::B::C")
end
-
class DeprecationTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Stream
@@ -364,7 +363,7 @@ class DeprecationTest < ActiveSupport::TestCase
def deprecator_with_messages
klass = Class.new(ActiveSupport::Deprecation)
deprecator = klass.new
- deprecator.behavior = Proc.new{|message, callstack| deprecator.messages << message}
+ deprecator.behavior = Proc.new { |message, callstack| deprecator.messages << message }
def deprecator.messages
@messages ||= []
end
diff --git a/activesupport/test/evented_file_update_checker_test.rb b/activesupport/test/evented_file_update_checker_test.rb
index aaa9aaa397..cc47318974 100644
--- a/activesupport/test/evented_file_update_checker_test.rb
+++ b/activesupport/test/evented_file_update_checker_test.rb
@@ -38,7 +38,7 @@ class EventedFileUpdateCheckerTest < ActiveSupport::TestCase
test "notifies forked processes" do
FileUtils.touch(tmpfiles)
- checker = new_checker(tmpfiles) { }
+ checker = new_checker(tmpfiles) {}
assert !checker.updated?
# Pipes used for flow controll across fork.
diff --git a/activesupport/test/executor_test.rb b/activesupport/test/executor_test.rb
index 11ef4e5a50..0b56ea008f 100644
--- a/activesupport/test/executor_test.rb
+++ b/activesupport/test/executor_test.rb
@@ -21,7 +21,7 @@ class ExecutorTest < ActiveSupport::TestCase
executor.to_run { @foo = true }
executor.to_complete { result = @foo }
- executor.wrap { }
+ executor.wrap {}
assert result
end
@@ -83,7 +83,7 @@ class ExecutorTest < ActiveSupport::TestCase
executor.register_hook(hook)
- executor.wrap { }
+ executor.wrap {}
assert_equal :some_state, supplied_state
end
@@ -103,7 +103,7 @@ class ExecutorTest < ActiveSupport::TestCase
executor.register_hook(hook)
- executor.wrap { }
+ executor.wrap {}
assert_equal nil, supplied_state
end
@@ -127,7 +127,7 @@ class ExecutorTest < ActiveSupport::TestCase
executor.register_hook(hook)
assert_raises(DummyError) do
- executor.wrap { }
+ executor.wrap {}
end
assert_equal :none, supplied_state
@@ -152,7 +152,7 @@ class ExecutorTest < ActiveSupport::TestCase
end
assert_raises(DummyError) do
- executor.wrap { }
+ executor.wrap {}
end
assert_equal :some_state, supplied_state
diff --git a/activesupport/test/file_update_checker_shared_tests.rb b/activesupport/test/file_update_checker_shared_tests.rb
index a749c1947c..cd6a58e840 100644
--- a/activesupport/test/file_update_checker_shared_tests.rb
+++ b/activesupport/test/file_update_checker_shared_tests.rb
@@ -80,7 +80,6 @@ module FileUpdateCheckerSharedTests
assert_equal 1, i
end
-
test "updated should become true when watched files are created" do
i = 0
@@ -92,7 +91,6 @@ module FileUpdateCheckerSharedTests
assert checker.updated?
end
-
test "updated should become true when watched files are modified" do
i = 0
diff --git a/activesupport/test/inflector_test.rb b/activesupport/test/inflector_test.rb
index f0b7dda682..39e8c611e5 100644
--- a/activesupport/test/inflector_test.rb
+++ b/activesupport/test/inflector_test.rb
@@ -80,7 +80,6 @@ class InflectorTest < ActiveSupport::TestCase
end
end
-
def test_overwrite_previous_inflectors
assert_equal("series", ActiveSupport::Inflector.singularize("series"))
ActiveSupport::Inflector.inflections.singular "series", "serie"
diff --git a/activesupport/test/json/decoding_test.rb b/activesupport/test/json/decoding_test.rb
index de314921ec..dd8382754b 100644
--- a/activesupport/test/json/decoding_test.rb
+++ b/activesupport/test/json/decoding_test.rb
@@ -13,57 +13,57 @@ class TestJSONDecoding < ActiveSupport::TestCase
end
TESTS = {
- %q({"returnTo":{"\/categories":"\/"}}) => {"returnTo" => {"/categories" => "/"}},
- %q({"return\\"To\\":":{"\/categories":"\/"}}) => {"return\"To\":" => {"/categories" => "/"}},
- %q({"returnTo":{"\/categories":1}}) => {"returnTo" => {"/categories" => 1}},
- %({"returnTo":[1,"a"]}) => {"returnTo" => [1, "a"]},
- %({"returnTo":[1,"\\"a\\",", "b"]}) => {"returnTo" => [1, "\"a\",", "b"]},
- %({"a": "'", "b": "5,000"}) => {"a" => "'", "b" => "5,000"},
- %({"a": "a's, b's and c's", "b": "5,000"}) => {"a" => "a's, b's and c's", "b" => "5,000"},
+ %q({"returnTo":{"\/categories":"\/"}}) => { "returnTo" => { "/categories" => "/" } },
+ %q({"return\\"To\\":":{"\/categories":"\/"}}) => { "return\"To\":" => { "/categories" => "/" } },
+ %q({"returnTo":{"\/categories":1}}) => { "returnTo" => { "/categories" => 1 } },
+ %({"returnTo":[1,"a"]}) => { "returnTo" => [1, "a"] },
+ %({"returnTo":[1,"\\"a\\",", "b"]}) => { "returnTo" => [1, "\"a\",", "b"] },
+ %({"a": "'", "b": "5,000"}) => { "a" => "'", "b" => "5,000" },
+ %({"a": "a's, b's and c's", "b": "5,000"}) => { "a" => "a's, b's and c's", "b" => "5,000" },
# multibyte
- %({"matzue": "松江", "asakusa": "浅草"}) => {"matzue" => "松江", "asakusa" => "浅草"},
- %({"a": "2007-01-01"}) => {"a" => Date.new(2007, 1, 1)},
- %({"a": "2007-01-01 01:12:34 Z"}) => {"a" => Time.utc(2007, 1, 1, 1, 12, 34)},
+ %({"matzue": "松江", "asakusa": "浅草"}) => { "matzue" => "松江", "asakusa" => "浅草" },
+ %({"a": "2007-01-01"}) => { "a" => Date.new(2007, 1, 1) },
+ %({"a": "2007-01-01 01:12:34 Z"}) => { "a" => Time.utc(2007, 1, 1, 1, 12, 34) },
%(["2007-01-01 01:12:34 Z"]) => [Time.utc(2007, 1, 1, 1, 12, 34)],
%(["2007-01-01 01:12:34 Z", "2007-01-01 01:12:35 Z"]) => [Time.utc(2007, 1, 1, 1, 12, 34), Time.utc(2007, 1, 1, 1, 12, 35)],
# no time zone
- %({"a": "2007-01-01 01:12:34"}) => {"a" => Time.new(2007, 1, 1, 1, 12, 34, "-05:00")},
+ %({"a": "2007-01-01 01:12:34"}) => { "a" => Time.new(2007, 1, 1, 1, 12, 34, "-05:00") },
# invalid date
- %({"a": "1089-10-40"}) => {"a" => "1089-10-40"},
+ %({"a": "1089-10-40"}) => { "a" => "1089-10-40" },
# xmlschema date notation
- %({"a": "2009-08-10T19:01:02"}) => {"a" => Time.new(2009, 8, 10, 19, 1, 2, "-04:00")},
- %({"a": "2009-08-10T19:01:02Z"}) => {"a" => Time.utc(2009, 8, 10, 19, 1, 2)},
- %({"a": "2009-08-10T19:01:02+02:00"}) => {"a" => Time.utc(2009, 8, 10, 17, 1, 2)},
- %({"a": "2009-08-10T19:01:02-05:00"}) => {"a" => Time.utc(2009, 8, 11, 00, 1, 2)},
+ %({"a": "2009-08-10T19:01:02"}) => { "a" => Time.new(2009, 8, 10, 19, 1, 2, "-04:00") },
+ %({"a": "2009-08-10T19:01:02Z"}) => { "a" => Time.utc(2009, 8, 10, 19, 1, 2) },
+ %({"a": "2009-08-10T19:01:02+02:00"}) => { "a" => Time.utc(2009, 8, 10, 17, 1, 2) },
+ %({"a": "2009-08-10T19:01:02-05:00"}) => { "a" => Time.utc(2009, 8, 11, 00, 1, 2) },
# needs to be *exact*
- %({"a": " 2007-01-01 01:12:34 Z "}) => {"a" => " 2007-01-01 01:12:34 Z "},
- %({"a": "2007-01-01 : it's your birthday"}) => {"a" => "2007-01-01 : it's your birthday"},
+ %({"a": " 2007-01-01 01:12:34 Z "}) => { "a" => " 2007-01-01 01:12:34 Z " },
+ %({"a": "2007-01-01 : it's your birthday"}) => { "a" => "2007-01-01 : it's your birthday" },
%([]) => [],
%({}) => {},
- %({"a":1}) => {"a" => 1},
- %({"a": ""}) => {"a" => ""},
- %({"a":"\\""}) => {"a" => "\""},
- %({"a": null}) => {"a" => nil},
- %({"a": true}) => {"a" => true},
- %({"a": false}) => {"a" => false},
- '{"bad":"\\\\","trailing":""}' => {"bad" => "\\", "trailing" => ""},
- %q({"a": "http:\/\/test.host\/posts\/1"}) => {"a" => "http://test.host/posts/1"},
- %q({"a": "\u003cunicode\u0020escape\u003e"}) => {"a" => "<unicode escape>"},
- '{"a": "\\\\u0020skip double backslashes"}' => {"a" => "\\u0020skip double backslashes"},
- %q({"a": "\u003cbr /\u003e"}) => {"a" => "<br />"},
- %q({"b":["\u003ci\u003e","\u003cb\u003e","\u003cu\u003e"]}) => {"b" => ["<i>","<b>","<u>"]},
+ %({"a":1}) => { "a" => 1 },
+ %({"a": ""}) => { "a" => "" },
+ %({"a":"\\""}) => { "a" => "\"" },
+ %({"a": null}) => { "a" => nil },
+ %({"a": true}) => { "a" => true },
+ %({"a": false}) => { "a" => false },
+ '{"bad":"\\\\","trailing":""}' => { "bad" => "\\", "trailing" => "" },
+ %q({"a": "http:\/\/test.host\/posts\/1"}) => { "a" => "http://test.host/posts/1" },
+ %q({"a": "\u003cunicode\u0020escape\u003e"}) => { "a" => "<unicode escape>" },
+ '{"a": "\\\\u0020skip double backslashes"}' => { "a" => "\\u0020skip double backslashes" },
+ %q({"a": "\u003cbr /\u003e"}) => { "a" => "<br />" },
+ %q({"b":["\u003ci\u003e","\u003cb\u003e","\u003cu\u003e"]}) => { "b" => ["<i>","<b>","<u>"] },
# test combination of dates and escaped or unicode encoded data in arrays
%q([{"d":"1970-01-01", "s":"\u0020escape"},{"d":"1970-01-01", "s":"\u0020escape"}]) =>
- [{"d" => Date.new(1970, 1, 1), "s" => " escape"},{"d" => Date.new(1970, 1, 1), "s" => " escape"}],
+ [{ "d" => Date.new(1970, 1, 1), "s" => " escape" },{ "d" => Date.new(1970, 1, 1), "s" => " escape" }],
%q([{"d":"1970-01-01","s":"http:\/\/example.com"},{"d":"1970-01-01","s":"http:\/\/example.com"}]) =>
- [{"d" => Date.new(1970, 1, 1), "s" => "http://example.com"},
- {"d" => Date.new(1970, 1, 1), "s" => "http://example.com"}],
+ [{ "d" => Date.new(1970, 1, 1), "s" => "http://example.com" },
+ { "d" => Date.new(1970, 1, 1), "s" => "http://example.com" }],
# tests escaping of "\n" char with Yaml backend
- %q({"a":"\n"}) => {"a"=>"\n"},
- %q({"a":"\u000a"}) => {"a"=>"\n"},
- %q({"a":"Line1\u000aLine2"}) => {"a"=>"Line1\nLine2"},
+ %q({"a":"\n"}) => { "a"=>"\n" },
+ %q({"a":"\u000a"}) => { "a"=>"\n" },
+ %q({"a":"Line1\u000aLine2"}) => { "a"=>"Line1\nLine2" },
# prevent json unmarshalling
- '{"json_class":"TestJSONDecoding::Foo"}' => {"json_class"=>"TestJSONDecoding::Foo"},
+ '{"json_class":"TestJSONDecoding::Foo"}' => { "json_class"=>"TestJSONDecoding::Foo" },
# json "fragments" - these are invalid JSON, but ActionPack relies on this
'"a string"' => "a string",
"1.1" => 1.1,
@@ -89,7 +89,7 @@ class TestJSONDecoding < ActiveSupport::TestCase
test "json decodes time json with time parsing disabled" do
with_parse_json_times(false) do
- expected = {"a" => "2007-01-01 01:12:34 Z"}
+ expected = { "a" => "2007-01-01 01:12:34 Z" }
assert_equal expected, ActiveSupport::JSON.decode(%({"a": "2007-01-01 01:12:34 Z"}))
end
end
diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb
index 4a9ed22951..d125cc939f 100644
--- a/activesupport/test/json/encoding_test.rb
+++ b/activesupport/test/json/encoding_test.rb
@@ -93,16 +93,16 @@ class TestJSONEncoding < ActiveSupport::TestCase
end
def test_hash_key_identifiers_are_always_quoted
- values = {0 => 0, 1 => 1, :_ => :_, "$" => "$", "a" => "a", :A => :A, :A0 => :A0, "A0B" => "A0B"}
+ values = { 0 => 0, 1 => 1, :_ => :_, "$" => "$", "a" => "a", :A => :A, :A0 => :A0, "A0B" => "A0B" }
assert_equal %w( "$" "A" "A0" "A0B" "_" "a" "0" "1" ).sort, object_keys(ActiveSupport::JSON.encode(values))
end
def test_hash_should_allow_key_filtering_with_only
- assert_equal %({"a":1}), ActiveSupport::JSON.encode({"a" => 1, :b => 2, :c => 3}, only: "a")
+ assert_equal %({"a":1}), ActiveSupport::JSON.encode({ "a" => 1, :b => 2, :c => 3 }, only: "a")
end
def test_hash_should_allow_key_filtering_with_except
- assert_equal %({"b":2}), ActiveSupport::JSON.encode({"foo" => "bar", :b => 2, :c => 3}, except: ["foo", :c])
+ assert_equal %({"b":2}), ActiveSupport::JSON.encode({ "foo" => "bar", :b => 2, :c => 3 }, except: ["foo", :c])
end
def test_time_to_json_includes_local_offset
@@ -135,7 +135,7 @@ class TestJSONEncoding < ActiveSupport::TestCase
h = JSONTest::Hashlike.new
json = h.to_json only: [:foo]
- assert_equal({"foo"=>"hello"}, JSON.parse(json))
+ assert_equal({ "foo"=>"hello" }, JSON.parse(json))
end
def test_object_to_json_with_options
@@ -144,7 +144,7 @@ class TestJSONEncoding < ActiveSupport::TestCase
obj.instance_variable_set :@bar, "world"
json = obj.to_json only: ["foo"]
- assert_equal({"foo"=>"hello"}, JSON.parse(json))
+ assert_equal({ "foo"=>"hello" }, JSON.parse(json))
end
def test_struct_to_json_with_options
@@ -153,7 +153,7 @@ class TestJSONEncoding < ActiveSupport::TestCase
struct.bar = "world"
json = struct.to_json only: [:foo]
- assert_equal({"foo"=>"hello"}, JSON.parse(json))
+ assert_equal({ "foo"=>"hello" }, JSON.parse(json))
end
def test_hash_should_pass_encoding_options_to_children_in_as_json
@@ -166,7 +166,7 @@ class TestJSONEncoding < ActiveSupport::TestCase
}
json = person.as_json only: [:address, :city]
- assert_equal({ "address" => { "city" => "London" }}, json)
+ assert_equal({ "address" => { "city" => "London" } }, json)
end
def test_hash_should_pass_encoding_options_to_children_in_to_json
@@ -184,13 +184,13 @@ class TestJSONEncoding < ActiveSupport::TestCase
def test_array_should_pass_encoding_options_to_children_in_as_json
people = [
- { name: "John", address: { city: "London", country: "UK" }},
- { name: "Jean", address: { city: "Paris" , country: "France" }}
+ { name: "John", address: { city: "London", country: "UK" } },
+ { name: "Jean", address: { city: "Paris" , country: "France" } }
]
json = people.as_json only: [:address, :city]
expected = [
- { "address" => { "city" => "London" }},
- { "address" => { "city" => "Paris" }}
+ { "address" => { "city" => "London" } },
+ { "address" => { "city" => "Paris" } }
]
assert_equal(expected, json)
@@ -198,8 +198,8 @@ class TestJSONEncoding < ActiveSupport::TestCase
def test_array_should_pass_encoding_options_to_children_in_to_json
people = [
- { name: "John", address: { city: "London", country: "UK" }},
- { name: "Jean", address: { city: "Paris" , country: "France" }}
+ { name: "John", address: { city: "London", country: "UK" } },
+ { name: "Jean", address: { city: "Paris" , country: "France" } }
]
json = people.to_json only: [:address, :city]
@@ -210,8 +210,8 @@ class TestJSONEncoding < ActiveSupport::TestCase
include Enumerable
def initialize()
@people = [
- { name: "John", address: { city: "London", country: "UK" }},
- { name: "Jean", address: { city: "Paris" , country: "France" }}
+ { name: "John", address: { city: "London", country: "UK" } },
+ { name: "Jean", address: { city: "Paris" , country: "France" } }
]
end
def each(*, &blk)
@@ -225,8 +225,8 @@ class TestJSONEncoding < ActiveSupport::TestCase
def test_enumerable_should_generate_json_with_as_json
json = People.new.as_json only: [:address, :city]
expected = [
- { "address" => { "city" => "London" }},
- { "address" => { "city" => "Paris" }}
+ { "address" => { "city" => "London" } },
+ { "address" => { "city" => "Paris" } }
]
assert_equal(expected, json)
@@ -240,8 +240,8 @@ class TestJSONEncoding < ActiveSupport::TestCase
def test_enumerable_should_pass_encoding_options_to_children_in_as_json
json = People.new.each.as_json only: [:address, :city]
expected = [
- { "address" => { "city" => "London" }},
- { "address" => { "city" => "Paris" }}
+ { "address" => { "city" => "London" } },
+ { "address" => { "city" => "Paris" } }
]
assert_equal(expected, json)
@@ -267,9 +267,9 @@ class TestJSONEncoding < ActiveSupport::TestCase
f.foo = "hello"
f.bar = "world"
- hash = {"foo" => f, "other_hash" => {"foo" => "other_foo", "test" => "other_test"}}
- assert_equal({"foo"=>{"foo"=>"hello","bar"=>"world"},
- "other_hash" => {"foo"=>"other_foo","test"=>"other_test"}}, ActiveSupport::JSON.decode(hash.to_json))
+ hash = { "foo" => f, "other_hash" => { "foo" => "other_foo", "test" => "other_test" } }
+ assert_equal({ "foo"=>{ "foo"=>"hello","bar"=>"world" },
+ "other_hash" => { "foo"=>"other_foo","test"=>"other_test" } }, ActiveSupport::JSON.decode(hash.to_json))
end
def test_array_to_json_should_not_keep_options_around
@@ -277,9 +277,9 @@ class TestJSONEncoding < ActiveSupport::TestCase
f.foo = "hello"
f.bar = "world"
- array = [f, {"foo" => "other_foo", "test" => "other_test"}]
- assert_equal([{"foo"=>"hello","bar"=>"world"},
- {"foo"=>"other_foo","test"=>"other_test"}], ActiveSupport::JSON.decode(array.to_json))
+ array = [f, { "foo" => "other_foo", "test" => "other_test" }]
+ assert_equal([{ "foo"=>"hello","bar"=>"world" },
+ { "foo"=>"other_foo","test"=>"other_test" }], ActiveSupport::JSON.decode(array.to_json))
end
class OptionsTest
@@ -290,7 +290,7 @@ class TestJSONEncoding < ActiveSupport::TestCase
def test_hash_as_json_without_options
json = { foo: OptionsTest.new }.as_json
- assert_equal({"foo" => :default}, json)
+ assert_equal({ "foo" => :default }, json)
end
def test_array_as_json_without_options
@@ -306,7 +306,6 @@ class TestJSONEncoding < ActiveSupport::TestCase
user_birthday = Struct::UserNameAndDate.new "David", Date.new(2010, 01, 01)
custom = Struct::Custom.new "David", user_birthday
-
json_strings = ""
json_string_and_date = ""
json_custom = ""
@@ -317,15 +316,15 @@ class TestJSONEncoding < ActiveSupport::TestCase
json_custom = custom.to_json
end
- assert_equal({"name" => "David",
+ assert_equal({ "name" => "David",
"sub" => {
"name" => "David",
- "date" => "2010-01-01" }}, ActiveSupport::JSON.decode(json_custom))
+ "date" => "2010-01-01" } }, ActiveSupport::JSON.decode(json_custom))
- assert_equal({"name" => "David", "email" => "sample@example.com"},
+ assert_equal({ "name" => "David", "email" => "sample@example.com" },
ActiveSupport::JSON.decode(json_strings))
- assert_equal({"name" => "David", "date" => "2010-01-01"},
+ assert_equal({ "name" => "David", "date" => "2010-01-01" },
ActiveSupport::JSON.decode(json_string_and_date))
end
diff --git a/activesupport/test/json/encoding_test_cases.rb b/activesupport/test/json/encoding_test_cases.rb
index f8c44f314f..ff2ed3a788 100644
--- a/activesupport/test/json/encoding_test_cases.rb
+++ b/activesupport/test/json/encoding_test_cases.rb
@@ -51,8 +51,8 @@ module JSONTest
ArrayTests = [[ ["a", "b", "c"], %([\"a\",\"b\",\"c\"]) ],
[ [1, "a", :b, nil, false], %([1,\"a\",\"b\",null,false]) ]]
- HashTests = [[ {foo: "bar"}, %({\"foo\":\"bar\"}) ],
- [ {1 => 1, 2 => "a", 3 => :b, 4 => nil, 5 => false}, %({\"1\":1,\"2\":\"a\",\"3\":\"b\",\"4\":null,\"5\":false}) ]]
+ HashTests = [[ { foo: "bar" }, %({\"foo\":\"bar\"}) ],
+ [ { 1 => 1, 2 => "a", 3 => :b, 4 => nil, 5 => false }, %({\"1\":1,\"2\":\"a\",\"3\":\"b\",\"4\":null,\"5\":false}) ]]
RangeTests = [[ 1..2, %("1..2")],
[ 1...2, %("1...2")],
diff --git a/activesupport/test/logger_test.rb b/activesupport/test/logger_test.rb
index 74e94bb9d7..ece4167de9 100644
--- a/activesupport/test/logger_test.rb
+++ b/activesupport/test/logger_test.rb
@@ -78,13 +78,13 @@ class LoggerTest < ActiveSupport::TestCase
def test_should_add_message_passed_as_block_when_using_add
@logger.level = Logger::INFO
- @logger.add(Logger::INFO) {@message}
+ @logger.add(Logger::INFO) { @message }
assert @output.string.include?(@message)
end
def test_should_add_message_passed_as_block_when_using_shortcut
@logger.level = Logger::INFO
- @logger.info {@message}
+ @logger.info { @message }
assert @output.string.include?(@message)
end
@@ -96,14 +96,14 @@ class LoggerTest < ActiveSupport::TestCase
def test_should_convert_message_to_string_when_passed_in_block
@logger.level = Logger::INFO
- @logger.info {@integer_message}
+ @logger.info { @integer_message }
assert @output.string.include?(@integer_message.to_s)
end
def test_should_not_evaluate_block_if_message_wont_be_logged
@logger.level = Logger::INFO
evaluated = false
- @logger.add(Logger::DEBUG) {evaluated = true}
+ @logger.add(Logger::DEBUG) { evaluated = true }
assert evaluated == false
end
diff --git a/activesupport/test/multibyte_chars_test.rb b/activesupport/test/multibyte_chars_test.rb
index 9ca9c7c803..54429f4aab 100644
--- a/activesupport/test/multibyte_chars_test.rb
+++ b/activesupport/test/multibyte_chars_test.rb
@@ -208,7 +208,7 @@ class MultibyteCharsUTF8BehaviourTest < ActiveSupport::TestCase
end
def test_insert_throws_index_error
- assert_raise(IndexError) { @chars.insert(-12, "わ")}
+ assert_raise(IndexError) { @chars.insert(-12, "わ") }
assert_raise(IndexError) { @chars.insert(12, "わ") }
end
@@ -479,7 +479,7 @@ class MultibyteCharsUTF8BehaviourTest < ActiveSupport::TestCase
assert_equal "Hello", chars.method(:capitalize!).call # Defined on Chars
assert_equal "Hello", chars
assert_equal "jello", "hello".mb_chars.method(:gsub).call(/h/, "j") # Defined on String
- assert_raise(NameError){ "".mb_chars.method(:undefined_method) } # Not defined
+ assert_raise(NameError) { "".mb_chars.method(:undefined_method) } # Not defined
end
def test_acts_like_string
diff --git a/activesupport/test/multibyte_conformance_test.rb b/activesupport/test/multibyte_conformance_test.rb
index a98e542783..bf004d7924 100644
--- a/activesupport/test/multibyte_conformance_test.rb
+++ b/activesupport/test/multibyte_conformance_test.rb
@@ -94,7 +94,7 @@ class MultibyteConformanceTest < ActiveSupport::TestCase
next unless cols.length == 5
# codepoints are in hex in the test suite, pack wants them as integers
- cols.map!{|c| c.split.map{|codepoint| codepoint.to_i(16)}.pack("U*") }
+ cols.map! { |c| c.split.map { |codepoint| codepoint.to_i(16) }.pack("U*") }
cols << comment
yield(*cols)
@@ -103,6 +103,6 @@ class MultibyteConformanceTest < ActiveSupport::TestCase
end
def inspect_codepoints(str)
- str.to_s.unpack("U*").map{|cp| cp.to_s(16) }.join(" ")
+ str.to_s.unpack("U*").map { |cp| cp.to_s(16) }.join(" ")
end
end
diff --git a/activesupport/test/multibyte_grapheme_break_conformance_test.rb b/activesupport/test/multibyte_grapheme_break_conformance_test.rb
index bb7668acd3..5dc42df08d 100644
--- a/activesupport/test/multibyte_grapheme_break_conformance_test.rb
+++ b/activesupport/test/multibyte_grapheme_break_conformance_test.rb
@@ -40,12 +40,12 @@ class MultibyteGraphemeBreakConformanceTest < ActiveSupport::TestCase
cols, comment = line.split("#")
# Cluster breaks are represented by ÷
- clusters = cols.split("÷").map{|e| e.strip}.reject{|e| e.empty? }
+ clusters = cols.split("÷").map { |e| e.strip }.reject { |e| e.empty? }
clusters = clusters.map do |cluster|
# Codepoints within each cluster are separated by ×
- codepoints = cluster.split("×").map{|e| e.strip}.reject{|e| e.empty? }
+ codepoints = cluster.split("×").map { |e| e.strip }.reject { |e| e.empty? }
# codepoints are in hex in the test suite, pack wants them as integers
- codepoints.map{|codepoint| codepoint.to_i(16)}
+ codepoints.map { |codepoint| codepoint.to_i(16) }
end
# The tests contain a solitary U+D800 <Non Private Use High
diff --git a/activesupport/test/multibyte_normalization_conformance_test.rb b/activesupport/test/multibyte_normalization_conformance_test.rb
index 4f1ace4346..716e6487aa 100644
--- a/activesupport/test/multibyte_normalization_conformance_test.rb
+++ b/activesupport/test/multibyte_normalization_conformance_test.rb
@@ -94,11 +94,11 @@ class MultibyteNormalizationConformanceTest < ActiveSupport::TestCase
next if line.empty? || line.start_with?("#")
cols, comment = line.split("#")
- cols = cols.split(";").map{|e| e.strip}.reject{|e| e.empty? }
+ cols = cols.split(";").map { |e| e.strip }.reject { |e| e.empty? }
next unless cols.length == 5
# codepoints are in hex in the test suite, pack wants them as integers
- cols.map!{|c| c.split.map{|codepoint| codepoint.to_i(16)}.pack("U*") }
+ cols.map! { |c| c.split.map { |codepoint| codepoint.to_i(16) }.pack("U*") }
cols << comment
yield(*cols)
@@ -107,6 +107,6 @@ class MultibyteNormalizationConformanceTest < ActiveSupport::TestCase
end
def inspect_codepoints(str)
- str.to_s.unpack("U*").map{|cp| cp.to_s(16) }.join(" ")
+ str.to_s.unpack("U*").map { |cp| cp.to_s(16) }.join(" ")
end
end
diff --git a/activesupport/test/multibyte_test_helpers.rb b/activesupport/test/multibyte_test_helpers.rb
index 29a384729a..22c586c50d 100644
--- a/activesupport/test/multibyte_test_helpers.rb
+++ b/activesupport/test/multibyte_test_helpers.rb
@@ -30,7 +30,7 @@ module MultibyteTestHelpers
end
def inspect_codepoints(str)
- str.to_s.unpack("U*").map{|cp| cp.to_s(16) }.join(" ")
+ str.to_s.unpack("U*").map { |cp| cp.to_s(16) }.join(" ")
end
def assert_equal_codepoints(expected, actual, message=nil)
diff --git a/activesupport/test/multibyte_unicode_database_test.rb b/activesupport/test/multibyte_unicode_database_test.rb
index 924db303b6..3724782930 100644
--- a/activesupport/test/multibyte_unicode_database_test.rb
+++ b/activesupport/test/multibyte_unicode_database_test.rb
@@ -1,6 +1,5 @@
require "abstract_unit"
-
class MultibyteUnicodeDatabaseTest < ActiveSupport::TestCase
include ActiveSupport::Multibyte::Unicode
diff --git a/activesupport/test/notifications_test.rb b/activesupport/test/notifications_test.rb
index 106aa9c892..a6f0d82e8a 100644
--- a/activesupport/test/notifications_test.rb
+++ b/activesupport/test/notifications_test.rb
@@ -31,7 +31,7 @@ module Notifications
expected = [name, name]
events = []
- callback = lambda {|*_| events << _.first}
+ callback = lambda { |*_| events << _.first }
ActiveSupport::Notifications.subscribed(callback, name) do
ActiveSupport::Notifications.instrument(name)
ActiveSupport::Notifications.instrument(name2)
diff --git a/activesupport/test/number_helper_i18n_test.rb b/activesupport/test/number_helper_i18n_test.rb
index 32e6e22525..4f58e6607a 100644
--- a/activesupport/test/number_helper_i18n_test.rb
+++ b/activesupport/test/number_helper_i18n_test.rb
@@ -26,9 +26,9 @@ module ActiveSupport
decimal_units: {
format: "%n %u",
units: {
- deci: {one: "Tenth", other: "Tenths"},
+ deci: { one: "Tenth", other: "Tenths" },
unit: "u",
- ten: {one: "Ten", other: "Tens"},
+ ten: { one: "Ten", other: "Tens" },
thousand: "t",
million: "m",
billion: "b",
@@ -37,10 +37,10 @@ module ActiveSupport
}
}
},
- percentage: { format: {delimiter: "", precision: 2, strip_insignificant_zeros: true} },
- precision: { format: {delimiter: "", significant: true} }
+ percentage: { format: { delimiter: "", precision: 2, strip_insignificant_zeros: true } },
+ precision: { format: { delimiter: "", significant: true } }
},
- custom_units_for_number_to_human: {mili: "mm", centi: "cm", deci: "dm", unit: "m", ten: "dam", hundred: "hm", thousand: "km"}
+ custom_units_for_number_to_human: { mili: "mm", centi: "cm", deci: "dm", unit: "m", ten: "dam", hundred: "hm", thousand: "km" }
end
def teardown
diff --git a/activesupport/test/number_helper_test.rb b/activesupport/test/number_helper_test.rb
index cd6f9ad234..1a59210018 100644
--- a/activesupport/test/number_helper_test.rb
+++ b/activesupport/test/number_helper_test.rb
@@ -316,13 +316,13 @@ module ActiveSupport
def test_number_to_human_with_custom_units
[@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
#Only integers
- volume = {unit: "ml", thousand: "lt", million: "m3"}
+ volume = { unit: "ml", thousand: "lt", million: "m3" }
assert_equal "123 lt", number_helper.number_to_human(123456, units: volume)
assert_equal "12 ml", number_helper.number_to_human(12, units: volume)
assert_equal "1.23 m3", number_helper.number_to_human(1234567, units: volume)
#Including fractionals
- distance = {mili: "mm", centi: "cm", deci: "dm", unit: "m", ten: "dam", hundred: "hm", thousand: "km"}
+ distance = { mili: "mm", centi: "cm", deci: "dm", unit: "m", ten: "dam", hundred: "hm", thousand: "km" }
assert_equal "1.23 mm", number_helper.number_to_human(0.00123, units: distance)
assert_equal "1.23 cm", number_helper.number_to_human(0.0123, units: distance)
assert_equal "1.23 dm", number_helper.number_to_human(0.123, units: distance)
@@ -335,21 +335,21 @@ module ActiveSupport
assert_equal "12.3 km", number_helper.number_to_human(12300, units: distance)
#The quantifiers don't need to be a continuous sequence
- gangster = {hundred: "hundred bucks", million: "thousand quids"}
+ gangster = { hundred: "hundred bucks", million: "thousand quids" }
assert_equal "1 hundred bucks", number_helper.number_to_human(100, units: gangster)
assert_equal "25 hundred bucks", number_helper.number_to_human(2500, units: gangster)
assert_equal "25 thousand quids", number_helper.number_to_human(25000000, units: gangster)
assert_equal "12300 thousand quids", number_helper.number_to_human(12345000000, units: gangster)
#Spaces are stripped from the resulting string
- assert_equal "4", number_helper.number_to_human(4, units: {unit: "", ten: "tens "})
- assert_equal "4.5 tens", number_helper.number_to_human(45, units: {unit: "", ten: " tens "})
+ assert_equal "4", number_helper.number_to_human(4, units: { unit: "", ten: "tens " })
+ assert_equal "4.5 tens", number_helper.number_to_human(45, units: { unit: "", ten: " tens " })
end
end
def test_number_to_human_with_custom_units_that_are_missing_the_needed_key
[@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
- assert_equal "123", number_helper.number_to_human(123, units: { thousand: "k"})
+ assert_equal "123", number_helper.number_to_human(123, units: { thousand: "k" })
assert_equal "123", number_helper.number_to_human(123, units: {})
end
end
@@ -357,7 +357,7 @@ module ActiveSupport
def test_number_to_human_with_custom_format
[@instance_with_helpers, TestClassWithClassNumberHelpers, ActiveSupport::NumberHelper].each do |number_helper|
assert_equal "123 times Thousand", number_helper.number_to_human(123456, format: "%n times %u")
- volume = {unit: "ml", thousand: "lt", million: "m3"}
+ volume = { unit: "ml", thousand: "lt", million: "m3" }
assert_equal "123.lt", number_helper.number_to_human(123456, units: volume, format: "%n.%u")
end
end
diff --git a/activesupport/test/option_merger_test.rb b/activesupport/test/option_merger_test.rb
index 2bac550452..c5a6d304ee 100644
--- a/activesupport/test/option_merger_test.rb
+++ b/activesupport/test/option_merger_test.rb
@@ -3,11 +3,11 @@ require "active_support/core_ext/object/with_options"
class OptionMergerTest < ActiveSupport::TestCase
def setup
- @options = {hello: "world"}
+ @options = { hello: "world" }
end
def test_method_with_options_merges_options_when_options_are_present
- local_options = {cool: true}
+ local_options = { cool: true }
with_options(@options) do |o|
assert_equal local_options, method_with_options(local_options)
@@ -24,7 +24,7 @@ class OptionMergerTest < ActiveSupport::TestCase
end
def test_method_with_options_allows_to_overwrite_options
- local_options = {hello: "moon"}
+ local_options = { hello: "moon" }
assert_equal @options.keys, local_options.keys
with_options(@options) do |o|
diff --git a/activesupport/test/ordered_hash_test.rb b/activesupport/test/ordered_hash_test.rb
index f7977b276b..d2dfc34040 100644
--- a/activesupport/test/ordered_hash_test.rb
+++ b/activesupport/test/ordered_hash_test.rb
@@ -94,13 +94,13 @@ class OrderedHashTest < ActiveSupport::TestCase
def test_each
values = []
- assert_equal @ordered_hash, @ordered_hash.each {|key, value| values << value}
+ assert_equal @ordered_hash, @ordered_hash.each { |key, value| values << value }
assert_equal @values, values
assert_kind_of Enumerator, @ordered_hash.each
end
def test_each_with_index
- @ordered_hash.each_with_index { |pair, index| assert_equal [@keys[index], @values[index]], pair}
+ @ordered_hash.each_with_index { |pair, index| assert_equal [@keys[index], @values[index]], pair }
end
def test_each_pair
@@ -242,7 +242,7 @@ class OrderedHashTest < ActiveSupport::TestCase
end
def test_nested_under_indifferent_access
- flash = {a: ActiveSupport::OrderedHash[:b, 1, :c, 2]}.with_indifferent_access
+ flash = { a: ActiveSupport::OrderedHash[:b, 1, :c, 2] }.with_indifferent_access
assert_kind_of ActiveSupport::OrderedHash, flash[:a]
end
diff --git a/activesupport/test/reloader_test.rb b/activesupport/test/reloader_test.rb
index c6d852cf39..67d8c4b0e3 100644
--- a/activesupport/test/reloader_test.rb
+++ b/activesupport/test/reloader_test.rb
@@ -21,13 +21,13 @@ class ReloaderTest < ActiveSupport::TestCase
r = new_reloader { true }
invoked = false
r.to_run { invoked = true }
- r.wrap { }
+ r.wrap {}
assert invoked
r = new_reloader { false }
invoked = false
r.to_run { invoked = true }
- r.wrap { }
+ r.wrap {}
assert !invoked
end
@@ -39,7 +39,7 @@ class ReloaderTest < ActiveSupport::TestCase
reloader.executor.to_run { called << :executor_run }
reloader.executor.to_complete { called << :executor_complete }
- reloader.wrap { }
+ reloader.wrap {}
assert_equal [:executor_run, :reloader_run, :prepare, :reloader_complete, :executor_complete], called
called = []
@@ -49,7 +49,7 @@ class ReloaderTest < ActiveSupport::TestCase
reloader.check = lambda { false }
called = []
- reloader.wrap { }
+ reloader.wrap {}
assert_equal [:executor_run, :executor_complete], called
called = []
diff --git a/activesupport/test/rescuable_test.rb b/activesupport/test/rescuable_test.rb
index 283afca642..7e5c3d1a8f 100644
--- a/activesupport/test/rescuable_test.rb
+++ b/activesupport/test/rescuable_test.rb
@@ -97,7 +97,6 @@ class CoolStargate < Stargate
end
end
-
class RescuableTest < ActiveSupport::TestCase
def setup
@stargate = Stargate.new
diff --git a/activesupport/test/safe_buffer_test.rb b/activesupport/test/safe_buffer_test.rb
index 36e262745c..4d083ab773 100644
--- a/activesupport/test/safe_buffer_test.rb
+++ b/activesupport/test/safe_buffer_test.rb
@@ -58,7 +58,7 @@ class SafeBufferTest < ActiveSupport::TestCase
str = "hello!"
data = { "str" => ActiveSupport::SafeBuffer.new(str) }
yaml = YAML.dump data
- assert_equal({"str" => str}, YAML.load(yaml))
+ assert_equal({ "str" => str }, YAML.load(yaml))
end
test "Should work with primitive-like-strings in to_yaml conversion" do
diff --git a/activesupport/test/share_lock_test.rb b/activesupport/test/share_lock_test.rb
index 8155d46934..a5970591fa 100644
--- a/activesupport/test/share_lock_test.rb
+++ b/activesupport/test/share_lock_test.rb
@@ -17,7 +17,7 @@ class ShareLockTest < ActiveSupport::TestCase
def test_sharing_doesnt_block
with_thread_waiting_in_lock_section(:sharing) do |sharing_thread_latch|
- assert_threads_not_stuck(Thread.new {@lock.sharing {} })
+ assert_threads_not_stuck(Thread.new { @lock.sharing {} })
end
end
diff --git a/activesupport/test/transliterate_test.rb b/activesupport/test/transliterate_test.rb
index fd417d4250..040ddd25fc 100644
--- a/activesupport/test/transliterate_test.rb
+++ b/activesupport/test/transliterate_test.rb
@@ -13,7 +13,7 @@ class TransliterateTest < ActiveSupport::TestCase
# create string with range of Unicode's western characters with
# diacritics, excluding the division and multiplication signs which for
# some reason or other are floating in the middle of all the letters.
- string = (0xC0..0x17E).to_a.reject {|c| [0xD7, 0xF7].include?(c)}.pack("U*")
+ string = (0xC0..0x17E).to_a.reject { |c| [0xD7, 0xF7].include?(c) }.pack("U*")
string.each_char do |char|
assert_match %r{^[a-zA-Z']*$}, ActiveSupport::Inflector.transliterate(char)
end
@@ -21,7 +21,7 @@ class TransliterateTest < ActiveSupport::TestCase
def test_transliterate_should_work_with_custom_i18n_rules_and_uncomposed_utf8
char = [117, 776].pack("U*") # "ü" as ASCII "u" plus COMBINING DIAERESIS
- I18n.backend.store_translations(:de, i18n: {transliterate: {rule: {"ü" => "ue"}}})
+ I18n.backend.store_translations(:de, i18n: { transliterate: { rule: { "ü" => "ue" } } })
default_locale, I18n.locale = I18n.locale, :de
assert_equal "ue", ActiveSupport::Inflector.transliterate(char)
ensure
diff --git a/activesupport/test/xml_mini/jdom_engine_test.rb b/activesupport/test/xml_mini/jdom_engine_test.rb
index 43edd49663..a776ad25c4 100644
--- a/activesupport/test/xml_mini/jdom_engine_test.rb
+++ b/activesupport/test/xml_mini/jdom_engine_test.rb
@@ -3,7 +3,6 @@ if RUBY_PLATFORM.include?("java")
require "active_support/xml_mini"
require "active_support/core_ext/hash/conversions"
-
class JDOMEngineTest < ActiveSupport::TestCase
include ActiveSupport
@@ -56,7 +55,6 @@ if RUBY_PLATFORM.include?("java")
end
end
-
def test_not_allowed_to_load_external_doctypes
attack_xml = <<-EOT
<!DOCTYPE member SYSTEM "file://#{FILES_DIR}/jdom_doctype.dtd">
diff --git a/activesupport/test/xml_mini/libxml_engine_test.rb b/activesupport/test/xml_mini/libxml_engine_test.rb
index d5fd17d06e..81b0d3c407 100644
--- a/activesupport/test/xml_mini/libxml_engine_test.rb
+++ b/activesupport/test/xml_mini/libxml_engine_test.rb
@@ -191,7 +191,6 @@ else
eoxml
end
-
private
def assert_equal_rexml(xml)
parsed_xml = XmlMini.parse(xml)
diff --git a/activesupport/test/xml_mini/rexml_engine_test.rb b/activesupport/test/xml_mini/rexml_engine_test.rb
index e616b73162..dc62f3f671 100644
--- a/activesupport/test/xml_mini/rexml_engine_test.rb
+++ b/activesupport/test/xml_mini/rexml_engine_test.rb
@@ -39,6 +39,6 @@ class REXMLEngineTest < ActiveSupport::TestCase
def test_parse_from_frozen_string
ActiveSupport::XmlMini.backend = "REXML"
xml_string = "<root></root>".freeze
- assert_equal({"root" => {}}, ActiveSupport::XmlMini.parse(xml_string))
+ assert_equal({ "root" => {} }, ActiveSupport::XmlMini.parse(xml_string))
end
end
diff --git a/activesupport/test/xml_mini_test.rb b/activesupport/test/xml_mini_test.rb
index 2d79e71343..b15ccfb764 100644
--- a/activesupport/test/xml_mini_test.rb
+++ b/activesupport/test/xml_mini_test.rb
@@ -63,16 +63,16 @@ module XmlMiniTest
def setup
@xml = ActiveSupport::XmlMini
- @options = {skip_instruct: true, builder: Builder::XmlMarkup.new}
+ @options = { skip_instruct: true, builder: Builder::XmlMarkup.new }
end
test "#to_tag accepts a callable object and passes options with the builder" do
- @xml.to_tag(:some_tag, lambda {|o| o[:builder].br }, @options)
+ @xml.to_tag(:some_tag, lambda { |o| o[:builder].br }, @options)
assert_xml "<br/>"
end
test "#to_tag accepts a callable object and passes options and tag name" do
- @xml.to_tag(:tag, lambda {|o, t| o[:builder].b(t) }, @options)
+ @xml.to_tag(:tag, lambda { |o, t| o[:builder].b(t) }, @options)
assert_xml "<b>tag</b>"
end
@@ -317,13 +317,13 @@ product:
YAML
expected = {
"product"=> [
- {"sku"=>"BL394D", "quantity"=>4, "description"=>"Basketball"}
+ { "sku"=>"BL394D", "quantity"=>4, "description"=>"Basketball" }
]
}
parser = @parsing["yaml"]
assert_equal(expected, parser.call(yaml))
- assert_equal({1 => "test"}, parser.call(1 => "test"))
- assert_equal({"1 => 'test'"=>nil}, parser.call("{1 => 'test'}"))
+ assert_equal({ 1 => "test" }, parser.call(1 => "test"))
+ assert_equal({ "1 => 'test'"=>nil }, parser.call("{1 => 'test'}"))
end
def test_base64Binary_and_binary
diff --git a/guides/rails_guides/helpers.rb b/guides/rails_guides/helpers.rb
index c7d3a38ba9..888b51b1ef 100644
--- a/guides/rails_guides/helpers.rb
+++ b/guides/rails_guides/helpers.rb
@@ -19,7 +19,7 @@ module RailsGuides
end
def documents_flat
- documents_by_section.flat_map {|section| section["documents"]}
+ documents_by_section.flat_map { |section| section["documents"] }
end
def finished_documents(documents)
diff --git a/guides/rails_guides/kindle.rb b/guides/rails_guides/kindle.rb
index 675df8e55b..6fb8183cb1 100644
--- a/guides/rails_guides/kindle.rb
+++ b/guides/rails_guides/kindle.rb
@@ -19,7 +19,7 @@ module Kindle
puts "=> Arranging html pages in document order"
toc = File.read("toc.ncx")
doc = Nokogiri::XML(toc).xpath("//ncx:content", "ncx" => "http://www.daisy.org/z3986/2005/ncx/")
- html_pages = doc.select {|c| c[:src]}.map {|c| c[:src]}.uniq
+ html_pages = doc.select { |c| c[:src] }.map { |c| c[:src] }.uniq
generate_front_matter(html_pages)
@@ -37,13 +37,13 @@ module Kindle
def generate_front_matter(html_pages)
frontmatter = []
- html_pages.delete_if {|x|
+ html_pages.delete_if { |x|
if x =~ /(toc|welcome|credits|copyright).html/
frontmatter << x unless x =~ /toc/
true
end
}
- html = frontmatter.map {|x|
+ html = frontmatter.map { |x|
Nokogiri::HTML(File.open(x)).at("body").inner_html
}.join("\n")
@@ -56,7 +56,7 @@ module Kindle
h2["id"] = h2.inner_text.gsub(/\s/, "-")
end
add_head_section fdoc, "Front Matter"
- File.open("frontmatter.html","w") {|f| f.puts fdoc.to_html}
+ File.open("frontmatter.html","w") { |f| f.puts fdoc.to_html }
html_pages.unshift "frontmatter.html"
end
@@ -67,18 +67,18 @@ module Kindle
doc = Nokogiri::HTML(File.open(page))
title = doc.at("title").inner_text.gsub("Ruby on Rails Guides: ", "")
title = page.capitalize.gsub(".html", "") if title.strip == ""
- File.open("sections/%03d/_section.txt" % section_idx, "w") {|f| f.puts title}
+ File.open("sections/%03d/_section.txt" % section_idx, "w") { |f| f.puts title }
doc.xpath("//h3[@id]").each_with_index do |h3,item_idx|
subsection = h3.inner_text
- content = h3.xpath("./following-sibling::*").take_while {|x| x.name != "h3"}.map(&:to_html)
+ content = h3.xpath("./following-sibling::*").take_while { |x| x.name != "h3" }.map(&:to_html)
item = Nokogiri::HTML(h3.to_html + content.join("\n"))
item_path = "sections/%03d/%03d.html" % [section_idx, item_idx]
add_head_section(item, subsection)
item.search("img").each do |img|
img["src"] = "#{Dir.pwd}/#{img['src']}"
end
- item.xpath("//li/p").each {|p| p.swap(p.children); p.remove}
- File.open(item_path, "w") {|f| f.puts item.to_html}
+ item.xpath("//li/p").each { |p| p.swap(p.children); p.remove }
+ File.open(item_path, "w") { |f| f.puts item.to_html }
end
end
end
@@ -101,7 +101,7 @@ module Kindle
"mobi_outfile" => mobi_outfile
}
puts document.to_yaml
- File.open("_document.yml", "w"){|f| f.puts document.to_yaml}
+ File.open("_document.yml", "w") { |f| f.puts document.to_yaml }
end
def add_head_section(doc, title)
diff --git a/guides/rails_guides/markdown.rb b/guides/rails_guides/markdown.rb
index e6c9fea87e..33563d669c 100644
--- a/guides/rails_guides/markdown.rb
+++ b/guides/rails_guides/markdown.rb
@@ -54,7 +54,8 @@ module RailsGuides
end
def engine
- @engine ||= Redcarpet::Markdown.new(Renderer, no_intra_emphasis: true,
+ @engine ||= Redcarpet::Markdown.new(Renderer,
+ no_intra_emphasis: true,
fenced_code_blocks: true,
autolink: true,
strikethrough: true,
diff --git a/guides/source/5_0_release_notes.md b/guides/source/5_0_release_notes.md
index 3710247582..45f396bbd6 100644
--- a/guides/source/5_0_release_notes.md
+++ b/guides/source/5_0_release_notes.md
@@ -1002,7 +1002,7 @@ Please refer to the [Changelog][active-support] for detailed changes.
* Added `#prev_day` and `#next_day` counterparts to `#yesterday` and
`#tomorrow` for `Date`, `Time`, and `DateTime`.
- ([Pull Request](httpshttps://github.com/rails/rails/pull/18335))
+ ([Pull Request](https://github.com/rails/rails/pull/18335))
* Added `SecureRandom.base58` for generation of random base58 strings.
([commit](https://github.com/rails/rails/commit/b1093977110f18ae0cafe56c3d99fc22a7d54d1b))
diff --git a/guides/source/action_cable_overview.md b/guides/source/action_cable_overview.md
index 02db86888c..118b0b52b2 100644
--- a/guides/source/action_cable_overview.md
+++ b/guides/source/action_cable_overview.md
@@ -242,10 +242,10 @@ WebNotificationsChannel.broadcast_to(
The `WebNotificationsChannel.broadcast_to` call places a message in the current
subscription adapter (Redis by default)'s pubsub queue under a separate
broadcasting name for each user. For a user with an ID of 1, the broadcasting
-name would be `web_notifications_1`.
+name would be `web_notifications:1`.
The channel has been instructed to stream everything that arrives at
-`web_notifications_1` directly to the client by invoking the `received`
+`web_notifications:1` directly to the client by invoking the `received`
callback.
### Subscriptions
@@ -313,7 +313,7 @@ App.cable.subscriptions.create { channel: "ChatChannel", room: "Best Room" },
```ruby
# Somewhere in your app this is called, perhaps
# from a NewCommentJob.
-ChatChannel.broadcast_to(
+ActionCable.server.broadcast(
"chat_#{room}",
sent_by: 'Paul',
body: 'This is a cool chat app.'
diff --git a/guides/source/active_model_basics.md b/guides/source/active_model_basics.md
index e834aeadb1..732e553c62 100644
--- a/guides/source/active_model_basics.md
+++ b/guides/source/active_model_basics.md
@@ -416,7 +416,6 @@ the Active Model API.
```ruby
class Person
include ActiveModel::Model
-
end
```
@@ -467,7 +466,7 @@ In order to make this work, the model must have an accessor named `password_dige
The `has_secure_password` will add the following validations on the `password` accessor:
1. Password should be present.
-2. Password should be equal to its confirmation.
+2. Password should be equal to its confirmation (provided +password_confirmation+ is passed along).
3. The maximum length of a password is 72 (required by `bcrypt` on which ActiveModel::SecurePassword depends)
#### Examples
@@ -493,6 +492,10 @@ person.valid? # => false
person.password = person.password_confirmation = 'a' * 100
person.valid? # => false
+# When only password is supplied with no password_confirmation.
+person.password = 'aditya'
+person.valid? # => true
+
# When all validations are passed.
person.password = person.password_confirmation = 'aditya'
person.valid? # => true
diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md
index 8ffd0d033d..6f941d0e4e 100644
--- a/guides/source/active_record_querying.md
+++ b/guides/source/active_record_querying.md
@@ -1251,8 +1251,9 @@ articles, all the articles would still be loaded. By using `joins` (an INNER
JOIN), the join conditions **must** match, otherwise no records will be
returned.
-
-
+NOTE: If an association is eager loaded as part of a join, any fields from a custom select clause will not present be on the loaded models.
+This is because it is ambiguous whether they should appear on the parent record, or the child.
+
Scopes
------
diff --git a/guides/source/caching_with_rails.md b/guides/source/caching_with_rails.md
index cc84ecb216..a1b0029c47 100644
--- a/guides/source/caching_with_rails.md
+++ b/guides/source/caching_with_rails.md
@@ -512,6 +512,30 @@ class ProductsController < ApplicationController
end
```
+Sometimes we want to cache response, for example a static page, that never gets
+expired. To achieve this, we can use `http_cache_forever` helper and by doing
+so browser and proxies will cache it indefinitely.
+
+By default cached responses will be private, cached only on the user's web
+browser. To allow proxies to cache the response, set `public: true` to indicate
+that they can serve the cached response to all users.
+
+Using this helper, `last_modified` header is set to `Time.new(2011, 1, 1).utc`
+and `expires` header is set to a 100 years.
+
+WARNING: Use this method carefully as browser/proxy won't be able to invalidate
+the cached response unless browser cache is forcefully cleared.
+
+```ruby
+class HomeController < ApplicationController
+ def index
+ http_cache_forever(public: true) do
+ render
+ end
+ end
+end
+```
+
### Strong v/s Weak ETags
Rails generates weak ETags by default. Weak ETags allow semantically equivalent
diff --git a/guides/source/configuring.md b/guides/source/configuring.md
index 572993a36b..7239105b29 100644
--- a/guides/source/configuring.md
+++ b/guides/source/configuring.md
@@ -402,6 +402,22 @@ The schema dumper adds one additional configuration option:
* `config.action_controller.always_permitted_parameters` sets a list of whitelisted parameters that are permitted by default. The default values are `['controller', 'action']`.
+* `config.action_controller.enable_fragment_cache_logging` determines whether to log fragment cache reads and writes in verbose format as follows:
+
+ ```
+ Read fragment views/v1/2914079/v1/2914079/recordings/70182313-20160225015037000000/d0bdf2974e1ef6d31685c3b392ad0b74 (0.6ms)
+ Rendered messages/_message.html.erb in 1.2 ms [cache hit]
+ Write fragment views/v1/2914079/v1/2914079/recordings/70182313-20160225015037000000/3b4e249ac9d168c617e32e84b99218b5 (1.1ms)
+ Rendered recordings/threads/_thread.html.erb in 1.5 ms [cache miss]
+ ```
+
+ By default it is set to `false` which results in following output:
+
+ ```
+ Rendered messages/_message.html.erb in 1.2 ms [cache hit]
+ Rendered recordings/threads/_thread.html.erb in 1.5 ms [cache miss]
+ ```
+
### Configuring Action Dispatch
* `config.action_dispatch.session_store` sets the name of the store for session data. The default is `:cookie_store`; other valid options include `:active_record_store`, `:mem_cache_store` or the name of your own custom class.
@@ -455,6 +471,8 @@ encrypted cookies salt value. Defaults to `'signed encrypted cookie'`.
'ActionDispatch::ParamsParser::ParseError' => :bad_request,
'ActionController::BadRequest' => :bad_request,
'ActionController::ParameterMissing' => :bad_request,
+ 'Rack::QueryParser::ParameterTypeError' => :bad_request,
+ 'Rack::QueryParser::InvalidParameterError' => :bad_request,
'ActiveRecord::RecordNotFound' => :not_found,
'ActiveRecord::StaleObjectError' => :conflict,
'ActiveRecord::RecordInvalid' => :unprocessable_entity,
diff --git a/guides/source/debugging_rails_applications.md b/guides/source/debugging_rails_applications.md
index e4fc7f4743..df3003a6a8 100644
--- a/guides/source/debugging_rails_applications.md
+++ b/guides/source/debugging_rails_applications.md
@@ -946,6 +946,7 @@ development that will end your tailing of development.log. Have all information
about your Rails app requests in the browser — in the Developer Tools panel.
Provides insight to db/rendering/total times, parameter list, rendered views and
more.
+* [Pry](https://github.com/pry/pry) An IRB alternative and runtime developer console.
References
----------
diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md
index 89b1d3ca03..0cb5d81042 100644
--- a/guides/source/getting_started.md
+++ b/guides/source/getting_started.md
@@ -68,7 +68,7 @@ The Rails philosophy includes two major guiding principles:
again, our code is more maintainable, more extensible, and less buggy.
* **Convention Over Configuration:** Rails has opinions about the best way to do many
things in a web application, and defaults to this set of conventions, rather than
- require that you specify every minutiae through endless configuration files.
+ require that you specify minutiae through endless configuration files.
Creating a New Rails Project
----------------------------
diff --git a/guides/source/i18n.md b/guides/source/i18n.md
index 850f0def03..e623f8cf8a 100644
--- a/guides/source/i18n.md
+++ b/guides/source/i18n.md
@@ -866,7 +866,7 @@ This way you can provide special translations for various error messages at diff
#### Error Message Interpolation
-The translated model name, translated attribute name, and value are always available for interpolation.
+The translated model name, translated attribute name, and value are always available for interpolation as `model`, `attribute` and `value` respectively.
So, for example, instead of the default error message `"cannot be blank"` you could use the attribute name like this : `"Please fill in your %{attribute}"`.
diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md
index 2ac5a2188b..a8afa0ca6e 100644
--- a/guides/source/upgrading_ruby_on_rails.md
+++ b/guides/source/upgrading_ruby_on_rails.md
@@ -44,7 +44,7 @@ TIP: Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails. Ruby Enterp
### The Update Task
-Rails provides the `app:update` task (`rails:update` on 4.2 and earlier). After updating the Rails version
+Rails provides the `app:update` task (`rake rails:update` on 4.2 and earlier). After updating the Rails version
in the Gemfile, run this task.
This will help you with the creation of new files and changes of old files in an
interactive session.
@@ -94,6 +94,8 @@ class ApplicationRecord < ActiveRecord::Base
end
```
+Then make sure that all your models inherit from it.
+
### Halting Callback Chains via `throw(:abort)`
In Rails 4.2, when a 'before' callback returns `false` in Active Record
diff --git a/guides/w3c_validator.rb b/guides/w3c_validator.rb
index f56feeb696..2ce27e2e16 100644
--- a/guides/w3c_validator.rb
+++ b/guides/w3c_validator.rb
@@ -67,7 +67,7 @@ module RailsGuides
def select_only(guides)
prefixes = ENV["ONLY"].split(",").map(&:strip)
guides.select do |guide|
- prefixes.any? {|p| guide.start_with?("./output/#{p}")}
+ prefixes.any? { |p| guide.start_with?("./output/#{p}") }
end
end
diff --git a/railties/lib/rails/application/finisher.rb b/railties/lib/rails/application/finisher.rb
index 9f07f8fa02..a855e8fab0 100644
--- a/railties/lib/rails/application/finisher.rb
+++ b/railties/lib/rails/application/finisher.rb
@@ -125,7 +125,7 @@ module Rails
initializer :set_routes_reloader_hook do |app|
reloader = routes_reloader
reloader.execute_if_updated
- self.reloaders << reloader
+ reloaders << reloader
app.reloader.to_run do
# We configure #execute rather than #execute_if_updated because if
# autoloaded constants are cleared we need to reload routes also in
@@ -161,7 +161,7 @@ module Rails
if config.reload_classes_only_on_change
reloader = config.file_watcher.new(*watchable_args, &callback)
- self.reloaders << reloader
+ reloaders << reloader
# Prepend this callback to have autoloaded constants cleared before
# any other possible reloading, in case they need to autoload fresh
diff --git a/railties/lib/rails/code_statistics.rb b/railties/lib/rails/code_statistics.rb
index f7e1b5194c..b3d88147a5 100644
--- a/railties/lib/rails/code_statistics.rb
+++ b/railties/lib/rails/code_statistics.rb
@@ -9,7 +9,7 @@ class CodeStatistics #:nodoc:
"Job tests",
"Integration tests"]
- HEADERS = {lines: " Lines", code_lines: " LOC", classes: "Classes", methods: "Methods"}
+ HEADERS = { lines: " Lines", code_lines: " LOC", classes: "Classes", methods: "Methods" }
def initialize(*pairs)
@pairs = pairs
@@ -32,7 +32,7 @@ class CodeStatistics #:nodoc:
private
def calculate_statistics
- Hash[@pairs.map{|pair| [pair.first, calculate_directory_statistics(pair.last)]}]
+ Hash[@pairs.map { |pair| [pair.first, calculate_directory_statistics(pair.last)] }]
end
def calculate_directory_statistics(directory, pattern = /^(?!\.).*?\.(rb|js|coffee|rake)$/)
@@ -70,7 +70,7 @@ class CodeStatistics #:nodoc:
end
def width_for(label)
- [@statistics.values.sum {|s| s.send(label) }.to_s.size, HEADERS[label].length].max
+ [@statistics.values.sum { |s| s.send(label) }.to_s.size, HEADERS[label].length].max
end
def print_header
diff --git a/railties/lib/rails/code_statistics_calculator.rb b/railties/lib/rails/code_statistics_calculator.rb
index 63e40b631c..d0194af197 100644
--- a/railties/lib/rails/code_statistics_calculator.rb
+++ b/railties/lib/rails/code_statistics_calculator.rb
@@ -43,7 +43,7 @@ class CodeStatisticsCalculator #:nodoc:
def add_by_file_path(file_path)
File.open(file_path) do |f|
- self.add_by_io(f, file_type(file_path))
+ add_by_io(f, file_type(file_path))
end
end
diff --git a/railties/lib/rails/commands/commands_tasks.rb b/railties/lib/rails/commands/commands_tasks.rb
index 02f6472330..43f9dd38f3 100644
--- a/railties/lib/rails/commands/commands_tasks.rb
+++ b/railties/lib/rails/commands/commands_tasks.rb
@@ -1,4 +1,6 @@
require "rails/commands/rake_proxy"
+require "rails/commands/common_commands_tasks"
+require "active_support/core_ext/string/strip"
module Rails
# This is a class which takes in a rails command and initiates the appropriate
@@ -8,27 +10,10 @@ module Rails
# it before they are run.
class CommandsTasks # :nodoc:
include Rails::RakeProxy
+ include Rails::CommonCommandsTasks
attr_reader :argv
- HELP_MESSAGE = <<-EOT
-Usage: rails COMMAND [ARGS]
-
-The most common rails commands are:
- generate Generate new code (short-cut alias: "g")
- console Start the Rails console (short-cut alias: "c")
- server Start the Rails server (short-cut alias: "s")
- test Run tests (short-cut alias: "t")
- dbconsole Start a console for the database specified in config/database.yml
- (short-cut alias: "db")
- new Create a new Rails application. "rails new my_app" creates a
- new application called MyApp in "./my_app"
-
-All commands can be run with -h (or --help) for more information.
-
-In addition to those commands, there are:
-EOT
-
ADDITIONAL_COMMANDS = [
[ "destroy", 'Undo code generated with "generate" (short-cut alias: "d")' ],
[ "plugin new", "Generates skeleton for developing a Rails plugin" ],
@@ -36,34 +21,14 @@ EOT
'Run a piece of code in the application environment (short-cut alias: "r")' ]
]
- COMMAND_WHITELIST = %w(plugin generate destroy console server dbconsole runner new version help test)
-
def initialize(argv)
@argv = argv
end
- def run_command!(command)
- command = parse_command(command)
-
- if COMMAND_WHITELIST.include?(command)
- send(command)
- else
- run_rake_task(command)
- end
- end
-
def plugin
require_command!("plugin")
end
- def generate
- generate_or_destroy(:generate)
- end
-
- def destroy
- generate_or_destroy(:destroy)
- end
-
def console
require_command!("console")
options = Rails::Console.parse_arguments(argv)
@@ -91,10 +56,6 @@ EOT
end
end
- def test
- require_command!("test")
- end
-
def dbconsole
require_command!("dbconsole")
Rails::DBConsole.start
@@ -112,16 +73,6 @@ EOT
end
end
- def version
- argv.unshift "--version"
- require_command!("application")
- end
-
- def help
- write_help_message
- write_commands ADDITIONAL_COMMANDS + formatted_rake_tasks
- end
-
private
def exit_with_initialization_warning!
@@ -134,17 +85,6 @@ EOT
argv.shift if argv.first && argv.first[0] != "-"
end
- def require_command!(command)
- require "rails/commands/#{command}"
- end
-
- def generate_or_destroy(command)
- require "rails/generators"
- require_application_and_environment!
- Rails.application.load_generators
- require_command!(command)
- end
-
# Change to the application's path if there is no config.ru file in current directory.
# This allows us to run `rails server` from other directories, but still get
# the main config.ru and properly set the tmp directory.
@@ -152,29 +92,45 @@ EOT
Dir.chdir(File.expand_path("../../", APP_PATH)) unless File.exist?(File.expand_path("config.ru"))
end
+ def commands
+ ADDITIONAL_COMMANDS + formatted_rake_tasks
+ end
+
+ def command_whitelist
+ %w(plugin generate destroy console server dbconsole runner new version help test)
+ end
+
+ def help_message
+ <<-EOT.strip_heredoc
+ Usage: rails COMMAND [ARGS]
+
+ The most common rails commands are:
+ generate Generate new code (short-cut alias: "g")
+ console Start the Rails console (short-cut alias: "c")
+ server Start the Rails server (short-cut alias: "s")
+ test Run tests (short-cut alias: "t")
+ dbconsole Start a console for the database specified in config/database.yml
+ (short-cut alias: "db")
+ new Create a new Rails application. "rails new my_app" creates a
+ new application called MyApp in "./my_app"
+
+ All commands can be run with -h (or --help) for more information.
+
+ In addition to those commands, there are:
+ EOT
+ end
+
def require_application_and_environment!
require APP_PATH
Rails.application.require_environment!
end
- def write_help_message
- puts HELP_MESSAGE
- end
-
- def write_commands(commands)
- width = commands.map { |name, _| name.size }.max || 10
- commands.each { |command| printf(" %-#{width}s %s\n", *command) }
+ def load_tasks
+ Rails.application.load_tasks
end
- def parse_command(command)
- case command
- when "--version", "-v"
- "version"
- when "--help", "-h"
- "help"
- else
- command
- end
+ def load_generators
+ Rails.application.load_generators
end
end
end
diff --git a/railties/lib/rails/commands/common_commands_tasks.rb b/railties/lib/rails/commands/common_commands_tasks.rb
new file mode 100644
index 0000000000..c1484d7ae2
--- /dev/null
+++ b/railties/lib/rails/commands/common_commands_tasks.rb
@@ -0,0 +1,68 @@
+module Rails
+ module CommonCommandsTasks # :nodoc:
+ def run_command!(command)
+ command = parse_command(command)
+
+ if command_whitelist.include?(command)
+ send(command)
+ else
+ run_rake_task(command)
+ end
+ end
+
+ def generate
+ generate_or_destroy(:generate)
+ end
+
+ def destroy
+ generate_or_destroy(:destroy)
+ end
+
+ def test
+ require_command!("test")
+ end
+
+ def version
+ argv.unshift "--version"
+ require_command!("application")
+ end
+
+ def help
+ write_help_message
+ write_commands(commands)
+ end
+
+ private
+
+ def generate_or_destroy(command)
+ require "rails/generators"
+ require_application_and_environment!
+ load_generators
+ require_command!(command)
+ end
+
+ def require_command!(command)
+ require "rails/commands/#{command}"
+ end
+
+ def write_help_message
+ puts help_message
+ end
+
+ def write_commands(commands)
+ width = commands.map { |name, _| name.size }.max || 10
+ commands.each { |command| printf(" %-#{width}s %s\n", *command) }
+ end
+
+ def parse_command(command)
+ case command
+ when "--version", "-v"
+ "version"
+ when "--help", "-h"
+ "help"
+ else
+ command
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/commands/dbconsole.rb b/railties/lib/rails/commands/dbconsole.rb
index d79a88b025..66b7a14f16 100644
--- a/railties/lib/rails/commands/dbconsole.rb
+++ b/railties/lib/rails/commands/dbconsole.rb
@@ -152,7 +152,7 @@ module Rails
dirs_on_path = ENV["PATH"].to_s.split(File::PATH_SEPARATOR)
unless (ext = RbConfig::CONFIG["EXEEXT"]).empty?
- commands = commands.map{|cmd| "#{cmd}#{ext}"}
+ commands = commands.map { |cmd| "#{cmd}#{ext}" }
end
full_path_command = nil
diff --git a/railties/lib/rails/commands/plugin.rb b/railties/lib/rails/commands/plugin.rb
index 6404748fca..60653a2cee 100644
--- a/railties/lib/rails/commands/plugin.rb
+++ b/railties/lib/rails/commands/plugin.rb
@@ -3,12 +3,13 @@ if ARGV.first != "new"
else
ARGV.shift
unless ARGV.delete("--no-rc")
- customrc = ARGV.index{ |x| x.include?("--rc=") }
+ customrc = ARGV.index { |x| x.include?("--rc=") }
railsrc = if customrc
File.expand_path(ARGV.delete_at(customrc).gsub(/--rc=/, ""))
- else
- File.join(File.expand_path("~"), ".railsrc")
- end
+ else
+ File.join(File.expand_path("~"), ".railsrc")
+ end
+
if File.exist?(railsrc)
extra_args_string = File.read(railsrc)
extra_args = extra_args_string.split(/\n+/).flat_map(&:split)
diff --git a/railties/lib/rails/commands/rake_proxy.rb b/railties/lib/rails/commands/rake_proxy.rb
index ad5249ff48..f8da71831a 100644
--- a/railties/lib/rails/commands/rake_proxy.rb
+++ b/railties/lib/rails/commands/rake_proxy.rb
@@ -1,10 +1,11 @@
-require "rake"
require "active_support"
module Rails
module RakeProxy #:nodoc:
private
def run_rake_task(command)
+ require_rake
+
ARGV.unshift(command) # Prepend the command, so Rake knows how to run it.
Rake.application.standard_exception_handling do
@@ -15,6 +16,8 @@ module Rails
end
def rake_tasks
+ require_rake
+
return @rake_tasks if defined?(@rake_tasks)
ActiveSupport::Deprecation.silence do
@@ -23,12 +26,16 @@ module Rails
Rake::TaskManager.record_task_metadata = true
Rake.application.instance_variable_set(:@name, "rails")
- Rails.application.load_tasks
+ load_tasks
@rake_tasks = Rake.application.tasks.select(&:comment)
end
def formatted_rake_tasks
rake_tasks.map { |t| [ t.name_with_args, t.comment ] }
end
+
+ def require_rake
+ require "rake" # Defer booting Rake until we know it's needed.
+ end
end
end
diff --git a/railties/lib/rails/commands/runner.rb b/railties/lib/rails/commands/runner.rb
index 11ef1d10e2..b74addf587 100644
--- a/railties/lib/rails/commands/runner.rb
+++ b/railties/lib/rails/commands/runner.rb
@@ -61,9 +61,11 @@ elsif File.exist?(code_or_file)
else
begin
eval(code_or_file, binding, __FILE__, __LINE__)
- rescue SyntaxError, NameError
+ rescue SyntaxError, NameError => e
$stderr.puts "Please specify a valid ruby command or the path of a script to run."
$stderr.puts "Run '#{command} -h' for help."
+ $stderr.puts
+ $stderr.puts e
exit 1
end
end
diff --git a/railties/lib/rails/commands/server.rb b/railties/lib/rails/commands/server.rb
index bf8ae0a5ee..0339849bfe 100644
--- a/railties/lib/rails/commands/server.rb
+++ b/railties/lib/rails/commands/server.rb
@@ -88,7 +88,8 @@ module Rails
end
def default_options
- super.merge( Port: ENV.fetch("PORT", 3000).to_i,
+ super.merge(
+ Port: ENV.fetch("PORT", 3000).to_i,
Host: ENV.fetch("HOST", "localhost").dup,
DoNotReverseLookup: true,
environment: (ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development").dup,
diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb
index bcd1a66921..86d66afddb 100644
--- a/railties/lib/rails/engine.rb
+++ b/railties/lib/rails/engine.rb
@@ -402,7 +402,7 @@ module Rails
end
unless mod.respond_to?(:railtie_routes_url_helpers)
- define_method(:railtie_routes_url_helpers) {|include_path_helpers = true| railtie.routes.url_helpers(include_path_helpers) }
+ define_method(:railtie_routes_url_helpers) { |include_path_helpers = true| railtie.routes.url_helpers(include_path_helpers) }
end
end
end
@@ -590,8 +590,8 @@ module Rails
initializer :add_view_paths do
views = paths["app/views"].existent
unless views.empty?
- ActiveSupport.on_load(:action_controller){ prepend_view_path(views) if respond_to?(:prepend_view_path) }
- ActiveSupport.on_load(:action_mailer){ prepend_view_path(views) }
+ ActiveSupport.on_load(:action_controller) { prepend_view_path(views) if respond_to?(:prepend_view_path) }
+ ActiveSupport.on_load(:action_mailer) { prepend_view_path(views) }
end
end
@@ -619,7 +619,7 @@ module Rails
end
rake_tasks do
- next if self.is_a?(Rails::Application)
+ next if is_a?(Rails::Application)
next unless has_migrations?
namespace railtie_name do
diff --git a/railties/lib/rails/engine/commands_tasks.rb b/railties/lib/rails/engine/commands_tasks.rb
index ac0861328b..d6effdb732 100644
--- a/railties/lib/rails/engine/commands_tasks.rb
+++ b/railties/lib/rails/engine/commands_tasks.rb
@@ -1,116 +1,62 @@
require "rails/commands/rake_proxy"
+require "rails/commands/common_commands_tasks"
+require "active_support/core_ext/string/strip"
module Rails
class Engine
class CommandsTasks # :nodoc:
include Rails::RakeProxy
+ include Rails::CommonCommandsTasks
attr_reader :argv
- HELP_MESSAGE = <<-EOT
-Usage: rails COMMAND [ARGS]
-
-The common Rails commands available for engines are:
- generate Generate new code (short-cut alias: "g")
- destroy Undo code generated with "generate" (short-cut alias: "d")
- test Run tests (short-cut alias: "t")
-
-All commands can be run with -h for more information.
-
-If you want to run any commands that need to be run in context
-of the application, like `rails server` or `rails console`,
-you should do it from application's directory (typically test/dummy).
-
-In addition to those commands, there are:
- EOT
-
- COMMAND_WHITELIST = %w(generate destroy version help test)
-
def initialize(argv)
@argv = argv
end
- def run_command!(command)
- command = parse_command(command)
+ private
- if COMMAND_WHITELIST.include?(command)
- send(command)
- else
- run_rake_task(command)
+ def commands
+ formatted_rake_tasks
end
- end
- def generate
- generate_or_destroy(:generate)
- end
+ def command_whitelist
+ %w(generate destroy version help test)
+ end
- def destroy
- generate_or_destroy(:destroy)
- end
+ def help_message
+ <<-EOT.strip_heredoc
+ Usage: rails COMMAND [ARGS]
- def test
- require_command!("test")
- end
+ The common Rails commands available for engines are:
+ generate Generate new code (short-cut alias: "g")
+ destroy Undo code generated with "generate" (short-cut alias: "d")
+ test Run tests (short-cut alias: "t")
- def version
- argv.unshift "--version"
- require_command!("application")
- end
+ All commands can be run with -h for more information.
- def help
- write_help_message
- write_commands(formatted_rake_tasks)
- end
+ If you want to run any commands that need to be run in context
+ of the application, like `rails server` or `rails console`,
+ you should do it from application's directory (typically test/dummy).
- private
+ In addition to those commands, there are:
+ EOT
+ end
- def require_command!(command)
- require "rails/commands/#{command}"
+ def require_application_and_environment!
+ require ENGINE_PATH
end
- def generate_or_destroy(command)
- load_generators
- require_command!(command)
+ def load_tasks
+ Rake.application.init("rails")
+ Rake.application.load_rakefile
end
def load_generators
- require "rails/generators"
- require ENGINE_PATH
-
engine = ::Rails::Engine.find(ENGINE_ROOT)
Rails::Generators.namespace = engine.railtie_namespace
engine.load_generators
end
-
- def write_help_message
- puts HELP_MESSAGE
- end
-
- def write_commands(commands)
- width = commands.map { |name, _| name.size }.max || 10
- commands.each { |command| printf(" %-#{width}s %s\n", *command) }
- end
-
- def parse_command(command)
- case command
- when "--version", "-v"
- "version"
- when "--help", "-h"
- "help"
- else
- command
- end
- end
-
- def rake_tasks
- return @rake_tasks if defined?(@rake_tasks)
-
- load_generators
- Rake::TaskManager.record_task_metadata = true
- Rake.application.init("rails")
- Rake.application.load_rakefile
- @rake_tasks = Rake.application.tasks.select(&:comment)
- end
end
end
end
diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb
index 708c0b11d6..6a112fc710 100644
--- a/railties/lib/rails/generators.rb
+++ b/railties/lib/rails/generators.rb
@@ -180,9 +180,9 @@ module Rails
klass.start(args, config)
else
options = sorted_groups.flat_map(&:last)
- suggestions = options.sort_by {|suggested| levenshtein_distance(namespace.to_s, suggested) }.first(3)
+ suggestions = options.sort_by { |suggested| levenshtein_distance(namespace.to_s, suggested) }.first(3)
msg = "Could not find generator '#{namespace}'. "
- msg << "Maybe you meant #{ suggestions.map {|s| "'#{s}'"}.to_sentence(last_word_connector: " or ", locale: :en) }\n"
+ msg << "Maybe you meant #{ suggestions.map { |s| "'#{s}'" }.to_sentence(last_word_connector: " or ", locale: :en) }\n"
msg << "Run `rails generate --help` for more options."
puts msg
end
diff --git a/railties/lib/rails/generators/actions.rb b/railties/lib/rails/generators/actions.rb
index 2959ae3169..ab9dc019e2 100644
--- a/railties/lib/rails/generators/actions.rb
+++ b/railties/lib/rails/generators/actions.rb
@@ -274,7 +274,6 @@ module Rails
end
end
-
# Runs the supplied command using either "rake ..." or "rails ..."
# based on the executor parameter provided.
def execute_command(executor, command, options={})
diff --git a/railties/lib/rails/generators/base.rb b/railties/lib/rails/generators/base.rb
index 60ef2d50ef..c0e34c20e7 100644
--- a/railties/lib/rails/generators/base.rb
+++ b/railties/lib/rails/generators/base.rb
@@ -48,7 +48,7 @@ module Rails
# Convenience method to hide this generator from the available ones when
# running rails generator command.
def self.hide!
- Rails::Generators.hide_namespace self.namespace
+ Rails::Generators.hide_namespace(namespace)
end
# Invoke a generator based on the value supplied by the user to the
@@ -168,7 +168,7 @@ module Rails
names.each do |name|
unless class_options.key?(name)
defaults = if options[:type] == :boolean
- { }
+ {}
elsif [true, false].include?(default_value_for_option(name, options))
{ banner: "" }
else
@@ -273,7 +273,7 @@ module Rails
# Use Rails default banner.
def self.banner
- "rails generate #{namespace.sub(/^rails:/,'')} #{self.arguments.map(&:usage).join(' ')} [options]".gsub(/\s+/, " ")
+ "rails generate #{namespace.sub(/^rails:/,'')} #{arguments.map(&:usage).join(' ')} [options]".gsub(/\s+/, " ")
end
# Sets the base_name taking into account the current class namespace.
diff --git a/railties/lib/rails/generators/generated_attribute.rb b/railties/lib/rails/generators/generated_attribute.rb
index 58ffdcc464..61181b7b97 100644
--- a/railties/lib/rails/generators/generated_attribute.rb
+++ b/railties/lib/rails/generators/generated_attribute.rb
@@ -127,11 +127,11 @@ module Rails
end
def polymorphic?
- self.attr_options[:polymorphic]
+ attr_options[:polymorphic]
end
def required?
- self.attr_options[:required]
+ attr_options[:required]
end
def has_index?
diff --git a/railties/lib/rails/generators/named_base.rb b/railties/lib/rails/generators/named_base.rb
index c799365ac8..c39ea24935 100644
--- a/railties/lib/rails/generators/named_base.rb
+++ b/railties/lib/rails/generators/named_base.rb
@@ -14,7 +14,7 @@ module Rails
# Unfreeze name in case it's given as a frozen string
args[0] = args[0].dup if args[0].is_a?(String) && args[0].frozen?
super
- assign_names!(self.name)
+ assign_names!(name)
parse_attributes! if respond_to?(:attributes)
end
@@ -51,7 +51,7 @@ module Rails
def indent(content, multiplier = 2)
spaces = " " * multiplier
- content.each_line.map {|line| line.blank? ? line : "#{spaces}#{line}" }.join
+ content.each_line.map { |line| line.blank? ? line : "#{spaces}#{line}" }.join
end
def wrap_with_namespace(content)
@@ -162,7 +162,7 @@ module Rails
end
def route_url
- @route_url ||= class_path.collect {|dname| "/" + dname }.join + "/" + plural_file_name
+ @route_url ||= class_path.collect { |dname| "/" + dname }.join + "/" + plural_file_name
end
def url_helper_prefix
diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb
index 2614bd85cf..9f9c50ca10 100644
--- a/railties/lib/rails/generators/rails/app/app_generator.rb
+++ b/railties/lib/rails/generators/rails/app/app_generator.rb
@@ -324,6 +324,8 @@ module Rails
remove_file "app/mailers/application_mailer.rb"
remove_file "app/views/layouts/mailer.html.erb"
remove_file "app/views/layouts/mailer.text.erb"
+ remove_dir "app/mailers"
+ remove_dir "test/mailers"
end
end
@@ -361,7 +363,7 @@ module Rails
protected
def self.banner
- "rails new #{self.arguments.map(&:usage).join(' ')} [options]"
+ "rails new #{arguments.map(&:usage).join(' ')} [options]"
end
# Define file as an alias to create_file for backwards compatibility.
@@ -478,7 +480,7 @@ module Rails
end
def railsrc(argv)
- if (customrc = argv.index{ |x| x.include?("--rc=") })
+ if (customrc = argv.index { |x| x.include?("--rc=") })
fname = File.expand_path(argv[customrc].gsub(/--rc=/, ""))
yield(argv.take(customrc) + argv.drop(customrc + 1), fname)
else
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
index f3ccf95045..511b4a82eb 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
@@ -18,7 +18,7 @@ Rails.application.configure do
config.cache_store = :memory_store
config.public_file_server.headers = {
- 'Cache-Control' => 'public, max-age=172800'
+ 'Cache-Control' => "public, max-age=#{2.days.seconds.to_i}"
}
else
config.action_controller.perform_caching = false
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt
index 42fee3b036..56416b3075 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt
@@ -15,7 +15,7 @@ Rails.application.configure do
# Configure public file server for tests with Cache-Control for performance.
config.public_file_server.enabled = true
config.public_file_server.headers = {
- 'Cache-Control' => 'public, max-age=3600'
+ 'Cache-Control' => "public, max-age=#{1.hour.seconds.to_i}"
}
# Show full error reports and disable caching.
diff --git a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb
index e24ece57ca..9ffeab4fbe 100644
--- a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb
+++ b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb
@@ -328,7 +328,7 @@ task default: :test
end
def self.banner
- "rails plugin new #{self.arguments.map(&:usage).join(' ')} [options]"
+ "rails plugin new #{arguments.map(&:usage).join(' ')} [options]"
end
def original_name
diff --git a/railties/lib/rails/generators/resource_helpers.rb b/railties/lib/rails/generators/resource_helpers.rb
index c7829869ef..6d80003271 100644
--- a/railties/lib/rails/generators/resource_helpers.rb
+++ b/railties/lib/rails/generators/resource_helpers.rb
@@ -17,7 +17,7 @@ module Rails
controller_name = name
if options[:model_name]
self.name = options[:model_name]
- assign_names!(self.name)
+ assign_names!(name)
end
assign_controller_names!(controller_name.pluralize)
diff --git a/railties/lib/rails/generators/testing/behaviour.rb b/railties/lib/rails/generators/testing/behaviour.rb
index fc91482d3b..a1e5a233b9 100644
--- a/railties/lib/rails/generators/testing/behaviour.rb
+++ b/railties/lib/rails/generators/testing/behaviour.rb
@@ -62,16 +62,16 @@ module Rails
#
# You can provide a configuration hash as second argument. This method returns the output
# printed by the generator.
- def run_generator(args=self.default_arguments, config={})
+ def run_generator(args = default_arguments, config = {})
capture(:stdout) do
args += ["--skip-bundle"] unless args.include? "--dev"
- self.generator_class.start(args, config.reverse_merge(destination_root: destination_root))
+ generator_class.start(args, config.reverse_merge(destination_root: destination_root))
end
end
# Instantiate the generator.
- def generator(args=self.default_arguments, options={}, config={})
- @generator ||= self.generator_class.new(args, options, config.reverse_merge(destination_root: destination_root))
+ def generator(args = default_arguments, options = {}, config = {})
+ @generator ||= generator_class.new(args, options, config.reverse_merge(destination_root: destination_root))
end
# Create a Rails::Generators::GeneratedAttribute by supplying the
diff --git a/railties/lib/rails/info.rb b/railties/lib/rails/info.rb
index d69cbbc001..5d4acd6f6b 100644
--- a/railties/lib/rails/info.rb
+++ b/railties/lib/rails/info.rb
@@ -43,9 +43,9 @@ module Rails
table << %(<tr><td class="name">#{CGI.escapeHTML(name.to_s)}</td>)
formatted_value = if value.kind_of?(Array)
"<ul>" + value.map { |v| "<li>#{CGI.escapeHTML(v.to_s)}</li>" }.join + "</ul>"
- else
- CGI.escapeHTML(value.to_s)
- end
+ else
+ CGI.escapeHTML(value.to_s)
+ end
table << %(<td class="value">#{formatted_value}</td></tr>)
end
table << "</table>"
diff --git a/railties/lib/rails/info_controller.rb b/railties/lib/rails/info_controller.rb
index f5aa074703..8b553aea79 100644
--- a/railties/lib/rails/info_controller.rb
+++ b/railties/lib/rails/info_controller.rb
@@ -21,8 +21,8 @@ class Rails::InfoController < Rails::ApplicationController # :nodoc:
path = URI.parser.escape path
normalized_path = with_leading_slash path
render json: {
- exact: match_route {|it| it.match normalized_path },
- fuzzy: match_route {|it| it.spec.to_s.match path }
+ exact: match_route { |it| it.match normalized_path },
+ fuzzy: match_route { |it| it.spec.to_s.match path }
}
else
@routes_inspector = ActionDispatch::Routing::RoutesInspector.new(_routes.routes)
@@ -33,9 +33,9 @@ class Rails::InfoController < Rails::ApplicationController # :nodoc:
private
def match_route
- _routes.routes.select {|route|
+ _routes.routes.select { |route|
yield route.path
- }.map {|route| route.path.spec.to_s }
+ }.map { |route| route.path.spec.to_s }
end
def with_leading_slash(path)
diff --git a/railties/lib/rails/mailers_controller.rb b/railties/lib/rails/mailers_controller.rb
index 66073899c2..95de998208 100644
--- a/railties/lib/rails/mailers_controller.rb
+++ b/railties/lib/rails/mailers_controller.rb
@@ -47,8 +47,8 @@ class Rails::MailersController < Rails::ApplicationController # :nodoc:
def find_preview
candidates = []
- params[:path].to_s.scan(%r{/|$}){ candidates << $` }
- preview = candidates.detect{ |candidate| ActionMailer::Preview.exists?(candidate) }
+ params[:path].to_s.scan(%r{/|$}) { candidates << $` }
+ preview = candidates.detect { |candidate| ActionMailer::Preview.exists?(candidate) }
if preview
@preview = ActionMailer::Preview.find(preview)
@@ -64,7 +64,7 @@ class Rails::MailersController < Rails::ApplicationController # :nodoc:
end
end
- if formats.any?{ |f| @email.mime_type == f }
+ if formats.any? { |f| @email.mime_type == f }
@email
end
end
diff --git a/railties/lib/rails/railtie/configurable.rb b/railties/lib/rails/railtie/configurable.rb
index d6040785a0..39f1f87575 100644
--- a/railties/lib/rails/railtie/configurable.rb
+++ b/railties/lib/rails/railtie/configurable.rb
@@ -9,7 +9,7 @@ module Rails
delegate :config, to: :instance
def inherited(base)
- raise "You cannot inherit from a #{self.superclass.name} child"
+ raise "You cannot inherit from a #{superclass.name} child"
end
def instance
diff --git a/railties/lib/rails/tasks/routes.rake b/railties/lib/rails/tasks/routes.rake
index 634b645d40..f5e5b9ae87 100644
--- a/railties/lib/rails/tasks/routes.rake
+++ b/railties/lib/rails/tasks/routes.rake
@@ -7,7 +7,7 @@ task routes: :environment do
all_routes = Rails.application.routes.routes
require "action_dispatch/routing/inspector"
inspector = ActionDispatch::Routing::RoutesInspector.new(all_routes)
- if ARGV.any?{ |argv| argv.start_with? "CONTROLLER" }
+ if ARGV.any? { |argv| argv.start_with? "CONTROLLER" }
puts <<-eow.strip_heredoc
Passing `CONTROLLER` to `bin/rails routes` is deprecated and will be removed in Rails 5.1.
Please use `bin/rails routes -c controller_name` instead.
diff --git a/railties/lib/rails/test_unit/reporter.rb b/railties/lib/rails/test_unit/reporter.rb
index afcdd2e9fd..fe11664d5e 100644
--- a/railties/lib/rails/test_unit/reporter.rb
+++ b/railties/lib/rails/test_unit/reporter.rb
@@ -68,7 +68,7 @@ module Rails
def format_rerun_snippet(result)
location, line = result.method(result.name).source_location
- "#{self.executable} #{relative_path_for(location)}:#{line}"
+ "#{executable} #{relative_path_for(location)}:#{line}"
end
def app_root
diff --git a/railties/lib/rails/test_unit/testing.rake b/railties/lib/rails/test_unit/testing.rake
index 91ff7f4be7..4c157c1262 100644
--- a/railties/lib/rails/test_unit/testing.rake
+++ b/railties/lib/rails/test_unit/testing.rake
@@ -9,9 +9,9 @@ task :test do
$: << "test"
pattern = if ENV.key?("TEST")
ENV["TEST"]
- else
- "test"
- end
+ else
+ "test"
+ end
Minitest.rake_run([pattern])
end
diff --git a/railties/test/application/asset_debugging_test.rb b/railties/test/application/asset_debugging_test.rb
index ccecf2c09e..a732869d62 100644
--- a/railties/test/application/asset_debugging_test.rb
+++ b/railties/test/application/asset_debugging_test.rb
@@ -42,7 +42,7 @@ module ApplicationTests
test "assets are concatenated when debug is off and compile is off either if debug_assets param is provided" do
# config.assets.debug and config.assets.compile are false for production environment
ENV["RAILS_ENV"] = "production"
- output = Dir.chdir(app_path){ `bin/rails assets:precompile --trace 2>&1` }
+ output = Dir.chdir(app_path) { `bin/rails assets:precompile --trace 2>&1` }
assert $?.success?, output
# Load app env
diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb
index ee482009d8..5dceaae96b 100644
--- a/railties/test/application/configuration_test.rb
+++ b/railties/test/application/configuration_test.rb
@@ -666,7 +666,6 @@ module ApplicationTests
end
RUBY
-
app_file "app/controllers/posts_controller.rb", <<-RUBY
class PostsController < ApplicationController
def index
@@ -1044,7 +1043,7 @@ module ApplicationTests
app "development"
- post "/posts", post: {"title" =>"zomg"}
+ post "/posts", post: { "title" =>"zomg" }
assert_equal "permitted", last_response.body
end
@@ -1068,7 +1067,7 @@ module ApplicationTests
assert_equal :raise, ActionController::Parameters.action_on_unpermitted_parameters
- post "/posts", post: {"title" =>"zomg"}
+ post "/posts", post: { "title" =>"zomg" }
assert_match "We're sorry, but something went wrong", last_response.body
end
@@ -1108,7 +1107,7 @@ module ApplicationTests
assert_equal :raise, ActionController::Parameters.action_on_unpermitted_parameters
- post "/posts", post: {"title" =>"zomg"}, format: "json"
+ post "/posts", post: { "title" =>"zomg" }, format: "json"
assert_equal 200, last_response.status
end
diff --git a/railties/test/application/generators_test.rb b/railties/test/application/generators_test.rb
index 0d7ccb2278..d4008fe677 100644
--- a/railties/test/application/generators_test.rb
+++ b/railties/test/application/generators_test.rb
@@ -29,7 +29,7 @@ module ApplicationTests
end
test "allow running plugin new generator inside Rails app directory" do
- FileUtils.cd(rails_root){ `ruby bin/rails plugin new vendor/plugins/bukkits` }
+ FileUtils.cd(rails_root) { `ruby bin/rails plugin new vendor/plugins/bukkits` }
assert File.exist?(File.join(rails_root, "vendor/plugins/bukkits/test/dummy/config/application.rb"))
end
@@ -165,7 +165,7 @@ module ApplicationTests
config.api_only = true
RUBY
- FileUtils.cd(rails_root){ `bin/rails generate mailer notifier foo` }
+ FileUtils.cd(rails_root) { `bin/rails generate mailer notifier foo` }
assert File.exist?(File.join(rails_root, "app/views/notifier_mailer/foo.text.erb"))
assert File.exist?(File.join(rails_root, "app/views/notifier_mailer/foo.html.erb"))
end
diff --git a/railties/test/application/loading_test.rb b/railties/test/application/loading_test.rb
index d57384d256..38f96f3ab9 100644
--- a/railties/test/application/loading_test.rb
+++ b/railties/test/application/loading_test.rb
@@ -298,7 +298,7 @@ class LoadingTest < ActiveSupport::TestCase
end
MIGRATION
- Dir.chdir(app_path) { `rake db:migrate`}
+ Dir.chdir(app_path) { `rake db:migrate` }
require "#{rails_root}/config/environment"
get "/title"
diff --git a/railties/test/application/middleware/cache_test.rb b/railties/test/application/middleware/cache_test.rb
index be44aa774f..cd1371359a 100644
--- a/railties/test/application/middleware/cache_test.rb
+++ b/railties/test/application/middleware/cache_test.rb
@@ -137,7 +137,7 @@ module ApplicationTests
body = last_response.body
etag = last_response.headers["ETag"]
- get "/expires/expires_etag", {private: true}, "If-None-Match" => etag
+ get "/expires/expires_etag", { private: true }, "If-None-Match" => etag
assert_equal "miss", last_response.headers["X-Rack-Cache"]
assert_not_equal body, last_response.body
end
@@ -171,7 +171,7 @@ module ApplicationTests
body = last_response.body
last = last_response.headers["Last-Modified"]
- get "/expires/expires_last_modified", {private: true}, "If-Modified-Since" => last
+ get "/expires/expires_last_modified", { private: true }, "If-Modified-Since" => last
assert_equal "miss", last_response.headers["X-Rack-Cache"]
assert_not_equal body, last_response.body
end
diff --git a/railties/test/application/middleware_test.rb b/railties/test/application/middleware_test.rb
index 3b48ada190..1cc931b29e 100644
--- a/railties/test/application/middleware_test.rb
+++ b/railties/test/application/middleware_test.rb
@@ -103,7 +103,7 @@ module ApplicationTests
add_to_config "config.ssl_options = { host: 'example.com' }"
boot!
- assert_equal [{host: "example.com"}], Rails.application.middleware.first.args
+ assert_equal [{ host: "example.com" }], Rails.application.middleware.first.args
end
test "removing Active Record omits its middleware" do
diff --git a/railties/test/application/rake/migrations_test.rb b/railties/test/application/rake/migrations_test.rb
index d608fa1976..76cb302c62 100644
--- a/railties/test/application/rake/migrations_test.rb
+++ b/railties/test/application/rake/migrations_test.rb
@@ -57,7 +57,7 @@ module ApplicationTests
end
test "migration status when schema migrations table is not present" do
- output = Dir.chdir(app_path){ `bin/rails db:migrate:status 2>&1` }
+ output = Dir.chdir(app_path) { `bin/rails db:migrate:status 2>&1` }
assert_equal "Schema migrations table does not exist yet.\n", output
end
diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb
index 5bb97a593d..5fd5507453 100644
--- a/railties/test/application/rake_test.rb
+++ b/railties/test/application/rake_test.rb
@@ -54,7 +54,7 @@ module ApplicationTests
Rails.application.initialize!
RUBY
- assert_match("SuperMiddleware", Dir.chdir(app_path){ `bin/rails middleware` })
+ assert_match("SuperMiddleware", Dir.chdir(app_path) { `bin/rails middleware` })
end
def test_initializers_are_executed_in_rake_tasks
@@ -69,7 +69,7 @@ module ApplicationTests
end
RUBY
- output = Dir.chdir(app_path){ `bin/rails do_nothing` }
+ output = Dir.chdir(app_path) { `bin/rails do_nothing` }
assert_match "Doing something...", output
end
@@ -128,7 +128,7 @@ module ApplicationTests
end
RUBY
- output = Dir.chdir(app_path){ `bin/rails routes` }
+ output = Dir.chdir(app_path) { `bin/rails routes` }
assert_equal "Prefix Verb URI Pattern Controller#Action\n cart GET /cart(.:format) cart#show\n", output
end
@@ -140,13 +140,13 @@ module ApplicationTests
end
RUBY
- output = Dir.chdir(app_path){ `bin/rails routes CONTROLLER=cart` }
+ output = Dir.chdir(app_path) { `bin/rails routes CONTROLLER=cart` }
assert_equal ["Passing `CONTROLLER` to `bin/rails routes` is deprecated and will be removed in Rails 5.1.",
"Please use `bin/rails routes -c controller_name` instead.",
"Prefix Verb URI Pattern Controller#Action",
" cart GET /cart(.:format) cart#show\n"].join("\n"), output
- output = Dir.chdir(app_path){ `bin/rails routes -c cart` }
+ output = Dir.chdir(app_path) { `bin/rails routes -c cart` }
assert_equal "Prefix Verb URI Pattern Controller#Action\n cart GET /cart(.:format) cart#show\n", output
end
@@ -167,10 +167,10 @@ module ApplicationTests
" PUT /admin/post(.:format) admin/posts#update",
" DELETE /admin/post(.:format) admin/posts#destroy\n"].join("\n")
- output = Dir.chdir(app_path){ `bin/rails routes -c Admin::PostController` }
+ output = Dir.chdir(app_path) { `bin/rails routes -c Admin::PostController` }
assert_equal expected_output, output
- output = Dir.chdir(app_path){ `bin/rails routes -c PostController` }
+ output = Dir.chdir(app_path) { `bin/rails routes -c PostController` }
assert_equal expected_output, output
end
@@ -183,13 +183,13 @@ module ApplicationTests
end
RUBY
- output = Dir.chdir(app_path){ `bin/rails routes -g show` }
+ output = Dir.chdir(app_path) { `bin/rails routes -g show` }
assert_equal "Prefix Verb URI Pattern Controller#Action\n cart GET /cart(.:format) cart#show\n", output
- output = Dir.chdir(app_path){ `bin/rails routes -g POST` }
+ output = Dir.chdir(app_path) { `bin/rails routes -g POST` }
assert_equal "Prefix Verb URI Pattern Controller#Action\n POST /cart(.:format) cart#create\n", output
- output = Dir.chdir(app_path){ `bin/rails routes -g basketballs` }
+ output = Dir.chdir(app_path) { `bin/rails routes -g basketballs` }
assert_equal " Prefix Verb URI Pattern Controller#Action\n" \
"basketballs GET /basketballs(.:format) basketball#index\n", output
end
@@ -202,13 +202,13 @@ module ApplicationTests
end
RUBY
- output = Dir.chdir(app_path){ `bin/rails routes -c cart` }
+ output = Dir.chdir(app_path) { `bin/rails routes -c cart` }
assert_equal "Prefix Verb URI Pattern Controller#Action\n cart GET /cart(.:format) cart#show\n", output
- output = Dir.chdir(app_path){ `bin/rails routes -c Cart` }
+ output = Dir.chdir(app_path) { `bin/rails routes -c Cart` }
assert_equal "Prefix Verb URI Pattern Controller#Action\n cart GET /cart(.:format) cart#show\n", output
- output = Dir.chdir(app_path){ `bin/rails routes -c CartController` }
+ output = Dir.chdir(app_path) { `bin/rails routes -c CartController` }
assert_equal "Prefix Verb URI Pattern Controller#Action\n cart GET /cart(.:format) cart#show\n", output
end
@@ -218,7 +218,7 @@ module ApplicationTests
end
RUBY
- assert_equal <<-MESSAGE.strip_heredoc, Dir.chdir(app_path){ `bin/rails routes` }
+ assert_equal <<-MESSAGE.strip_heredoc, Dir.chdir(app_path) { `bin/rails routes` }
You don't have any routes defined!
Please add some routes in config/routes.rb.
@@ -234,7 +234,7 @@ module ApplicationTests
end
RUBY
- output = Dir.chdir(app_path){ `bin/rake --rakefile Rakefile routes` }
+ output = Dir.chdir(app_path) { `bin/rake --rakefile Rakefile routes` }
assert_equal "Prefix Verb URI Pattern Controller#Action\n cart GET /cart(.:format) cart#show\n", output
end
@@ -247,7 +247,7 @@ module ApplicationTests
end
RUBY
- output = Dir.chdir(app_path){ `bin/rails log_something RAILS_ENV=production && cat log/production.log` }
+ output = Dir.chdir(app_path) { `bin/rails log_something RAILS_ENV=production && cat log/production.log` }
assert_match "Sample log message", output
end
diff --git a/railties/test/application/routing_test.rb b/railties/test/application/routing_test.rb
index c70af162ae..c86759de5a 100644
--- a/railties/test/application/routing_test.rb
+++ b/railties/test/application/routing_test.rb
@@ -263,7 +263,7 @@ module ApplicationTests
assert_equal "WIN", last_response.body
end
- {"development" => "baz", "production" => "bar"}.each do |mode, expected|
+ { "development" => "baz", "production" => "bar" }.each do |mode, expected|
test "reloads routes when configuration is changed in #{mode}" do
controller :foo, <<-RUBY
class FooController < ApplicationController
diff --git a/railties/test/application/runner_test.rb b/railties/test/application/runner_test.rb
index 1c4aa1d4c4..4dc766dfda 100644
--- a/railties/test/application/runner_test.rb
+++ b/railties/test/application/runner_test.rb
@@ -74,13 +74,15 @@ module ApplicationTests
end
def test_runner_detects_syntax_errors
- Dir.chdir(app_path) { `bin/rails runner "puts 'hello world" 2>&1` }
- refute $?.success?
+ output = Dir.chdir(app_path) { `bin/rails runner "puts 'hello world" 2>&1` }
+ assert_not $?.success?
+ assert_match "unterminated string meets end of file", output
end
def test_runner_detects_bad_script_name
- Dir.chdir(app_path) { `bin/rails runner "iuiqwiourowe" 2>&1` }
- refute $?.success?
+ output = Dir.chdir(app_path) { `bin/rails runner "iuiqwiourowe" 2>&1` }
+ assert_not $?.success?
+ assert_match "undefined local variable or method `iuiqwiourowe' for main:Object", output
end
def test_environment_with_rails_env
diff --git a/railties/test/commands/console_test.rb b/railties/test/commands/console_test.rb
index b3343d9b7f..96ac7c0661 100644
--- a/railties/test/commands/console_test.rb
+++ b/railties/test/commands/console_test.rb
@@ -40,7 +40,6 @@ class Rails::ConsoleTest < ActiveSupport::TestCase
def test_start_with_sandbox
start ["--sandbox"]
-
assert app.console.started?
assert app.sandbox
assert_match(/Loading \w+ environment in sandbox \(Rails/, output)
diff --git a/railties/test/commands/dbconsole_test.rb b/railties/test/commands/dbconsole_test.rb
index 545460e933..286e7c16c1 100644
--- a/railties/test/commands/dbconsole_test.rb
+++ b/railties/test/commands/dbconsole_test.rb
@@ -9,7 +9,7 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase
def teardown
Rails::DBConsole.send(:remove_const, "APP_PATH")
- %w[PGUSER PGHOST PGPORT PGPASSWORD DATABASE_URL].each{|key| ENV.delete(key)}
+ %w[PGUSER PGHOST PGPORT PGPASSWORD DATABASE_URL].each { |key| ENV.delete(key) }
end
def test_config_with_db_config_only
@@ -123,7 +123,7 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase
end
def test_mysql_include_password
- start({adapter: "mysql2", database: "db", username: "user", password: "qwerty"}, ["-p"])
+ start({ adapter: "mysql2", database: "db", username: "user", password: "qwerty" }, ["-p"])
assert !aborted
assert_equal [%w[mysql mysql5], "--user=user", "--password=qwerty", "db"], dbconsole.find_cmd_and_exec_args
end
@@ -145,7 +145,7 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase
end
def test_postgresql_include_password
- start({adapter: "postgresql", database: "db", username: "user", password: "q1w2e3"}, ["-p"])
+ start({ adapter: "postgresql", database: "db", username: "user", password: "q1w2e3" }, ["-p"])
assert !aborted
assert_equal ["psql", "db"], dbconsole.find_cmd_and_exec_args
assert_equal "user", ENV["PGUSER"]
@@ -159,13 +159,13 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase
end
def test_sqlite3_mode
- start({adapter: "sqlite3", database: "db.sqlite3"}, ["--mode", "html"])
+ start({ adapter: "sqlite3", database: "db.sqlite3" }, ["--mode", "html"])
assert !aborted
assert_equal ["sqlite3", "-html", Rails.root.join("db.sqlite3").to_s], dbconsole.find_cmd_and_exec_args
end
def test_sqlite3_header
- start({adapter: "sqlite3", database: "db.sqlite3"}, ["--header"])
+ start({ adapter: "sqlite3", database: "db.sqlite3" }, ["--header"])
assert_equal ["sqlite3", "-header", Rails.root.join("db.sqlite3").to_s], dbconsole.find_cmd_and_exec_args
end
@@ -190,7 +190,7 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase
end
def test_oracle_include_password
- start({adapter: "oracle", database: "db", username: "user", password: "secret"}, ["-p"])
+ start({ adapter: "oracle", database: "db", username: "user", password: "secret" }, ["-p"])
assert !aborted
assert_equal ["sqlplus", "user/secret@db"], dbconsole.find_cmd_and_exec_args
end
diff --git a/railties/test/engine/commands_tasks_test.rb b/railties/test/engine/commands_tasks_test.rb
new file mode 100644
index 0000000000..817175b9ef
--- /dev/null
+++ b/railties/test/engine/commands_tasks_test.rb
@@ -0,0 +1,24 @@
+require "abstract_unit"
+
+class Rails::Engine::CommandsTasksTest < ActiveSupport::TestCase
+ def setup
+ @destination_root = Dir.mktmpdir("bukkits")
+ Dir.chdir(@destination_root) { `bundle exec rails plugin new bukkits --mountable` }
+ end
+
+ def teardown
+ FileUtils.rm_rf(@destination_root)
+ end
+
+ def test_help_command_work_inside_engine
+ output = capture(:stderr) do
+ Dir.chdir(plugin_path) { `bin/rails --help` }
+ end
+ assert_no_match "NameError", output
+ end
+
+ private
+ def plugin_path
+ "#{@destination_root}/bukkits"
+ end
+end
diff --git a/railties/test/generators/actions_test.rb b/railties/test/generators/actions_test.rb
index 9d0d0dc59d..0a26897a4d 100644
--- a/railties/test/generators/actions_test.rb
+++ b/railties/test/generators/actions_test.rb
@@ -34,7 +34,7 @@ class ActionsTest < Rails::Generators::TestCase
end
def test_create_file_should_write_block_contents_to_file_path
- action(:create_file, "lib/test_file.rb"){ "heres block data" }
+ action(:create_file, "lib/test_file.rb") { "heres block data" }
assert_file "lib/test_file.rb", "heres block data"
end
@@ -78,7 +78,7 @@ class ActionsTest < Rails::Generators::TestCase
def test_gem_should_insert_on_separate_lines
run_generator
- File.open("Gemfile", "a") {|f| f.write("# Some content...") }
+ File.open("Gemfile", "a") { |f| f.write("# Some content...") }
action :gem, "rspec"
action :gem, "rspec-rails"
@@ -372,6 +372,6 @@ F
protected
def action(*args, &block)
- capture(:stdout){ generator.send(*args, &block) }
+ capture(:stdout) { generator.send(*args, &block) }
end
end
diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb
index 969c2df718..acab83799d 100644
--- a/railties/test/generators/app_generator_test.rb
+++ b/railties/test/generators/app_generator_test.rb
@@ -77,7 +77,7 @@ class AppGeneratorTest < Rails::Generators::TestCase
end
def test_invalid_application_name_raises_an_error
- content = capture(:stderr){ run_generator [File.join(destination_root, "43-things")] }
+ content = capture(:stderr) { run_generator [File.join(destination_root, "43-things")] }
assert_equal "Invalid application name 43-things. Please give a name which does not start with numbers.\n", content
end
@@ -380,6 +380,8 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file "config/environments/production.rb" do |content|
assert_no_match(/config\.action_mailer/, content)
end
+ assert_no_directory "app/mailers"
+ assert_no_directory "test/mailers"
end
def test_generator_has_assets_gems
diff --git a/railties/test/generators/controller_generator_test.rb b/railties/test/generators/controller_generator_test.rb
index dd19c5e166..9b986a636a 100644
--- a/railties/test/generators/controller_generator_test.rb
+++ b/railties/test/generators/controller_generator_test.rb
@@ -19,7 +19,7 @@ class ControllerGeneratorTest < Rails::Generators::TestCase
def test_check_class_collision
Object.send :const_set, :ObjectController, Class.new
- content = capture(:stderr){ run_generator ["object"] }
+ content = capture(:stderr) { run_generator ["object"] }
assert_match(/The name 'ObjectController' is either already used in your application or reserved/, content)
ensure
Object.send :remove_const, :ObjectController
diff --git a/railties/test/generators/generator_generator_test.rb b/railties/test/generators/generator_generator_test.rb
index d68cdc29b0..5ff8bb0357 100644
--- a/railties/test/generators/generator_generator_test.rb
+++ b/railties/test/generators/generator_generator_test.rb
@@ -12,7 +12,7 @@ class GeneratorGeneratorTest < Rails::Generators::TestCase
lib/generators/awesome
lib/generators/awesome/USAGE
lib/generators/awesome/templates
- ).each{ |path| assert_file path }
+ ).each { |path| assert_file path }
assert_file "lib/generators/awesome/awesome_generator.rb",
/class AwesomeGenerator < Rails::Generators::NamedBase/
@@ -28,7 +28,7 @@ class GeneratorGeneratorTest < Rails::Generators::TestCase
lib/generators/rails/awesome
lib/generators/rails/awesome/USAGE
lib/generators/rails/awesome/templates
- ).each{ |path| assert_file path }
+ ).each { |path| assert_file path }
assert_file "lib/generators/rails/awesome/awesome_generator.rb",
/class Rails::AwesomeGenerator < Rails::Generators::NamedBase/
@@ -44,7 +44,7 @@ class GeneratorGeneratorTest < Rails::Generators::TestCase
lib/generators/
lib/generators/USAGE
lib/generators/templates
- ).each{ |path| assert_file path }
+ ).each { |path| assert_file path }
assert_file "lib/generators/awesome_generator.rb",
/class AwesomeGenerator < Rails::Generators::NamedBase/
@@ -60,7 +60,7 @@ class GeneratorGeneratorTest < Rails::Generators::TestCase
lib/generators/rails
lib/generators/rails/USAGE
lib/generators/rails/templates
- ).each{ |path| assert_file path }
+ ).each { |path| assert_file path }
assert_file "lib/generators/rails/awesome_generator.rb",
/class Rails::AwesomeGenerator < Rails::Generators::NamedBase/
diff --git a/railties/test/generators/helper_generator_test.rb b/railties/test/generators/helper_generator_test.rb
index e64cb4cbe0..d9e6e0a85a 100644
--- a/railties/test/generators/helper_generator_test.rb
+++ b/railties/test/generators/helper_generator_test.rb
@@ -14,7 +14,7 @@ class HelperGeneratorTest < Rails::Generators::TestCase
end
def test_check_class_collision
- content = capture(:stderr){ run_generator ["object"] }
+ content = capture(:stderr) { run_generator ["object"] }
assert_match(/The name 'ObjectHelper' is either already used in your application or reserved/, content)
end
diff --git a/railties/test/generators/mailer_generator_test.rb b/railties/test/generators/mailer_generator_test.rb
index 1edaa1b37f..7d69d7470d 100644
--- a/railties/test/generators/mailer_generator_test.rb
+++ b/railties/test/generators/mailer_generator_test.rb
@@ -30,7 +30,7 @@ class MailerGeneratorTest < Rails::Generators::TestCase
def test_check_class_collision
Object.send :const_set, :NotifierMailer, Class.new
- content = capture(:stderr){ run_generator }
+ content = capture(:stderr) { run_generator }
assert_match(/The name 'NotifierMailer' is either already used in your application or reserved/, content)
ensure
Object.send :remove_const, :NotifierMailer
@@ -59,7 +59,7 @@ class MailerGeneratorTest < Rails::Generators::TestCase
def test_check_test_class_collision
Object.send :const_set, :NotifierMailerTest, Class.new
- content = capture(:stderr){ run_generator }
+ content = capture(:stderr) { run_generator }
assert_match(/The name 'NotifierMailerTest' is either already used in your application or reserved/, content)
ensure
Object.send :remove_const, :NotifierMailerTest
@@ -67,7 +67,7 @@ class MailerGeneratorTest < Rails::Generators::TestCase
def test_check_preview_class_collision
Object.send :const_set, :NotifierMailerPreview, Class.new
- content = capture(:stderr){ run_generator }
+ content = capture(:stderr) { run_generator }
assert_match(/The name 'NotifierMailerPreview' is either already used in your application or reserved/, content)
ensure
Object.send :remove_const, :NotifierMailerPreview
diff --git a/railties/test/generators/model_generator_test.rb b/railties/test/generators/model_generator_test.rb
index 6451aa75c9..701d3ceaf2 100644
--- a/railties/test/generators/model_generator_test.rb
+++ b/railties/test/generators/model_generator_test.rb
@@ -275,7 +275,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase
def test_migration_error_is_not_shown_on_revoke
run_generator
- error = capture(:stderr){ run_generator ["Account"], behavior: :revoke }
+ error = capture(:stderr) { run_generator ["Account"], behavior: :revoke }
assert_no_match(/Another migration is already named create_accounts/, error)
end
@@ -300,7 +300,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase
assert_file "test/fixtures/accounts.yml", /name: MyString/, /age: 1/
assert_generated_fixture("test/fixtures/accounts.yml",
- "one"=>{"name"=>"MyString", "age"=>1}, "two"=>{"name"=>"MyString", "age"=>1})
+ "one"=>{ "name"=>"MyString", "age"=>1 }, "two"=>{ "name"=>"MyString", "age"=>1 })
end
def test_fixtures_use_the_references_ids
@@ -308,7 +308,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase
assert_file "test/fixtures/line_items.yml", /product: one\n cart: one/
assert_generated_fixture("test/fixtures/line_items.yml",
- "one"=>{"product"=>"one", "cart"=>"one"}, "two"=>{"product"=>"two", "cart"=>"two"})
+ "one"=>{ "product"=>"one", "cart"=>"one" }, "two"=>{ "product"=>"two", "cart"=>"two" })
end
def test_fixtures_use_the_references_ids_and_type
@@ -316,15 +316,15 @@ class ModelGeneratorTest < Rails::Generators::TestCase
assert_file "test/fixtures/line_items.yml", /product: one\n product_type: Product\n cart: one/
assert_generated_fixture("test/fixtures/line_items.yml",
- "one"=>{"product"=>"one", "product_type"=>"Product", "cart"=>"one"},
- "two"=>{"product"=>"two", "product_type"=>"Product", "cart"=>"two"})
+ "one"=>{ "product"=>"one", "product_type"=>"Product", "cart"=>"one" },
+ "two"=>{ "product"=>"two", "product_type"=>"Product", "cart"=>"two" })
end
def test_fixtures_respect_reserved_yml_keywords
run_generator ["LineItem", "no:integer", "Off:boolean", "ON:boolean"]
assert_generated_fixture("test/fixtures/line_items.yml",
- "one"=>{"no"=>1, "Off"=>false, "ON"=>false}, "two"=>{"no"=>1, "Off"=>false, "ON"=>false})
+ "one"=>{ "no"=>1, "Off"=>false, "ON"=>false }, "two"=>{ "no"=>1, "Off"=>false, "ON"=>false })
end
def test_fixture_is_skipped
@@ -343,13 +343,13 @@ class ModelGeneratorTest < Rails::Generators::TestCase
ActiveRecord::Base.pluralize_table_names = false
run_generator
assert_generated_fixture("test/fixtures/account.yml",
- "one"=>{"name"=>"MyString", "age"=>1}, "two"=>{"name"=>"MyString", "age"=>1})
+ "one"=>{ "name"=>"MyString", "age"=>1 }, "two"=>{ "name"=>"MyString", "age"=>1 })
ensure
ActiveRecord::Base.pluralize_table_names = original_pluralize_table_name
end
def test_check_class_collision
- content = capture(:stderr){ run_generator ["object"] }
+ content = capture(:stderr) { run_generator ["object"] }
assert_match(/The name 'Object' is either already used in your application or reserved/, content)
end
diff --git a/railties/test/generators/plugin_generator_test.rb b/railties/test/generators/plugin_generator_test.rb
index d20c2266a8..0d8e6f8907 100644
--- a/railties/test/generators/plugin_generator_test.rb
+++ b/railties/test/generators/plugin_generator_test.rb
@@ -27,19 +27,19 @@ class PluginGeneratorTest < Rails::Generators::TestCase
include SharedGeneratorTests
def test_invalid_plugin_name_raises_an_error
- content = capture(:stderr){ run_generator [File.join(destination_root, "my_plugin-31fr-extension")] }
+ content = capture(:stderr) { run_generator [File.join(destination_root, "my_plugin-31fr-extension")] }
assert_equal "Invalid plugin name my_plugin-31fr-extension. Please give a name which does not contain a namespace starting with numeric characters.\n", content
- content = capture(:stderr){ run_generator [File.join(destination_root, "things4.3")] }
+ content = capture(:stderr) { run_generator [File.join(destination_root, "things4.3")] }
assert_equal "Invalid plugin name things4.3. Please give a name which uses only alphabetic, numeric, \"_\" or \"-\" characters.\n", content
- content = capture(:stderr){ run_generator [File.join(destination_root, "43things")] }
+ content = capture(:stderr) { run_generator [File.join(destination_root, "43things")] }
assert_equal "Invalid plugin name 43things. Please give a name which does not start with numbers.\n", content
- content = capture(:stderr){ run_generator [File.join(destination_root, "plugin")] }
+ content = capture(:stderr) { run_generator [File.join(destination_root, "plugin")] }
assert_equal "Invalid plugin name plugin. Please give a name which does not match one of the reserved rails words: application, destroy, plugin, runner, test\n", content
- content = capture(:stderr){ run_generator [File.join(destination_root, "Digest")] }
+ content = capture(:stderr) { run_generator [File.join(destination_root, "Digest")] }
assert_equal "Invalid plugin name Digest, constant Digest is already in use. Please choose another plugin name.\n", content
end
@@ -618,7 +618,6 @@ class PluginGeneratorTest < Rails::Generators::TestCase
end
end
-
def test_api_generators_configuration_for_api_engines
run_generator [destination_root, "--full", "--api"]
@@ -711,7 +710,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase
protected
def action(*args, &block)
- silence(:stdout){ generator.send(*args, &block) }
+ silence(:stdout) { generator.send(*args, &block) }
end
def default_files
diff --git a/railties/test/generators/shared_generator_tests.rb b/railties/test/generators/shared_generator_tests.rb
index 766162b625..27b2fc8955 100644
--- a/railties/test/generators/shared_generator_tests.rb
+++ b/railties/test/generators/shared_generator_tests.rb
@@ -28,11 +28,11 @@ module SharedGeneratorTests
def test_plugin_new_generate_pretend
run_generator ["testapp", "--pretend"]
- default_files.each{ |path| assert_no_file File.join("testapp",path) }
+ default_files.each { |path| assert_no_file File.join("testapp",path) }
end
def test_invalid_database_option_raises_an_error
- content = capture(:stderr){ run_generator([destination_root, "-d", "unknown"]) }
+ content = capture(:stderr) { run_generator([destination_root, "-d", "unknown"]) }
assert_match(/Invalid value for \-\-database option/, content)
end
@@ -44,14 +44,14 @@ module SharedGeneratorTests
def test_name_collision_raises_an_error
reserved_words = %w[application destroy plugin runner test]
reserved_words.each do |reserved|
- content = capture(:stderr){ run_generator [File.join(destination_root, reserved)] }
+ content = capture(:stderr) { run_generator [File.join(destination_root, reserved)] }
assert_match(/Invalid \w+ name #{reserved}. Please give a name which does not match one of the reserved rails words: application, destroy, plugin, runner, test\n/, content)
end
end
def test_name_raises_an_error_if_name_already_used_constant
%w{ String Hash Class Module Set Symbol }.each do |ruby_class|
- content = capture(:stderr){ run_generator [File.join(destination_root, ruby_class)] }
+ content = capture(:stderr) { run_generator [File.join(destination_root, ruby_class)] }
assert_match(/Invalid \w+ name #{ruby_class}, constant #{ruby_class} is already in use. Please choose another \w+ name.\n/, content)
end
end
@@ -68,7 +68,7 @@ module SharedGeneratorTests
def test_template_raises_an_error_with_invalid_path
quietly do
- content = capture(:stderr){ run_generator([destination_root, "-m", "non/existent/path"]) }
+ content = capture(:stderr) { run_generator([destination_root, "-m", "non/existent/path"]) }
assert_match(/The template \[.*\] could not be loaded/, content)
assert_match(/non\/existent\/path/, content)
diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb
index 83c1d6811c..3c22881080 100644
--- a/railties/test/generators_test.rb
+++ b/railties/test/generators_test.rb
@@ -23,32 +23,32 @@ class GeneratorsTest < Rails::Generators::TestCase
def test_invoke_when_generator_is_not_found
name = :unknown
- output = capture(:stdout){ Rails::Generators.invoke name }
+ output = capture(:stdout) { Rails::Generators.invoke name }
assert_match "Could not find generator '#{name}'", output
assert_match "`rails generate --help`", output
end
def test_generator_suggestions
name = :migrationz
- output = capture(:stdout){ Rails::Generators.invoke name }
+ output = capture(:stdout) { Rails::Generators.invoke name }
assert_match "Maybe you meant 'migration'", output
end
def test_generator_multiple_suggestions
name = :tas
- output = capture(:stdout){ Rails::Generators.invoke name }
+ output = capture(:stdout) { Rails::Generators.invoke name }
assert_match "Maybe you meant 'task', 'job' or", output
end
def test_help_when_a_generator_with_required_arguments_is_invoked_without_arguments
- output = capture(:stdout){ Rails::Generators.invoke :model, [] }
+ output = capture(:stdout) { Rails::Generators.invoke :model, [] }
assert_match(/Description:/, output)
end
def test_should_give_higher_preference_to_rails_generators
assert File.exist?(File.join(@path, "generators", "model_generator.rb"))
assert_called_with(Rails::Generators::ModelGenerator, :start, [["Account"], {}]) do
- warnings = capture(:stderr){ Rails::Generators.invoke :model, ["Account"] }
+ warnings = capture(:stderr) { Rails::Generators.invoke :model, ["Account"] }
assert warnings.empty?
end
end
@@ -115,7 +115,7 @@ class GeneratorsTest < Rails::Generators::TestCase
end
def test_rails_generators_help_with_builtin_information
- output = capture(:stdout){ Rails::Generators.help }
+ output = capture(:stdout) { Rails::Generators.help }
assert_match(/Rails:/, output)
assert_match(/^ model$/, output)
assert_match(/^ scaffold_controller$/, output)
@@ -123,19 +123,19 @@ class GeneratorsTest < Rails::Generators::TestCase
end
def test_rails_generators_help_does_not_include_app_nor_plugin_new
- output = capture(:stdout){ Rails::Generators.help }
+ output = capture(:stdout) { Rails::Generators.help }
assert_no_match(/app/, output)
assert_no_match(/[^:]plugin/, output)
end
def test_rails_generators_with_others_information
- output = capture(:stdout){ Rails::Generators.help }
+ output = capture(:stdout) { Rails::Generators.help }
assert_match(/Fixjour:/, output)
assert_match(/^ fixjour$/, output)
end
def test_rails_generators_does_not_show_active_record_hooks
- output = capture(:stdout){ Rails::Generators.help }
+ output = capture(:stdout) { Rails::Generators.help }
assert_match(/ActiveRecord:/, output)
assert_match(/^ active_record:fixjour$/, output)
end
@@ -214,7 +214,7 @@ class GeneratorsTest < Rails::Generators::TestCase
# Create template
mkdir_p(File.dirname(template))
- File.open(template, "w"){ |f| f.write "empty" }
+ File.open(template, "w") { |f| f.write "empty" }
capture(:stdout) do
Rails::Generators.invoke :model, ["user"], destination_root: destination_root
diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb
index fb3818b92c..b9b11504dc 100644
--- a/railties/test/isolation/abstract_unit.rb
+++ b/railties/test/isolation/abstract_unit.rb
@@ -66,7 +66,7 @@ module TestHelpers
def extract_body(response)
"".tap do |body|
- response[2].each {|chunk| body << chunk }
+ response[2].each { |chunk| body << chunk }
end
end
@@ -214,7 +214,7 @@ module TestHelpers
def write(file, string)
path = "#{@path}/#{file}"
FileUtils.mkdir_p(File.dirname(path))
- File.open(path, "w") {|f| f.puts string }
+ File.open(path, "w") { |f| f.puts string }
end
def delete(file)
@@ -308,7 +308,7 @@ module TestHelpers
remove_from_config "config.active_record.*"
end
- $:.reject! {|path| path =~ %r'/(#{to_remove.join('|')})/' }
+ $:.reject! { |path| path =~ %r'/(#{to_remove.join('|')})/' }
end
end
end
diff --git a/railties/test/json_params_parsing_test.rb b/railties/test/json_params_parsing_test.rb
new file mode 100644
index 0000000000..104664c1ee
--- /dev/null
+++ b/railties/test/json_params_parsing_test.rb
@@ -0,0 +1,49 @@
+require "abstract_unit"
+require "action_dispatch"
+require "active_record"
+
+class JsonParamsParsingTest < ActionDispatch::IntegrationTest
+ def test_prevent_null_query
+ # Make sure we have data to find
+ klass = Class.new(ActiveRecord::Base) do
+ def self.name; 'Foo'; end
+ establish_connection adapter: "sqlite3", database: ":memory:"
+ connection.create_table "foos" do |t|
+ t.string :title
+ t.timestamps null: false
+ end
+ end
+ klass.create
+ assert klass.first
+
+ app = ->(env) {
+ request = ActionDispatch::Request.new env
+ params = ActionController::Parameters.new request.parameters
+ if params[:t]
+ klass.find_by_title(params[:t])
+ else
+ nil
+ end
+ }
+
+ assert_nil app.call(make_env({ 't' => nil }))
+ assert_nil app.call(make_env({ 't' => [nil] }))
+
+ [[[nil]], [[[nil]]]].each do |data|
+ assert_nil app.call(make_env({ 't' => data }))
+ end
+ ensure
+ klass.connection.drop_table("foos")
+ end
+
+ private
+ def make_env json
+ data = JSON.dump json
+ content_length = data.length
+ {
+ 'CONTENT_LENGTH' => content_length,
+ 'CONTENT_TYPE' => 'application/json',
+ 'rack.input' => StringIO.new(data)
+ }
+ end
+end
diff --git a/railties/test/path_generation_test.rb b/railties/test/path_generation_test.rb
index 71aab479e5..579e50ac95 100644
--- a/railties/test/path_generation_test.rb
+++ b/railties/test/path_generation_test.rb
@@ -30,7 +30,7 @@ class PathGenerationTest < ActiveSupport::TestCase
end
def make_request(env)
- Request.new super, self.url_helpers, @block
+ Request.new(super, url_helpers, @block)
end
end
@@ -38,7 +38,7 @@ class PathGenerationTest < ActiveSupport::TestCase
host = uri_or_host.host unless path
path ||= uri_or_host.path
- params = {"PATH_INFO" => path,
+ params = { "PATH_INFO" => path,
"REQUEST_METHOD" => method,
"HTTP_HOST" => host }
diff --git a/railties/test/paths_test.rb b/railties/test/paths_test.rb
index 5e96f9f32f..a4f6922cb4 100644
--- a/railties/test/paths_test.rb
+++ b/railties/test/paths_test.rb
@@ -139,7 +139,7 @@ class PathsTest < ActiveSupport::TestCase
@root["app"] = "/app"
@root["app"].autoload_once!
@root["app"].autoload_once!
- assert_equal 1, @root.autoload_once.select {|p| p == @root["app"].expanded.first }.size
+ assert_equal 1, @root.autoload_once.select { |p| p == @root["app"].expanded.first }.size
end
end
@@ -203,7 +203,7 @@ class PathsTest < ActiveSupport::TestCase
@root["app"] = "/app"
@root["app"].eager_load!
@root["app"].eager_load!
- assert_equal 1, @root.eager_load.select {|p| p == @root["app"].expanded.first }.size
+ assert_equal 1, @root.eager_load.select { |p| p == @root["app"].expanded.first }.size
end
end
diff --git a/railties/test/rack_logger_test.rb b/railties/test/rack_logger_test.rb
index e14eff41ce..7dd91a2465 100644
--- a/railties/test/rack_logger_test.rb
+++ b/railties/test/rack_logger_test.rb
@@ -47,7 +47,7 @@ module Rails
end
def test_notification
- logger = TestLogger.new { }
+ logger = TestLogger.new {}
assert_difference("subscriber.starts.length") do
assert_difference("subscriber.finishes.length") do
diff --git a/railties/test/rails_info_test.rb b/railties/test/rails_info_test.rb
index 3c893fb3e0..fc4175719e 100644
--- a/railties/test/rails_info_test.rb
+++ b/railties/test/rails_info_test.rb
@@ -17,7 +17,7 @@ class InfoTest < ActiveSupport::TestCase
def test_property_with_block_swallows_exceptions_and_ignores_property
assert_nothing_raised do
Rails::Info.module_eval do
- property("Bogus") {raise}
+ property("Bogus") { raise }
end
end
assert !property_defined?("Bogus")
@@ -32,7 +32,7 @@ class InfoTest < ActiveSupport::TestCase
def test_property_with_block
Rails::Info.module_eval do
- property("Goodbye") {"World"}
+ property("Goodbye") { "World" }
end
assert_property "Goodbye", "World"
end
diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb
index d6bd281c53..0c8896a715 100644
--- a/railties/test/railties/engine_test.rb
+++ b/railties/test/railties/engine_test.rb
@@ -98,7 +98,7 @@ module RailtiesTest
assert_no_match(/2_create_users/, output.join("\n"))
- bukkits_migration_order = output.index(output.detect{|o| /NOTE: Migration 3_create_sessions.rb from bukkits has been skipped/ =~ o })
+ bukkits_migration_order = output.index(output.detect { |o| /NOTE: Migration 3_create_sessions.rb from bukkits has been skipped/ =~ o })
assert_not_nil bukkits_migration_order, "Expected migration to be skipped"
migrations_count = Dir["#{app_path}/db/migrate/*.rb"].length
@@ -1226,7 +1226,6 @@ YAML
end
RUBY
-
app_file "config/routes.rb", <<-RUBY
Rails.application.routes.draw do
mount Bukkits::Engine => "/"
@@ -1276,7 +1275,6 @@ YAML
end
RUBY
-
@plugin.write "app/controllers/bukkits/bukkit_controller.rb", <<-RUBY
class Bukkits::BukkitController < ActionController::Base
def index
diff --git a/railties/test/railties/mounted_engine_test.rb b/railties/test/railties/mounted_engine_test.rb
index 37036db16d..9db42c0c38 100644
--- a/railties/test/railties/mounted_engine_test.rb
+++ b/railties/test/railties/mounted_engine_test.rb
@@ -34,7 +34,6 @@ module ApplicationTests
end
RUBY
-
@simple_plugin.write "lib/weblog.rb", <<-RUBY
module Weblog
class Engine < ::Rails::Engine
@@ -239,7 +238,6 @@ module ApplicationTests
get "/metrics/generate_blog_route_in_view", {}, "SCRIPT_NAME" => "/foo"
assert_equal "/foo/anonymous/blog/posts/1", last_response.body
-
# test generating application's route from engine with default_url_options
get "/someone/blog/generate_application_route", {}, "SCRIPT_NAME" => "/foo"
assert_equal "/foo/", last_response.body
diff --git a/tools/profile b/tools/profile
index 0fec570875..124ed0f4be 100755
--- a/tools/profile
+++ b/tools/profile
@@ -71,7 +71,7 @@ module CodeTools
fail Error.new("No such file") unless File.exist?(path)
fail Error.new("#{path} is a directory") if File.directory?(path)
ruby_extension = File.extname(path) == ".rb"
- ruby_executable = File.open(path, "rb") {|f| f.readline } =~ [/\A#!.*ruby/]
+ ruby_executable = File.open(path, "rb") { |f| f.readline } =~ [/\A#!.*ruby/]
fail Error.new("Not a ruby file") unless ruby_extension or ruby_executable
end
@@ -111,7 +111,7 @@ rescue LoadError
# File activesupport/lib/active_support/inflector/methods.rb, line 150
def classify
# strip out any leading schema name
- camelize(self.sub(/.*\./, ""))
+ camelize(sub(/.*\./, ""))
end
# File activesupport/lib/active_support/inflector/methods.rb, line 68
def camelize(uppercase_first_letter = true)