From 80e66cc4d90bf8c15d1a5f6e3152e90147f00772 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sat, 6 Aug 2016 19:55:02 +0200 Subject: normalizes indentation and whitespace across the project --- .../lib/action_cable/connection/authorization.rb | 2 +- actioncable/test/stubs/test_server.rb | 6 +- actionmailer/lib/action_mailer/base.rb | 188 +-- actionmailer/lib/action_mailer/test_case.rb | 8 +- .../rails/generators/mailer/mailer_generator.rb | 2 +- actionmailer/test/base_test.rb | 18 +- actionmailer/test/i18n_with_controller_test.rb | 12 +- actionmailer/test/mail_helper_test.rb | 8 +- actionmailer/test/mailers/asset_mailer.rb | 2 +- actionmailer/test/mailers/proc_mailer.rb | 6 +- actionpack/lib/abstract_controller/helpers.rb | 24 +- actionpack/lib/action_controller/metal.rb | 44 +- .../metal/etag_with_template_digest.rb | 22 +- actionpack/lib/action_controller/metal/head.rb | 18 +- actionpack/lib/action_controller/metal/helpers.rb | 6 +- .../lib/action_controller/metal/implicit_render.rb | 2 +- actionpack/lib/action_controller/metal/live.rb | 22 +- .../lib/action_controller/metal/params_wrapper.rb | 32 +- .../lib/action_controller/metal/rendering.rb | 94 +- .../metal/request_forgery_protection.rb | 40 +- actionpack/lib/action_controller/test_case.rb | 88 +- actionpack/lib/action_dispatch/http/headers.rb | 14 +- .../lib/action_dispatch/http/mime_negotiation.rb | 26 +- actionpack/lib/action_dispatch/http/mime_type.rb | 30 +- actionpack/lib/action_dispatch/http/parameters.rb | 26 +- actionpack/lib/action_dispatch/http/response.rb | 2 +- actionpack/lib/action_dispatch/journey/nfa/dot.rb | 2 +- actionpack/lib/action_dispatch/journey/parser.rb | 296 ++--- actionpack/lib/action_dispatch/journey/route.rb | 12 +- actionpack/lib/action_dispatch/journey/visitors.rb | 36 +- .../lib/action_dispatch/middleware/cookies.rb | 42 +- .../action_dispatch/middleware/debug_exceptions.rb | 196 +-- .../middleware/exception_wrapper.rb | 70 +- actionpack/lib/action_dispatch/middleware/flash.rb | 14 +- .../middleware/public_exceptions.rb | 38 +- .../middleware/session/abstract_store.rb | 12 +- .../middleware/session/cookie_store.rb | 60 +- .../action_dispatch/middleware/show_exceptions.rb | 32 +- actionpack/lib/action_dispatch/middleware/stack.rb | 36 +- actionpack/lib/action_dispatch/request/session.rb | 34 +- actionpack/lib/action_dispatch/request/utils.rb | 1 - .../lib/action_dispatch/routing/inspector.rb | 64 +- actionpack/lib/action_dispatch/routing/mapper.rb | 32 +- .../action_dispatch/routing/polymorphic_routes.rb | 264 ++-- .../lib/action_dispatch/routing/route_set.rb | 92 +- actionpack/lib/action_dispatch/routing/url_for.rb | 24 +- .../action_dispatch/testing/assertion_response.rb | 12 +- actionpack/test/abstract/callbacks_test.rb | 32 +- actionpack/test/abstract_unit.rb | 38 +- .../test/controller/api/conditional_get_test.rb | 6 +- actionpack/test/controller/content_type_test.rb | 14 +- actionpack/test/controller/filters_test.rb | 58 +- .../controller/http_basic_authentication_test.rb | 42 +- .../controller/http_digest_authentication_test.rb | 68 +- .../controller/http_token_authentication_test.rb | 28 +- .../controller/new_base/render_context_test.rb | 12 +- .../controller/new_base/render_template_test.rb | 6 +- actionpack/test/controller/new_base/render_test.rb | 6 +- .../parameters/log_on_unpermitted_params_test.rb | 22 +- actionpack/test/controller/params_wrapper_test.rb | 14 +- .../controller/request_forgery_protection_test.rb | 20 +- actionpack/test/controller/resources_test.rb | 30 +- actionpack/test/controller/routing_test.rb | 2 +- actionpack/test/controller/show_exceptions_test.rb | 6 +- actionpack/test/controller/url_rewriter_test.rb | 1 - actionpack/test/dispatch/request/session_test.rb | 14 +- actionpack/test/dispatch/request_id_test.rb | 28 +- actionpack/test/dispatch/routing_test.rb | 6 +- .../test/dispatch/session/abstract_store_test.rb | 8 +- actionpack/test/dispatch/url_generation_test.rb | 1 - .../test/fixtures/helpers/fun/games_helper.rb | 2 +- actionpack/test/fixtures/helpers/just_me_helper.rb | 2 +- actionpack/test/fixtures/helpers/me_too_helper.rb | 2 +- .../fixtures/helpers_typo/admin/users_helper.rb | 1 - actionpack/test/journey/gtg/builder_test.rb | 26 +- .../test/journey/gtg/transition_table_test.rb | 32 +- .../test/journey/nfa/transition_table_test.rb | 10 +- actionpack/test/journey/router_test.rb | 62 +- actionview/lib/action_view/flows.rb | 6 +- .../lib/action_view/helpers/active_model_helper.rb | 12 +- actionview/lib/action_view/helpers/csrf_helper.rb | 2 +- actionview/lib/action_view/helpers/form_helper.rb | 4 +- .../lib/action_view/helpers/number_helper.rb | 76 +- actionview/lib/action_view/helpers/tags/base.rb | 198 +-- .../lib/action_view/helpers/tags/check_box.rb | 32 +- .../helpers/tags/collection_check_boxes.rb | 12 +- .../action_view/helpers/tags/collection_helpers.rb | 114 +- .../lib/action_view/helpers/tags/date_select.rb | 68 +- .../lib/action_view/helpers/tags/radio_button.rb | 6 +- actionview/lib/action_view/helpers/tags/select.rb | 6 +- .../lib/action_view/helpers/tags/text_field.rb | 6 +- .../lib/action_view/helpers/tags/translator.rb | 24 +- actionview/lib/action_view/helpers/text_helper.rb | 18 +- actionview/lib/action_view/layouts.rb | 26 +- actionview/lib/action_view/path_set.rb | 38 +- .../lib/action_view/renderer/abstract_renderer.rb | 30 +- .../lib/action_view/renderer/partial_renderer.rb | 324 ++--- .../renderer/streaming_template_renderer.rb | 88 +- .../lib/action_view/renderer/template_renderer.rb | 118 +- .../lib/action_view/template/handlers/builder.rb | 10 +- actionview/lib/action_view/template/resolver.rb | 148 +-- actionview/lib/action_view/view_paths.rb | 6 +- actionview/test/abstract_unit.rb | 20 +- .../abstract/abstract_controller_test.rb | 32 +- .../test/actionpack/abstract/layouts_test.rb | 12 +- .../activerecord/form_helper_activerecord_test.rb | 48 +- .../helpers_missing/invalid_require_helper.rb | 1 - actionview/test/fixtures/mascot.rb | 2 +- actionview/test/template/atom_feed_helper_test.rb | 16 +- actionview/test/template/date_helper_test.rb | 6 +- actionview/test/template/form_helper_test.rb | 108 +- .../test/template/form_options_helper_test.rb | 80 +- actionview/test/template/form_tag_helper_test.rb | 6 +- actionview/test/template/tag_helper_test.rb | 2 +- activejob/lib/active_job/logging.rb | 100 +- activejob/lib/active_job/queue_adapter.rb | 44 +- .../lib/active_job/queue_adapters/qu_adapter.rb | 2 +- .../lib/active_job/queue_adapters/test_adapter.rb | 26 +- .../lib/rails/generators/job/job_generator.rb | 10 +- activejob/test/adapters/backburner.rb | 2 +- activejob/test/adapters/delayed_job.rb | 1 - activejob/test/adapters/inline.rb | 2 +- activejob/test/cases/exceptions_test.rb | 30 +- activejob/test/jobs/gid_job.rb | 1 - activejob/test/jobs/logging_job.rb | 1 - activejob/test/jobs/nested_job.rb | 1 - activejob/test/support/backburner/inline.rb | 2 +- .../support/integration/adapters/backburner.rb | 1 - .../test/support/integration/adapters/inline.rb | 1 - .../lib/active_model/attribute_assignment.rb | 20 +- activemodel/lib/active_model/callbacks.rb | 36 +- activemodel/lib/active_model/naming.rb | 6 +- activemodel/lib/active_model/type/big_integer.rb | 6 +- activemodel/lib/active_model/type/boolean.rb | 12 +- activemodel/lib/active_model/type/date.rb | 50 +- activemodel/lib/active_model/type/date_time.rb | 38 +- activemodel/lib/active_model/type/decimal.rb | 62 +- activemodel/lib/active_model/type/float.rb | 16 +- .../lib/active_model/type/helpers/numeric.rb | 18 +- .../lib/active_model/type/helpers/time_value.rb | 34 +- .../lib/active_model/type/immutable_string.rb | 16 +- activemodel/lib/active_model/type/integer.rb | 42 +- activemodel/lib/active_model/type/registry.rb | 16 +- activemodel/lib/active_model/type/string.rb | 6 +- activemodel/lib/active_model/type/time.rb | 30 +- .../lib/active_model/type/unsigned_integer.rb | 12 +- activemodel/lib/active_model/type/value.rb | 6 +- .../lib/active_model/validations/acceptance.rb | 76 +- .../lib/active_model/validations/clusivity.rb | 2 +- .../lib/active_model/validations/confirmation.rb | 28 +- activemodel/lib/active_model/validations/format.rb | 42 +- activemodel/lib/active_model/validations/length.rb | 26 +- .../lib/active_model/validations/numericality.rb | 8 +- activemodel/lib/active_model/validator.rb | 6 +- .../test/cases/attribute_assignment_test.rb | 2 +- activemodel/test/cases/attribute_methods_test.rb | 4 +- .../cases/forbidden_attributes_protection_test.rb | 2 +- activemodel/test/cases/translation_test.rb | 1 - activemodel/test/cases/types_test.rb | 14 +- .../validations/numericality_validation_test.rb | 34 +- activemodel/test/models/custom_reader.rb | 2 +- activemodel/test/models/topic.rb | 2 +- activemodel/test/models/track_back.rb | 2 +- activemodel/test/models/user.rb | 2 +- activerecord/examples/performance.rb | 4 +- activerecord/lib/active_record/aggregations.rb | 174 +-- .../lib/active_record/association_relation.rb | 6 +- activerecord/lib/active_record/associations.rb | 1318 ++++++++++---------- .../associations/association_scope.rb | 158 +-- .../builder/has_and_belongs_to_many.rb | 44 +- .../associations/collection_association.rb | 2 +- .../active_record/associations/join_dependency.rb | 210 ++-- .../lib/active_record/associations/preloader.rb | 134 +- .../associations/preloader/association.rb | 142 +-- .../preloader/collection_association.rb | 14 +- .../associations/preloader/singular_association.rb | 14 +- .../associations/preloader/through_association.rb | 64 +- activerecord/lib/active_record/attribute.rb | 146 +-- .../attribute/user_provided_default.rb | 2 +- .../lib/active_record/attribute_assignment.rb | 106 +- .../lib/active_record/attribute_decorators.rb | 26 +- .../lib/active_record/attribute_methods.rb | 82 +- .../attribute_methods/before_type_cast.rb | 12 +- .../lib/active_record/attribute_methods/dirty.rb | 72 +- .../active_record/attribute_methods/primary_key.rb | 134 +- .../lib/active_record/attribute_methods/read.rb | 18 +- .../attribute_methods/serialization.rb | 2 +- .../attribute_methods/time_zone_conversion.rb | 88 +- .../lib/active_record/attribute_methods/write.rb | 36 +- .../active_record/attribute_mutation_tracker.rb | 8 +- activerecord/lib/active_record/attribute_set.rb | 8 +- .../lib/active_record/attribute_set/builder.rb | 38 +- .../active_record/attribute_set/yaml_encoder.rb | 2 +- activerecord/lib/active_record/attributes.rb | 32 +- .../lib/active_record/coders/yaml_column.rb | 12 +- .../abstract/connection_pool.rb | 360 +++--- .../connection_adapters/abstract/query_cache.rb | 28 +- .../connection_adapters/abstract/quoting.rb | 76 +- .../abstract/schema_definitions.rb | 82 +- .../connection_adapters/abstract/schema_dumper.rb | 66 +- .../abstract/schema_statements.rb | 64 +- .../connection_adapters/abstract_adapter.rb | 182 +-- .../connection_adapters/abstract_mysql_adapter.rb | 536 ++++---- .../active_record/connection_adapters/column.rb | 6 +- .../connection_specification.rb | 112 +- .../connection_adapters/mysql/column.rb | 8 +- .../mysql/database_statements.rb | 76 +- .../mysql/explain_pretty_printer.rb | 44 +- .../connection_adapters/mysql/quoting.rb | 12 +- .../connection_adapters/mysql/schema_creation.rb | 84 +- .../mysql/schema_definitions.rb | 6 +- .../connection_adapters/mysql/schema_dumper.rb | 36 +- .../connection_adapters/mysql/type_metadata.rb | 6 +- .../connection_adapters/mysql2_adapter.rb | 22 +- .../postgresql/database_statements.rb | 6 +- .../connection_adapters/postgresql/oid/array.rb | 12 +- .../connection_adapters/postgresql/oid/bit.rb | 2 +- .../connection_adapters/postgresql/oid/enum.rb | 6 +- .../connection_adapters/postgresql/oid/hstore.rb | 26 +- .../connection_adapters/postgresql/oid/point.rb | 6 +- .../postgresql/oid/rails_5_1_point.rb | 14 +- .../connection_adapters/postgresql/oid/range.rb | 52 +- .../postgresql/oid/type_map_initializer.rb | 88 +- .../connection_adapters/postgresql/quoting.rb | 60 +- .../postgresql/schema_dumper.rb | 26 +- .../postgresql/schema_statements.rb | 18 +- .../postgresql/type_metadata.rb | 6 +- .../connection_adapters/sql_type_metadata.rb | 6 +- .../connection_adapters/sqlite3/quoting.rb | 32 +- .../connection_adapters/sqlite3_adapter.rb | 6 +- .../connection_adapters/statement_pool.rb | 12 +- activerecord/lib/active_record/core.rb | 86 +- activerecord/lib/active_record/dynamic_matchers.rb | 148 +-- activerecord/lib/active_record/enum.rb | 2 +- activerecord/lib/active_record/fixtures.rb | 26 +- activerecord/lib/active_record/inheritance.rb | 132 +- .../lib/active_record/locking/optimistic.rb | 86 +- activerecord/lib/active_record/log_subscriber.rb | 56 +- activerecord/lib/active_record/migration.rb | 230 ++-- .../active_record/migration/command_recorder.rb | 176 +-- .../lib/active_record/migration/compatibility.rb | 24 +- .../lib/active_record/migration/join_table.rb | 12 +- activerecord/lib/active_record/model_schema.rb | 124 +- .../lib/active_record/nested_attributes.rb | 232 ++-- .../lib/active_record/railties/databases.rake | 4 +- activerecord/lib/active_record/relation.rb | 68 +- activerecord/lib/active_record/relation/batches.rb | 30 +- .../lib/active_record/relation/calculations.rb | 296 ++--- .../lib/active_record/relation/delegation.rb | 42 +- .../lib/active_record/relation/finder_methods.rb | 336 ++--- activerecord/lib/active_record/relation/merger.rb | 122 +- .../active_record/relation/predicate_builder.rb | 134 +- .../relation/predicate_builder/array_handler.rb | 10 +- .../predicate_builder/association_query_handler.rb | 42 +- .../relation/predicate_builder/base_handler.rb | 2 +- .../relation/predicate_builder/class_handler.rb | 8 +- .../predicate_builder/polymorphic_array_handler.rb | 20 +- .../lib/active_record/relation/query_methods.rb | 412 +++--- .../lib/active_record/relation/where_clause.rb | 122 +- .../active_record/relation/where_clause_factory.rb | 2 +- activerecord/lib/active_record/result.rb | 58 +- activerecord/lib/active_record/sanitization.rb | 180 +-- activerecord/lib/active_record/scoping.rb | 8 +- activerecord/lib/active_record/scoping/default.rb | 84 +- activerecord/lib/active_record/store.rb | 48 +- activerecord/lib/active_record/table_metadata.rb | 2 +- .../lib/active_record/tasks/database_tasks.rb | 50 +- .../active_record/tasks/mysql_database_tasks.rb | 116 +- .../tasks/postgresql_database_tasks.rb | 54 +- .../active_record/tasks/sqlite_database_tasks.rb | 12 +- activerecord/lib/active_record/transactions.rb | 140 +-- .../type/adapter_specific_registry.rb | 82 +- .../lib/active_record/type/hash_lookup_type_map.rb | 6 +- activerecord/lib/active_record/type/serialized.rb | 14 +- activerecord/lib/active_record/type/time.rb | 1 - activerecord/lib/active_record/type/type_map.rb | 24 +- .../lib/active_record/type_caster/connection.rb | 12 +- activerecord/lib/active_record/type_caster/map.rb | 2 +- .../active_record/migration/migration_generator.rb | 54 +- .../test/cases/adapters/mysql2/connection_test.rb | 6 +- .../test/cases/adapters/mysql2/json_test.rb | 270 ++-- .../cases/adapters/mysql2/mysql2_adapter_test.rb | 6 +- .../cases/adapters/mysql2/reserved_word_test.rb | 22 +- .../adapters/mysql2/schema_migrations_test.rb | 32 +- .../test/cases/adapters/postgresql/array_test.rb | 26 +- .../cases/adapters/postgresql/composite_test.rb | 10 +- .../cases/adapters/postgresql/connection_test.rb | 12 +- .../cases/adapters/postgresql/geometric_test.rb | 14 +- .../test/cases/adapters/postgresql/hstore_test.rb | 52 +- .../adapters/postgresql/postgresql_adapter_test.rb | 12 +- .../postgresql/referential_integrity_test.rb | 6 +- .../cases/adapters/postgresql/rename_table_test.rb | 6 +- .../postgresql/schema_authorization_test.rb | 2 +- .../cases/adapters/postgresql/transaction_test.rb | 12 +- .../test/cases/adapters/postgresql/uuid_test.rb | 4 +- .../cases/adapters/sqlite3/sqlite3_adapter_test.rb | 24 +- .../associations/eager_singularization_test.rb | 246 ++-- .../test/cases/associations/required_test.rb | 12 +- activerecord/test/cases/attribute_methods_test.rb | 48 +- .../test/cases/autosave_association_test.rb | 18 +- activerecord/test/cases/column_alias_test.rb | 2 +- activerecord/test/cases/column_definition_test.rb | 6 +- activerecord/test/cases/comment_test.rb | 208 +-- .../connection_adapters/mysql_type_lookup_test.rb | 100 +- .../cases/connection_adapters/type_lookup_test.rb | 172 +-- activerecord/test/cases/connection_pool_test.rb | 14 +- .../test/cases/database_statements_test.rb | 18 +- .../test/cases/date_time_precision_test.rb | 124 +- activerecord/test/cases/finder_respond_to_test.rb | 6 +- activerecord/test/cases/finder_test.rb | 2 +- activerecord/test/cases/fixture_set/file_test.rb | 18 +- activerecord/test/cases/helper.rb | 22 +- activerecord/test/cases/hot_compatibility_test.rb | 28 +- activerecord/test/cases/invalid_connection_test.rb | 30 +- activerecord/test/cases/json_serialization_test.rb | 16 +- activerecord/test/cases/locking_test.rb | 46 +- .../test/cases/migration/change_schema_test.rb | 12 +- activerecord/test/cases/migration/columns_test.rb | 2 +- .../test/cases/migration/foreign_key_test.rb | 464 +++---- activerecord/test/cases/migration/helper.rb | 2 +- .../cases/migration/references_foreign_key_test.rb | 314 ++--- .../cases/migration/references_statements_test.rb | 10 +- activerecord/test/cases/migration_test.rb | 36 +- activerecord/test/cases/migrator_test.rb | 52 +- activerecord/test/cases/nested_attributes_test.rb | 12 +- .../cases/nested_attributes_with_callbacks_test.rb | 2 +- activerecord/test/cases/pooled_connections_test.rb | 6 +- .../test/cases/relation/delegation_test.rb | 2 +- .../test/cases/relation/where_clause_test.rb | 18 +- activerecord/test/cases/relation_test.rb | 22 +- activerecord/test/cases/tasks/mysql_rake_test.rb | 518 ++++---- .../test/cases/tasks/postgresql_rake_test.rb | 450 +++---- activerecord/test/cases/tasks/sqlite_rake_test.rb | 330 ++--- activerecord/test/cases/time_precision_test.rb | 120 +- activerecord/test/cases/timestamp_test.rb | 14 +- activerecord/test/cases/transactions_test.rb | 16 +- activerecord/test/cases/type/type_map_test.rb | 1 - activerecord/test/cases/view_test.rb | 206 +-- activerecord/test/cases/yaml_serialization_test.rb | 14 +- activerecord/test/models/club.rb | 6 +- activerecord/test/models/company.rb | 22 +- activerecord/test/models/company_in_module.rb | 6 +- activerecord/test/models/engine.rb | 1 - activerecord/test/models/eye.rb | 2 +- activerecord/test/models/mentor.rb | 2 +- activerecord/test/models/person.rb | 12 +- activerecord/test/models/vehicle.rb | 2 +- .../lib/active_support/cache/mem_cache_store.rb | 28 +- activesupport/lib/active_support/callbacks.rb | 1120 ++++++++--------- .../lib/active_support/concurrency/share_lock.rb | 34 +- .../core_ext/array/prepend_and_append.rb | 2 +- .../active_support/core_ext/date/calculations.rb | 2 +- .../active_support/core_ext/date_and_time/zones.rb | 13 +- .../core_ext/date_time/conversions.rb | 12 +- .../lib/active_support/core_ext/hash/slice.rb | 8 +- .../lib/active_support/core_ext/numeric/inquiry.rb | 42 +- .../active_support/core_ext/string/inflections.rb | 2 +- .../core_ext/string/output_safety.rb | 6 +- activesupport/lib/active_support/dependencies.rb | 26 +- .../lib/active_support/duration/iso8601_parser.rb | 56 +- .../active_support/evented_file_update_checker.rb | 100 +- .../lib/active_support/file_update_checker.rb | 86 +- activesupport/lib/active_support/gzip.rb | 2 +- .../lib/active_support/inflector/methods.rb | 30 +- .../lib/active_support/inflector/transliterate.rb | 2 +- activesupport/lib/active_support/key_generator.rb | 24 +- .../active_support/log_subscriber/test_helper.rb | 10 +- .../lib/active_support/message_encryptor.rb | 102 +- .../lib/active_support/multibyte/unicode.rb | 34 +- .../active_support/notifications/instrumenter.rb | 6 +- .../number_to_human_size_converter.rb | 1 - .../number_helper/number_to_phone_converter.rb | 1 - activesupport/lib/active_support/testing/stream.rb | 56 +- .../lib/active_support/values/time_zone.rb | 10 +- activesupport/lib/active_support/xml_mini.rb | 38 +- activesupport/lib/active_support/xml_mini/jdom.rb | 134 +- activesupport/test/autoload_test.rb | 2 +- activesupport/test/autoloading_fixtures/a/b.rb | 2 +- activesupport/test/autoloading_fixtures/a/c/d.rb | 2 +- .../test/autoloading_fixtures/a/c/em/f.rb | 2 +- .../test/autoloading_fixtures/conflict.rb | 2 +- .../autoloading_fixtures/cross_site_dependency.rb | 2 +- activesupport/test/autoloading_fixtures/d.rb | 2 +- activesupport/test/autoloading_fixtures/em.rb | 2 +- .../load_path/loaded_constant.rb | 1 - .../module_folder/nested_sibling.rb | 2 +- .../module_with_custom_const_missing/a/b.rb | 2 +- .../test/autoloading_fixtures/requires_constant.rb | 1 - activesupport/test/autoloading_fixtures/typo.rb | 1 - activesupport/test/caching_test.rb | 14 +- activesupport/test/core_ext/date_ext_test.rb | 1 - .../test/core_ext/module/anonymous_test.rb | 2 +- .../module/attribute_accessor_per_thread_test.rb | 8 +- .../test/core_ext/module/qualified_const_test.rb | 8 +- .../test/core_ext/module/reachable_test.rb | 2 +- activesupport/test/core_ext/module_test.rb | 6 +- .../test/core_ext/object/inclusion_test.rb | 4 +- activesupport/test/dependencies/conflict.rb | 2 +- .../test/dependencies/cross_site_depender.rb | 2 +- activesupport/test/dependencies/service_one.rb | 2 +- activesupport/test/dependencies/service_two.rb | 2 +- activesupport/test/dependencies_test_helpers.rb | 2 +- .../test/descendants_tracker_test_cases.rb | 34 +- .../test/fixtures/autoload/another_class.rb | 2 +- activesupport/test/fixtures/autoload/some_class.rb | 2 +- activesupport/test/inflector_test_cases.rb | 36 +- activesupport/test/json/decoding_test.rb | 15 +- activesupport/test/key_generator_test.rb | 114 +- activesupport/test/lazy_load_hooks_test.rb | 2 +- activesupport/test/message_encryptor_test.rb | 26 +- activesupport/test/multibyte_chars_test.rb | 22 +- activesupport/test/share_lock_test.rb | 124 +- activesupport/test/subscriber_test.rb | 6 +- activesupport/test/xml_mini/jdom_engine_test.rb | 12 +- activesupport/test/xml_mini/libxml_engine_test.rb | 194 +-- .../test/xml_mini/libxmlsax_engine_test.rb | 160 +-- .../test/xml_mini/nokogiri_engine_test.rb | 182 +-- .../test/xml_mini/nokogirisax_engine_test.rb | 182 +-- activesupport/test/xml_mini/rexml_engine_test.rb | 4 +- ci/travis.rb | 4 +- guides/Rakefile | 2 +- guides/rails_guides/generator.rb | 220 ++-- guides/rails_guides/indexer.rb | 72 +- guides/rails_guides/kindle.rb | 12 +- guides/w3c_validator.rb | 52 +- railties/lib/rails/application.rb | 18 +- railties/lib/rails/application_controller.rb | 14 +- railties/lib/rails/commands/console_helper.rb | 6 +- railties/lib/rails/commands/dbconsole.rb | 2 +- railties/lib/rails/commands/plugin.rb | 2 +- railties/lib/rails/commands/runner.rb | 14 +- railties/lib/rails/commands/server.rb | 48 +- railties/lib/rails/engine.rb | 84 +- .../rails/generators/actions/create_migration.rb | 42 +- railties/lib/rails/generators/erb.rb | 24 +- .../generators/erb/mailer/mailer_generator.rb | 12 +- .../generators/rails/assets/assets_generator.rb | 18 +- railties/lib/rails/info.rb | 2 +- railties/lib/rails/info_controller.rb | 16 +- railties/lib/rails/rack/logger.rb | 14 +- railties/lib/rails/railtie.rb | 38 +- railties/lib/rails/railtie/configurable.rb | 6 +- railties/lib/rails/tasks/annotations.rake | 2 +- railties/lib/rails/tasks/log.rake | 8 +- railties/lib/rails/test_unit/testing.rake | 2 +- railties/test/application/assets_test.rb | 12 +- railties/test/application/loading_test.rb | 14 +- .../test/application/middleware/static_test.rb | 4 +- railties/test/application/rake/migrations_test.rb | 72 +- railties/test/application/rake/notes_test.rb | 34 +- railties/test/commands/console_test.rb | 50 +- railties/test/commands/dbconsole_test.rb | 50 +- .../configuration/middleware_stack_proxy_test.rb | 12 +- railties/test/env_helpers.rb | 36 +- .../about_yml_plugins/bad_about_yml/init.rb | 2 +- .../plugin_without_about_yml/init.rb | 2 +- .../fixtures/lib/generators/model_generator.rb | 2 +- railties/test/generators/api_app_generator_test.rb | 90 +- railties/test/generators/app_generator_test.rb | 2 +- railties/test/generators/model_generator_test.rb | 14 +- railties/test/railties/mounted_engine_test.rb | 6 +- railties/test/test_unit/reporter_test.rb | 60 +- tools/profile | 52 +- 463 files changed, 11638 insertions(+), 11661 deletions(-) diff --git a/actioncable/lib/action_cable/connection/authorization.rb b/actioncable/lib/action_cable/connection/authorization.rb index 070a70e4e2..85df206445 100644 --- a/actioncable/lib/action_cable/connection/authorization.rb +++ b/actioncable/lib/action_cable/connection/authorization.rb @@ -10,4 +10,4 @@ module ActionCable end end end -end \ No newline at end of file +end diff --git a/actioncable/test/stubs/test_server.rb b/actioncable/test/stubs/test_server.rb index f1b194de12..71819a43dc 100644 --- a/actioncable/test/stubs/test_server.rb +++ b/actioncable/test/stubs/test_server.rb @@ -12,12 +12,12 @@ class TestServer @config = OpenStruct.new(log_tags: [], subscription_adapter: subscription_adapter) @config.use_faye = ENV["FAYE"].present? @config.client_socket_class = if @config.use_faye - ActionCable::Connection::FayeClientSocket + ActionCable::Connection::FayeClientSocket else ActionCable::Connection::ClientSocket end - @mutex = Monitor.new + @mutex = Monitor.new end def pubsub @@ -26,7 +26,7 @@ class TestServer def event_loop @event_loop ||= if @config.use_faye - ActionCable::Connection::FayeEventLoop.new + ActionCable::Connection::FayeEventLoop.new else ActionCable::Connection::StreamEventLoop.new end diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb index 315321620b..fb6ff819c9 100644 --- a/actionmailer/lib/action_mailer/base.rb +++ b/actionmailer/lib/action_mailer/base.rb @@ -841,127 +841,127 @@ module ActionMailer # If there is no content type passed in via headers, and there are no # attachments, or the message is multipart, then the default content type is # used. - def set_content_type(m, user_content_type, class_default) - params = m.content_type_parameters || {} - case - when user_content_type.present? - user_content_type - when m.has_attachments? - if m.attachments.detect(&:inline?) - ["multipart", "related", params] + def set_content_type(m, user_content_type, class_default) + params = m.content_type_parameters || {} + case + when user_content_type.present? + user_content_type + when m.has_attachments? + if m.attachments.detect(&:inline?) + ["multipart", "related", params] + else + ["multipart", "mixed", params] + end + when m.multipart? + ["multipart", "alternative", params] else - ["multipart", "mixed", params] + m.content_type || class_default end - when m.multipart? - ["multipart", "alternative", params] - else - m.content_type || class_default end - end # Translates the +subject+ using Rails I18n class under [mailer_scope, action_name] scope. # If it does not find a translation for the +subject+ under the specified scope it will default to a # humanized version of the action_name. # If the subject has interpolations, you can pass them through the +interpolations+ parameter. - def default_i18n_subject(interpolations = {}) - mailer_scope = self.class.mailer_name.tr("/", ".") - I18n.t(:subject, interpolations.merge(scope: [mailer_scope, action_name], default: action_name.humanize)) - end + def default_i18n_subject(interpolations = {}) + mailer_scope = self.class.mailer_name.tr("/", ".") + I18n.t(:subject, interpolations.merge(scope: [mailer_scope, action_name], default: action_name.humanize)) + end # Emails do not support relative path links. - def self.supports_path? - false - end + def self.supports_path? + false + end private - def apply_defaults(headers) - default_values = self.class.default.map do |key, value| - [ - key, - value.is_a?(Proc) ? instance_eval(&value) : value - ] - end.to_h - - headers_with_defaults = headers.reverse_merge(default_values) - headers_with_defaults[:subject] ||= default_i18n_subject - headers_with_defaults - end + def apply_defaults(headers) + default_values = self.class.default.map do |key, value| + [ + key, + value.is_a?(Proc) ? instance_eval(&value) : value + ] + end.to_h + + headers_with_defaults = headers.reverse_merge(default_values) + headers_with_defaults[:subject] ||= default_i18n_subject + headers_with_defaults + end - def assign_headers_to_message(message, headers) - assignable = headers.except(:parts_order, :content_type, :body, :template_name, - :template_path, :delivery_method, :delivery_method_options) - assignable.each { |k, v| message[k] = v } - end + def assign_headers_to_message(message, headers) + assignable = headers.except(:parts_order, :content_type, :body, :template_name, + :template_path, :delivery_method, :delivery_method_options) + assignable.each { |k, v| message[k] = v } + end - def collect_responses(headers) - if block_given? - collector = ActionMailer::Collector.new(lookup_context) { render(action_name) } - yield(collector) - collector.responses - elsif headers[:body] - [{ - body: headers.delete(:body), - content_type: self.class.default[:content_type] || "text/plain" - }] - else - collect_responses_from_templates(headers) + def collect_responses(headers) + if block_given? + collector = ActionMailer::Collector.new(lookup_context) { render(action_name) } + yield(collector) + collector.responses + elsif headers[:body] + [{ + body: headers.delete(:body), + content_type: self.class.default[:content_type] || "text/plain" + }] + else + collect_responses_from_templates(headers) + end end - end - def collect_responses_from_templates(headers) - templates_path = headers[:template_path] || self.class.mailer_name - templates_name = headers[:template_name] || action_name + def collect_responses_from_templates(headers) + templates_path = headers[:template_path] || self.class.mailer_name + templates_name = headers[:template_name] || action_name - each_template(Array(templates_path), templates_name).map do |template| - self.formats = template.formats - { - body: render(template: template), - content_type: template.type.to_s - } + each_template(Array(templates_path), templates_name).map do |template| + self.formats = template.formats + { + body: render(template: template), + content_type: template.type.to_s + } + end end - end - def each_template(paths, name, &block) - templates = lookup_context.find_all(name, paths) - if templates.empty? - raise ActionView::MissingTemplate.new(paths, name, paths, false, "mailer") - else - templates.uniq(&:formats).each(&block) + def each_template(paths, name, &block) + templates = lookup_context.find_all(name, paths) + if templates.empty? + raise ActionView::MissingTemplate.new(paths, name, paths, false, "mailer") + else + templates.uniq(&:formats).each(&block) + end end - end - def create_parts_from_responses(m, responses) - if responses.size == 1 && !m.has_attachments? - responses[0].each { |k,v| m[k] = v } - elsif responses.size > 1 && m.has_attachments? - container = Mail::Part.new - container.content_type = "multipart/alternative" - responses.each { |r| insert_part(container, r, m.charset) } - m.add_part(container) - else - responses.each { |r| insert_part(m, r, m.charset) } + def create_parts_from_responses(m, responses) + if responses.size == 1 && !m.has_attachments? + responses[0].each { |k,v| m[k] = v } + elsif responses.size > 1 && m.has_attachments? + container = Mail::Part.new + container.content_type = "multipart/alternative" + responses.each { |r| insert_part(container, r, m.charset) } + m.add_part(container) + else + responses.each { |r| insert_part(m, r, m.charset) } + end end - end - def insert_part(container, response, charset) - response[:charset] ||= charset - part = Mail::Part.new(response) - container.add_part(part) - end + def insert_part(container, response, charset) + response[:charset] ||= charset + part = Mail::Part.new(response) + container.add_part(part) + end # This and #instrument_name is for caching instrument - def instrument_payload(key) - { - mailer: mailer_name, - key: key - } - end + def instrument_payload(key) + { + mailer: mailer_name, + key: key + } + end - def instrument_name - "action_mailer" - end + def instrument_name + "action_mailer" + end - ActiveSupport.run_load_hooks(:action_mailer, self) + ActiveSupport.run_load_hooks(:action_mailer, self) end end diff --git a/actionmailer/lib/action_mailer/test_case.rb b/actionmailer/lib/action_mailer/test_case.rb index c224fa11d4..d3eded547c 100644 --- a/actionmailer/lib/action_mailer/test_case.rb +++ b/actionmailer/lib/action_mailer/test_case.rb @@ -21,11 +21,11 @@ module ActionMailer private - def clear_test_deliveries - if ActionMailer::Base.delivery_method == :test - ActionMailer::Base.deliveries.clear + def clear_test_deliveries + if ActionMailer::Base.delivery_method == :test + ActionMailer::Base.deliveries.clear + end end - end end module Behavior diff --git a/actionmailer/lib/rails/generators/mailer/mailer_generator.rb b/actionmailer/lib/rails/generators/mailer/mailer_generator.rb index 4b74fb4258..72e53fb993 100644 --- a/actionmailer/lib/rails/generators/mailer/mailer_generator.rb +++ b/actionmailer/lib/rails/generators/mailer/mailer_generator.rb @@ -27,7 +27,7 @@ module Rails private def application_mailer_file_name @_application_mailer_file_name ||= if mountable_engine? - "app/mailers/#{namespaced_path}/application_mailer.rb" + "app/mailers/#{namespaced_path}/application_mailer.rb" else "app/mailers/application_mailer.rb" end diff --git a/actionmailer/test/base_test.rb b/actionmailer/test/base_test.rb index cc7b90d7a4..5b0566a131 100644 --- a/actionmailer/test/base_test.rb +++ b/actionmailer/test/base_test.rb @@ -732,9 +732,9 @@ class BaseTest < ActiveSupport::TestCase def welcome ; mail ; end private - def add_special_header! - headers("X-Special-Header" => "Wow, so special") - end + def add_special_header! + headers("X-Special-Header" => "Wow, so special") + end end assert_equal("Wow, so special", BeforeActionMailer.welcome["X-Special-Header"].to_s) @@ -747,9 +747,9 @@ class BaseTest < ActiveSupport::TestCase def welcome ; mail ; end private - def add_special_header! - headers("X-Special-Header" => "Testing") - end + def add_special_header! + headers("X-Special-Header" => "Testing") + end end assert_equal("Testing", AfterActionMailer.welcome["X-Special-Header"].to_s) @@ -762,9 +762,9 @@ class BaseTest < ActiveSupport::TestCase def welcome ; mail ; end private - def add_inline_attachment! - attachments.inline["footer.jpg"] = "hey there" - end + def add_inline_attachment! + attachments.inline["footer.jpg"] = "hey there" + end end mail = DefaultInlineAttachmentMailer.welcome diff --git a/actionmailer/test/i18n_with_controller_test.rb b/actionmailer/test/i18n_with_controller_test.rb index 2f91bb6237..6370213043 100644 --- a/actionmailer/test/i18n_with_controller_test.rb +++ b/actionmailer/test/i18n_with_controller_test.rb @@ -68,10 +68,10 @@ class ActionMailerI18nWithControllerTest < ActionDispatch::IntegrationTest protected - def with_translation(locale, data) - I18n.backend.store_translations(locale, data) - yield - ensure - I18n.backend.reload! - end + def with_translation(locale, data) + I18n.backend.store_translations(locale, data) + yield + ensure + I18n.backend.reload! + end end diff --git a/actionmailer/test/mail_helper_test.rb b/actionmailer/test/mail_helper_test.rb index 2002d3b636..972629e477 100644 --- a/actionmailer/test/mail_helper_test.rb +++ b/actionmailer/test/mail_helper_test.rb @@ -67,10 +67,10 @@ The second protected - def mail_with_defaults(&block) - mail(to: "test@localhost", from: "tester@example.com", - subject: "using helpers", &block) - end + def mail_with_defaults(&block) + mail(to: "test@localhost", from: "tester@example.com", + subject: "using helpers", &block) + end end class MailerHelperTest < ActionMailer::TestCase diff --git a/actionmailer/test/mailers/asset_mailer.rb b/actionmailer/test/mailers/asset_mailer.rb index f54a50d00d..1cf15128d2 100644 --- a/actionmailer/test/mailers/asset_mailer.rb +++ b/actionmailer/test/mailers/asset_mailer.rb @@ -2,6 +2,6 @@ class AssetMailer < ActionMailer::Base self.mailer_name = "asset_mailer" def welcome - mail + mail end end diff --git a/actionmailer/test/mailers/proc_mailer.rb b/actionmailer/test/mailers/proc_mailer.rb index f5371fa674..40610812fb 100644 --- a/actionmailer/test/mailers/proc_mailer.rb +++ b/actionmailer/test/mailers/proc_mailer.rb @@ -10,8 +10,8 @@ class ProcMailer < ActionMailer::Base private - def give_a_greeting - "Thanks for signing up this afternoon" - end + def give_a_greeting + "Thanks for signing up this afternoon" + end end diff --git a/actionpack/lib/abstract_controller/helpers.rb b/actionpack/lib/abstract_controller/helpers.rb index e7f5863f1c..cb76898f59 100644 --- a/actionpack/lib/abstract_controller/helpers.rb +++ b/actionpack/lib/abstract_controller/helpers.rb @@ -177,19 +177,19 @@ module AbstractController # ==== Parameters # * module - The module to include into the current helper module # for the class - def add_template_helper(mod) - _helpers.module_eval { include mod } - end + def add_template_helper(mod) + _helpers.module_eval { include mod } + end - def default_helper_module! - module_name = name.sub(/Controller$/, "".freeze) - module_path = module_name.underscore - helper module_path - rescue LoadError => e - raise e unless e.is_missing? "helpers/#{module_path}_helper" - rescue NameError => e - raise e unless e.missing_name? "#{module_name}Helper" - end + def default_helper_module! + module_name = name.sub(/Controller$/, "".freeze) + module_path = module_name.underscore + helper module_path + rescue LoadError => e + raise e unless e.is_missing? "helpers/#{module_path}_helper" + rescue NameError => e + raise e unless e.missing_name? "#{module_name}Helper" + end end end end diff --git a/actionpack/lib/action_controller/metal.rb b/actionpack/lib/action_controller/metal.rb index 32ad746769..0364500944 100644 --- a/actionpack/lib/action_controller/metal.rb +++ b/actionpack/lib/action_controller/metal.rb @@ -34,29 +34,29 @@ module ActionController private - INCLUDE = ->(list, action) { list.include? action } - EXCLUDE = ->(list, action) { !list.include? action } - NULL = ->(list, action) { true } - - def build_middleware(klass, args, block) - options = args.extract_options! - only = Array(options.delete(:only)).map(&:to_s) - except = Array(options.delete(:except)).map(&:to_s) - args << options unless options.empty? - - strategy = NULL - list = nil - - if only.any? - strategy = INCLUDE - list = only - elsif except.any? - strategy = EXCLUDE - list = except - end + INCLUDE = ->(list, action) { list.include? action } + EXCLUDE = ->(list, action) { !list.include? action } + NULL = ->(list, action) { true } + + def build_middleware(klass, args, block) + options = args.extract_options! + only = Array(options.delete(:only)).map(&:to_s) + except = Array(options.delete(:except)).map(&:to_s) + args << options unless options.empty? + + strategy = NULL + list = nil + + if only.any? + strategy = INCLUDE + list = only + elsif except.any? + strategy = EXCLUDE + list = except + end - Middleware.new(get_class(klass), args, list, strategy, block) - end + Middleware.new(get_class(klass), args, list, strategy, block) + end end # ActionController::Metal is the simplest possible controller, providing a diff --git a/actionpack/lib/action_controller/metal/etag_with_template_digest.rb b/actionpack/lib/action_controller/metal/etag_with_template_digest.rb index e3a7c3b166..49b5f1090e 100644 --- a/actionpack/lib/action_controller/metal/etag_with_template_digest.rb +++ b/actionpack/lib/action_controller/metal/etag_with_template_digest.rb @@ -33,24 +33,24 @@ module ActionController end private - def determine_template_etag(options) - if template = pick_template_for_etag(options) - lookup_and_digest_template(template) + def determine_template_etag(options) + if template = pick_template_for_etag(options) + lookup_and_digest_template(template) + end end - end # Pick the template digest to include in the ETag. If the +:template+ option # is present, use the named template. If +:template+ is nil or absent, use # the default controller/action template. If +:template+ is false, omit the # template digest from the ETag. - def pick_template_for_etag(options) - unless options[:template] == false - options[:template] || "#{controller_path}/#{action_name}" + def pick_template_for_etag(options) + unless options[:template] == false + options[:template] || "#{controller_path}/#{action_name}" + end end - end - def lookup_and_digest_template(template) - ActionView::Digestor.digest name: template, finder: lookup_context - end + def lookup_and_digest_template(template) + ActionView::Digestor.digest name: template, finder: lookup_context + end end end diff --git a/actionpack/lib/action_controller/metal/head.rb b/actionpack/lib/action_controller/metal/head.rb index d4344dc7b3..97306b5265 100644 --- a/actionpack/lib/action_controller/metal/head.rb +++ b/actionpack/lib/action_controller/metal/head.rb @@ -50,15 +50,15 @@ module ActionController end private - def include_content?(status) - case status - when 100..199 - false - when 204, 205, 304 - false - else - true + def include_content?(status) + case status + when 100..199 + false + when 204, 205, 304 + false + else + true + end end - end end end diff --git a/actionpack/lib/action_controller/metal/helpers.rb b/actionpack/lib/action_controller/metal/helpers.rb index 295f0cb66f..7257bbfa95 100644 --- a/actionpack/lib/action_controller/metal/helpers.rb +++ b/actionpack/lib/action_controller/metal/helpers.rb @@ -109,9 +109,9 @@ module ActionController private # Extract helper names from files in app/helpers/**/*_helper.rb - def all_application_helpers - all_helpers_from_path(helpers_path) - end + def all_application_helpers + all_helpers_from_path(helpers_path) + end end # Provides a proxy to access helper methods from outside the view. diff --git a/actionpack/lib/action_controller/metal/implicit_render.rb b/actionpack/lib/action_controller/metal/implicit_render.rb index b76291d927..c4a1b00a54 100644 --- a/actionpack/lib/action_controller/metal/implicit_render.rb +++ b/actionpack/lib/action_controller/metal/implicit_render.rb @@ -62,7 +62,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/live.rb b/actionpack/lib/action_controller/metal/live.rb index 1839230ffb..0f74ec25ff 100644 --- a/actionpack/lib/action_controller/metal/live.rb +++ b/actionpack/lib/action_controller/metal/live.rb @@ -215,18 +215,18 @@ module ActionController class Response < ActionDispatch::Response #:nodoc: all private - def before_committed - super - jar = request.cookie_jar - # The response can be committed multiple times - jar.write self unless committed? - end + def before_committed + super + jar = request.cookie_jar + # The response can be committed multiple times + jar.write self unless committed? + end - def build_buffer(response, body) - buf = Live::Buffer.new response - body.each { |part| buf.write part } - buf - end + def build_buffer(response, body) + buf = Live::Buffer.new response + body.each { |part| buf.write part } + buf + end end def process(name) diff --git a/actionpack/lib/action_controller/metal/params_wrapper.rb b/actionpack/lib/action_controller/metal/params_wrapper.rb index e52a3cd211..745f449a05 100644 --- a/actionpack/lib/action_controller/metal/params_wrapper.rb +++ b/actionpack/lib/action_controller/metal/params_wrapper.rb @@ -135,23 +135,23 @@ module ActionController # # This method also does namespace lookup. Foo::Bar::UsersController will # try to find Foo::Bar::User, Foo::User and finally User. - def _default_wrap_model #:nodoc: - return nil if klass.anonymous? - model_name = klass.name.sub(/Controller$/, "").classify - - begin - if model_klass = model_name.safe_constantize - model_klass - else - namespaces = model_name.split("::") - namespaces.delete_at(-2) - break if namespaces.last == model_name - model_name = namespaces.join("::") - end - end until model_klass + def _default_wrap_model #:nodoc: + return nil if klass.anonymous? + model_name = klass.name.sub(/Controller$/, "").classify + + begin + if model_klass = model_name.safe_constantize + model_klass + else + namespaces = model_name.split("::") + namespaces.delete_at(-2) + break if namespaces.last == model_name + model_name = namespaces.join("::") + end + end until model_klass - model_klass - end + model_klass + end end included do diff --git a/actionpack/lib/action_controller/metal/rendering.rb b/actionpack/lib/action_controller/metal/rendering.rb index d99486f29b..41b166b346 100644 --- a/actionpack/lib/action_controller/metal/rendering.rb +++ b/actionpack/lib/action_controller/metal/rendering.rb @@ -54,37 +54,37 @@ module ActionController private - def _render_in_priorities(options) - RENDER_FORMATS_IN_PRIORITY.each do |format| - return options[format] if options.key?(format) - end + def _render_in_priorities(options) + RENDER_FORMATS_IN_PRIORITY.each do |format| + return options[format] if options.key?(format) + end - nil - end + nil + end - def _set_html_content_type - self.content_type = Mime[:html].to_s - end + def _set_html_content_type + self.content_type = Mime[:html].to_s + end - def _set_rendered_content_type(format) - unless response.content_type - self.content_type = format.to_s + def _set_rendered_content_type(format) + unless response.content_type + self.content_type = format.to_s + end end - end # Normalize arguments by catching blocks and setting them on :update. - def _normalize_args(action=nil, options={}, &blk) #:nodoc: - options = super - options[:update] = blk if block_given? - options - end + def _normalize_args(action=nil, options={}, &blk) #:nodoc: + options = super + options[:update] = blk if block_given? + options + end # Normalize both text and status options. - def _normalize_options(options) #:nodoc: - _normalize_text(options) + def _normalize_options(options) #:nodoc: + _normalize_text(options) - if options[:text] - ActiveSupport::Deprecation.warn <<-WARNING.squish + if options[:text] + ActiveSupport::Deprecation.warn <<-WARNING.squish `render :text` is deprecated because it does not actually render a `text/plain` response. Switch to `render plain: 'plain text'` to render as `text/plain`, `render html: 'HTML'` to @@ -92,41 +92,41 @@ module ActionController behavior and render with the default Content-Type, which is `text/plain`. WARNING - end + end - if options[:html] - options[:html] = ERB::Util.html_escape(options[:html]) - end + if options[:html] + options[:html] = ERB::Util.html_escape(options[:html]) + end - if options.delete(:nothing) - ActiveSupport::Deprecation.warn("`:nothing` option is deprecated and will be removed in Rails 5.1. Use `head` method to respond with empty response body.") - options[:body] = nil - end + if options.delete(:nothing) + ActiveSupport::Deprecation.warn("`:nothing` option is deprecated and will be removed in Rails 5.1. Use `head` method to respond with empty response body.") + options[:body] = nil + end - if options[:status] - options[:status] = Rack::Utils.status_code(options[:status]) - end + if options[:status] + options[:status] = Rack::Utils.status_code(options[:status]) + end - super - end + super + end - def _normalize_text(options) - RENDER_FORMATS_IN_PRIORITY.each do |format| - if options.key?(format) && options[format].respond_to?(:to_text) - options[format] = options[format].to_text + def _normalize_text(options) + RENDER_FORMATS_IN_PRIORITY.each do |format| + if options.key?(format) && options[format].respond_to?(:to_text) + options[format] = options[format].to_text + end end end - end # Process controller specific options, as status, content-type and location. - def _process_options(options) #:nodoc: - status, content_type, location = options.values_at(:status, :content_type, :location) + def _process_options(options) #:nodoc: + status, content_type, location = options.values_at(:status, :content_type, :location) - self.status = status if status - self.content_type = content_type if content_type - self.headers["Location"] = url_for(location) if location + self.status = status if status + self.content_type = content_type if content_type + self.headers["Location"] = url_for(location) if location - super - end + super + end end end diff --git a/actionpack/lib/action_controller/metal/request_forgery_protection.rb b/actionpack/lib/action_controller/metal/request_forgery_protection.rb index a6e24ded9e..3d3c121280 100644 --- a/actionpack/lib/action_controller/metal/request_forgery_protection.rb +++ b/actionpack/lib/action_controller/metal/request_forgery_protection.rb @@ -130,11 +130,11 @@ module ActionController #:nodoc: private - def protection_method_class(name) - ActionController::RequestForgeryProtection::ProtectionMethods.const_get(name.to_s.classify) - rescue NameError - raise ArgumentError, "Invalid request forgery protection method, use :null_session, :exception, or :reset_session" - end + def protection_method_class(name) + ActionController::RequestForgeryProtection::ProtectionMethods.const_get(name.to_s.classify) + rescue NameError + raise ArgumentError, "Invalid request forgery protection method, use :null_session, :exception, or :reset_session" + end end module ProtectionMethods @@ -154,26 +154,26 @@ module ActionController #:nodoc: protected - class NullSessionHash < Rack::Session::Abstract::SessionHash #:nodoc: - def initialize(req) - super(nil, req) - @data = {} - @loaded = true - end + class NullSessionHash < Rack::Session::Abstract::SessionHash #:nodoc: + def initialize(req) + super(nil, req) + @data = {} + @loaded = true + end - # no-op - def destroy; end + # no-op + def destroy; end - def exists? - true + def exists? + true + end end - end - class NullCookieJar < ActionDispatch::Cookies::CookieJar #:nodoc: - def write(*) - # nothing + class NullCookieJar < ActionDispatch::Cookies::CookieJar #:nodoc: + def write(*) + # nothing + end end - end end class ResetSession diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb index 42c2e111b1..506548db5d 100644 --- a/actionpack/lib/action_controller/test_case.rb +++ b/actionpack/lib/action_controller/test_case.rb @@ -152,9 +152,9 @@ module ActionController private - def params_parsers - super.merge @custom_param_parsers - end + def params_parsers + super.merge @custom_param_parsers + end end class LiveTestResponse < Live::Response @@ -615,37 +615,37 @@ module ActionController private - def scrub_env!(env) - env.delete_if { |k, v| k =~ /^(action_dispatch|rack)\.request/ } - env.delete_if { |k, v| k =~ /^action_dispatch\.rescue/ } - env.delete "action_dispatch.request.query_parameters" - env.delete "action_dispatch.request.request_parameters" - env["rack.input"] = StringIO.new - env - end + def scrub_env!(env) + env.delete_if { |k, v| k =~ /^(action_dispatch|rack)\.request/ } + env.delete_if { |k, v| k =~ /^action_dispatch\.rescue/ } + env.delete "action_dispatch.request.query_parameters" + env.delete "action_dispatch.request.request_parameters" + env["rack.input"] = StringIO.new + env + end - def process_with_kwargs(http_method, action, *args) - if kwarg_request?(args) - args.first.merge!(method: http_method) - process(action, *args) - else - non_kwarg_request_warning if args.any? + def process_with_kwargs(http_method, action, *args) + if kwarg_request?(args) + args.first.merge!(method: http_method) + process(action, *args) + else + non_kwarg_request_warning if args.any? - args = args.unshift(http_method) - process(action, *args) + args = args.unshift(http_method) + process(action, *args) + end end - end - REQUEST_KWARGS = %i(params session flash method body xhr) - def kwarg_request?(args) - args[0].respond_to?(:keys) && ( - (args[0].key?(:format) && args[0].keys.size == 1) || - args[0].keys.any? { |k| REQUEST_KWARGS.include?(k) } - ) - end + REQUEST_KWARGS = %i(params session flash method body xhr) + def kwarg_request?(args) + args[0].respond_to?(:keys) && ( + (args[0].key?(:format) && args[0].keys.size == 1) || + args[0].keys.any? { |k| REQUEST_KWARGS.include?(k) } + ) + end - def non_kwarg_request_warning - ActiveSupport::Deprecation.warn(<<-MSG.strip_heredoc) + def non_kwarg_request_warning + ActiveSupport::Deprecation.warn(<<-MSG.strip_heredoc) ActionController::TestCase HTTP request methods will accept only keyword arguments in future Rails versions. @@ -654,26 +654,26 @@ module ActionController get :show, params: { id: 1 }, session: { user_id: 1 } process :update, method: :post, params: { id: 1 } MSG - end + end - def document_root_element - html_document.root - end + def document_root_element + html_document.root + end - def check_required_ivars - # Sanity check for required instance variables so we can give an - # understandable error message. - [:@routes, :@controller, :@request, :@response].each do |iv_name| - if !instance_variable_defined?(iv_name) || instance_variable_get(iv_name).nil? - raise "#{iv_name} is nil: make sure you set it in your test's setup method." + def check_required_ivars + # Sanity check for required instance variables so we can give an + # understandable error message. + [:@routes, :@controller, :@request, :@response].each do |iv_name| + if !instance_variable_defined?(iv_name) || instance_variable_get(iv_name).nil? + raise "#{iv_name} is nil: make sure you set it in your test's setup method." + end end end - end - def html_format?(parameters) - return true unless parameters.key?(:format) - Mime.fetch(parameters[:format]) { Mime["html"] }.html? - end + def html_format?(parameters) + return true unless parameters.key?(:format) + Mime.fetch(parameters[:format]) { Mime["html"] }.html? + end end include Behavior diff --git a/actionpack/lib/action_dispatch/http/headers.rb b/actionpack/lib/action_dispatch/http/headers.rb index 0b0c9e9590..91c45767ef 100644 --- a/actionpack/lib/action_dispatch/http/headers.rb +++ b/actionpack/lib/action_dispatch/http/headers.rb @@ -117,14 +117,14 @@ module ActionDispatch # Converts an HTTP header name to an environment variable name if it is # not contained within the headers hash. - def env_name(key) - key = key.to_s - if key =~ HTTP_HEADER - key = key.upcase.tr("-", "_") - key = "HTTP_" + key unless CGI_VARIABLES.include?(key) + def env_name(key) + key = key.to_s + if key =~ HTTP_HEADER + key = key.upcase.tr("-", "_") + key = "HTTP_" + key unless CGI_VARIABLES.include?(key) + end + key end - key - end end end end diff --git a/actionpack/lib/action_dispatch/http/mime_negotiation.rb b/actionpack/lib/action_dispatch/http/mime_negotiation.rb index d8ee9c6def..d0c9413efa 100644 --- a/actionpack/lib/action_dispatch/http/mime_negotiation.rb +++ b/actionpack/lib/action_dispatch/http/mime_negotiation.rb @@ -152,23 +152,23 @@ module ActionDispatch protected - BROWSER_LIKE_ACCEPTS = /,\s*\*\/\*|\*\/\*\s*,/ + BROWSER_LIKE_ACCEPTS = /,\s*\*\/\*|\*\/\*\s*,/ - def valid_accept_header - (xhr? && (accept.present? || content_mime_type)) || - (accept.present? && accept !~ BROWSER_LIKE_ACCEPTS) - end + def valid_accept_header + (xhr? && (accept.present? || content_mime_type)) || + (accept.present? && accept !~ BROWSER_LIKE_ACCEPTS) + end - def use_accept_header - !self.class.ignore_accept_header - end + def use_accept_header + !self.class.ignore_accept_header + end - def format_from_path_extension - path = get_header("action_dispatch.original_path") || get_header("PATH_INFO") - if match = path && path.match(/\.(\w+)\z/) - Mime[match.captures.first] + def format_from_path_extension + path = get_header("action_dispatch.original_path") || get_header("PATH_INFO") + if match = path && path.match(/\.(\w+)\z/) + Mime[match.captures.first] + end end - end end end end diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb index 3e6cfeb3d0..b9121a577c 100644 --- a/actionpack/lib/action_dispatch/http/mime_type.rb +++ b/actionpack/lib/action_dispatch/http/mime_type.rb @@ -306,24 +306,24 @@ module Mime protected - attr_reader :string, :synonyms + attr_reader :string, :synonyms private - def to_ary; end - def to_a; end + def to_ary; end + def to_a; end - def method_missing(method, *args) - if method.to_s.ends_with? "?" - method[0..-2].downcase.to_sym == to_sym - else - super + def method_missing(method, *args) + if method.to_s.ends_with? "?" + method[0..-2].downcase.to_sym == to_sym + else + super + end end - end - def respond_to_missing?(method, include_private = false) #:nodoc: - method.to_s.ends_with? "?" - end + def respond_to_missing?(method, include_private = false) #:nodoc: + method.to_s.ends_with? "?" + end end class AllType < Type @@ -356,9 +356,9 @@ module Mime end private - def method_missing(method, *args) - false if method.to_s.ends_with? "?" - end + def method_missing(method, *args) + false if method.to_s.ends_with? "?" + end end end diff --git a/actionpack/lib/action_dispatch/http/parameters.rb b/actionpack/lib/action_dispatch/http/parameters.rb index 4850ca4404..f25e50f9f3 100644 --- a/actionpack/lib/action_dispatch/http/parameters.rb +++ b/actionpack/lib/action_dispatch/http/parameters.rb @@ -64,24 +64,24 @@ module ActionDispatch private - def parse_formatted_parameters(parsers) - return yield if content_length.zero? || content_mime_type.nil? + def parse_formatted_parameters(parsers) + return yield if content_length.zero? || content_mime_type.nil? - strategy = parsers.fetch(content_mime_type.symbol) { return yield } + strategy = parsers.fetch(content_mime_type.symbol) { return yield } - begin - strategy.call(raw_post) - rescue # JSON or Ruby code block errors - my_logger = logger || ActiveSupport::Logger.new($stderr) - my_logger.debug "Error occurred while parsing request parameters.\nContents:\n\n#{raw_post}" + begin + strategy.call(raw_post) + rescue # JSON or Ruby code block errors + my_logger = logger || ActiveSupport::Logger.new($stderr) + my_logger.debug "Error occurred while parsing request parameters.\nContents:\n\n#{raw_post}" - raise ParamsParser::ParseError + raise ParamsParser::ParseError + end end - end - def params_parsers - ActionDispatch::Request.parameter_parsers - end + def params_parsers + ActionDispatch::Request.parameter_parsers + end end end end diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb index 6483bb3804..9788431943 100644 --- a/actionpack/lib/action_dispatch/http/response.rb +++ b/actionpack/lib/action_dispatch/http/response.rb @@ -104,7 +104,7 @@ module ActionDispatch # :nodoc: def body @str_body ||= begin buf = "" - each { |chunk| buf << chunk } + each { |chunk| buf << chunk } buf end end diff --git a/actionpack/lib/action_dispatch/journey/nfa/dot.rb b/actionpack/lib/action_dispatch/journey/nfa/dot.rb index 7063b44bb5..0cd71b726a 100644 --- a/actionpack/lib/action_dispatch/journey/nfa/dot.rb +++ b/actionpack/lib/action_dispatch/journey/nfa/dot.rb @@ -18,7 +18,7 @@ module ActionDispatch # (memos || []).map { |v| " #{k} -> #{v.object_id};" } #}.uniq - <<-eodot + <<-eodot digraph nfa { rankdir=LR; node [shape = doublecircle]; diff --git a/actionpack/lib/action_dispatch/journey/parser.rb b/actionpack/lib/action_dispatch/journey/parser.rb index 65805cd51b..9b4707369b 100644 --- a/actionpack/lib/action_dispatch/journey/parser.rb +++ b/actionpack/lib/action_dispatch/journey/parser.rb @@ -13,133 +13,133 @@ module ActionDispatch class Parser < Racc::Parser ##### State transition tables begin ### -racc_action_table = [ - 13, 15, 14, 7, 21, 16, 8, 19, 13, 15, - 14, 7, 17, 16, 8, 13, 15, 14, 7, 24, - 16, 8, 13, 15, 14, 7, 19, 16, 8 ] - -racc_action_check = [ - 2, 2, 2, 2, 17, 2, 2, 2, 0, 0, - 0, 0, 1, 0, 0, 19, 19, 19, 19, 20, - 19, 19, 7, 7, 7, 7, 22, 7, 7 ] - -racc_action_pointer = [ - 6, 12, -2, nil, nil, nil, nil, 20, nil, nil, - nil, nil, nil, nil, nil, nil, nil, 4, nil, 13, - 13, nil, 17, nil, nil ] - -racc_action_default = [ - -19, -19, -2, -3, -4, -5, -6, -19, -10, -11, - -12, -13, -14, -15, -16, -17, -18, -19, -1, -19, - -19, 25, -8, -9, -7 ] - -racc_goto_table = [ - 1, 22, 18, 23, nil, nil, nil, 20 ] - -racc_goto_check = [ - 1, 2, 1, 3, nil, nil, nil, 1 ] - -racc_goto_pointer = [ - nil, 0, -18, -16, nil, nil, nil, nil, nil, nil, - nil ] - -racc_goto_default = [ - nil, nil, 2, 3, 4, 5, 6, 9, 10, 11, - 12 ] - -racc_reduce_table = [ - 0, 0, :racc_error, - 2, 11, :_reduce_1, - 1, 11, :_reduce_2, - 1, 11, :_reduce_none, - 1, 12, :_reduce_none, - 1, 12, :_reduce_none, - 1, 12, :_reduce_none, - 3, 15, :_reduce_7, - 3, 13, :_reduce_8, - 3, 13, :_reduce_9, - 1, 16, :_reduce_10, - 1, 14, :_reduce_none, - 1, 14, :_reduce_none, - 1, 14, :_reduce_none, - 1, 14, :_reduce_none, - 1, 19, :_reduce_15, - 1, 17, :_reduce_16, - 1, 18, :_reduce_17, - 1, 20, :_reduce_18 ] - -racc_reduce_n = 19 - -racc_shift_n = 25 - -racc_token_table = { - false => 0, - :error => 1, - :SLASH => 2, - :LITERAL => 3, - :SYMBOL => 4, - :LPAREN => 5, - :RPAREN => 6, - :DOT => 7, - :STAR => 8, - :OR => 9 } - -racc_nt_base = 10 - -racc_use_result_var = false - -Racc_arg = [ - racc_action_table, - racc_action_check, - racc_action_default, - racc_action_pointer, - racc_goto_table, - racc_goto_check, - racc_goto_default, - racc_goto_pointer, - racc_nt_base, - racc_reduce_table, - racc_token_table, - racc_shift_n, - racc_reduce_n, - racc_use_result_var ] - -Racc_token_to_s_table = [ - "$end", - "error", - "SLASH", - "LITERAL", - "SYMBOL", - "LPAREN", - "RPAREN", - "DOT", - "STAR", - "OR", - "$start", - "expressions", - "expression", - "or", - "terminal", - "group", - "star", - "symbol", - "literal", - "slash", - "dot" ] - -Racc_debug_parser = false + racc_action_table = [ + 13, 15, 14, 7, 21, 16, 8, 19, 13, 15, + 14, 7, 17, 16, 8, 13, 15, 14, 7, 24, + 16, 8, 13, 15, 14, 7, 19, 16, 8 ] + + racc_action_check = [ + 2, 2, 2, 2, 17, 2, 2, 2, 0, 0, + 0, 0, 1, 0, 0, 19, 19, 19, 19, 20, + 19, 19, 7, 7, 7, 7, 22, 7, 7 ] + + racc_action_pointer = [ + 6, 12, -2, nil, nil, nil, nil, 20, nil, nil, + nil, nil, nil, nil, nil, nil, nil, 4, nil, 13, + 13, nil, 17, nil, nil ] + + racc_action_default = [ + -19, -19, -2, -3, -4, -5, -6, -19, -10, -11, + -12, -13, -14, -15, -16, -17, -18, -19, -1, -19, + -19, 25, -8, -9, -7 ] + + racc_goto_table = [ + 1, 22, 18, 23, nil, nil, nil, 20 ] + + racc_goto_check = [ + 1, 2, 1, 3, nil, nil, nil, 1 ] + + racc_goto_pointer = [ + nil, 0, -18, -16, nil, nil, nil, nil, nil, nil, + nil ] + + racc_goto_default = [ + nil, nil, 2, 3, 4, 5, 6, 9, 10, 11, + 12 ] + + racc_reduce_table = [ + 0, 0, :racc_error, + 2, 11, :_reduce_1, + 1, 11, :_reduce_2, + 1, 11, :_reduce_none, + 1, 12, :_reduce_none, + 1, 12, :_reduce_none, + 1, 12, :_reduce_none, + 3, 15, :_reduce_7, + 3, 13, :_reduce_8, + 3, 13, :_reduce_9, + 1, 16, :_reduce_10, + 1, 14, :_reduce_none, + 1, 14, :_reduce_none, + 1, 14, :_reduce_none, + 1, 14, :_reduce_none, + 1, 19, :_reduce_15, + 1, 17, :_reduce_16, + 1, 18, :_reduce_17, + 1, 20, :_reduce_18 ] + + racc_reduce_n = 19 + + racc_shift_n = 25 + + racc_token_table = { + false => 0, + :error => 1, + :SLASH => 2, + :LITERAL => 3, + :SYMBOL => 4, + :LPAREN => 5, + :RPAREN => 6, + :DOT => 7, + :STAR => 8, + :OR => 9 } + + racc_nt_base = 10 + + racc_use_result_var = false + + Racc_arg = [ + racc_action_table, + racc_action_check, + racc_action_default, + racc_action_pointer, + racc_goto_table, + racc_goto_check, + racc_goto_default, + racc_goto_pointer, + racc_nt_base, + racc_reduce_table, + racc_token_table, + racc_shift_n, + racc_reduce_n, + racc_use_result_var ] + + Racc_token_to_s_table = [ + "$end", + "error", + "SLASH", + "LITERAL", + "SYMBOL", + "LPAREN", + "RPAREN", + "DOT", + "STAR", + "OR", + "$start", + "expressions", + "expression", + "or", + "terminal", + "group", + "star", + "symbol", + "literal", + "slash", + "dot" ] + + Racc_debug_parser = false ##### State transition tables end ##### # reduce 0 omitted -def _reduce_1(val, _values) - Cat.new(val.first, val.last) -end + def _reduce_1(val, _values) + Cat.new(val.first, val.last) + end -def _reduce_2(val, _values) - val.first -end + def _reduce_2(val, _values) + val.first + end # reduce 3 omitted @@ -149,21 +149,21 @@ end # reduce 6 omitted -def _reduce_7(val, _values) - Group.new(val[1]) -end + def _reduce_7(val, _values) + Group.new(val[1]) + end -def _reduce_8(val, _values) - Or.new([val.first, val.last]) -end + def _reduce_8(val, _values) + Or.new([val.first, val.last]) + end -def _reduce_9(val, _values) - Or.new([val.first, val.last]) -end + def _reduce_9(val, _values) + Or.new([val.first, val.last]) + end -def _reduce_10(val, _values) - Star.new(Symbol.new(val.last)) -end + def _reduce_10(val, _values) + Star.new(Symbol.new(val.last)) + end # reduce 11 omitted @@ -173,25 +173,25 @@ end # reduce 14 omitted -def _reduce_15(val, _values) - Slash.new("/") -end + def _reduce_15(val, _values) + Slash.new("/") + end -def _reduce_16(val, _values) - Symbol.new(val.first) -end + def _reduce_16(val, _values) + Symbol.new(val.first) + end -def _reduce_17(val, _values) - Literal.new(val.first) -end + def _reduce_17(val, _values) + Literal.new(val.first) + end -def _reduce_18(val, _values) - Dot.new(val.first) -end + def _reduce_18(val, _values) + Dot.new(val.first) + end -def _reduce_none(val, _values) - val[0] -end + def _reduce_none(val, _values) + val[0] + end end # class Parser end # module Journey diff --git a/actionpack/lib/action_dispatch/journey/route.rb b/actionpack/lib/action_dispatch/journey/route.rb index b6d9f4737a..f437897522 100644 --- a/actionpack/lib/action_dispatch/journey/route.rb +++ b/actionpack/lib/action_dispatch/journey/route.rb @@ -168,13 +168,13 @@ module ActionDispatch end private - def verbs - @request_method_match.map(&:verb) - end + def verbs + @request_method_match.map(&:verb) + end - def match_verb(request) - @request_method_match.any? { |m| m.call request } - end + def match_verb(request) + @request_method_match.any? { |m| m.call request } + end end end end diff --git a/actionpack/lib/action_dispatch/journey/visitors.rb b/actionpack/lib/action_dispatch/journey/visitors.rb index 819accd44a..8476c5d079 100644 --- a/actionpack/lib/action_dispatch/journey/visitors.rb +++ b/actionpack/lib/action_dispatch/journey/visitors.rb @@ -166,28 +166,28 @@ module ActionDispatch class String < FunctionalVisitor # :nodoc: private - def binary(node, seed) - visit(node.right, visit(node.left, seed)) - end + def binary(node, seed) + visit(node.right, visit(node.left, seed)) + end - def nary(node, seed) - last_child = node.children.last - node.children.inject(seed) { |s, c| - string = visit(c, s) - string << "|".freeze unless last_child == c - string - } - end + def nary(node, seed) + last_child = node.children.last + node.children.inject(seed) { |s, c| + string = visit(c, s) + string << "|".freeze unless last_child == c + string + } + end - def terminal(node, seed) - seed + node.left - end + def terminal(node, seed) + seed + node.left + end - def visit_GROUP(node, seed) - visit(node.left, seed << "(".freeze) << ")".freeze - end + def visit_GROUP(node, seed) + visit(node.left, seed << "(".freeze) << ")".freeze + end - INSTANCE = new + INSTANCE = new end class Dot < FunctionalVisitor # :nodoc: diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb index ddae0c5a8e..bebf220488 100644 --- a/actionpack/lib/action_dispatch/middleware/cookies.rb +++ b/actionpack/lib/action_dispatch/middleware/cookies.rb @@ -237,9 +237,9 @@ module ActionDispatch private - def upgrade_legacy_signed_cookies? - request.secret_token.present? && request.secret_key_base.present? - end + def upgrade_legacy_signed_cookies? + request.secret_token.present? && request.secret_key_base.present? + end end # Passing the ActiveSupport::MessageEncryptor::NullSerializer downstream @@ -420,26 +420,26 @@ module ActionDispatch private - def escape(string) - ::Rack::Utils.escape(string) - end + def escape(string) + ::Rack::Utils.escape(string) + end - def make_set_cookie_header(header) - header = @set_cookies.inject(header) { |m, (k, v)| - if write_cookie?(v) - ::Rack::Utils.add_cookie_to_header(m, k, v) - else - m - end - } - @delete_cookies.inject(header) { |m, (k, v)| - ::Rack::Utils.add_remove_cookie_to_header(m, k, v) - } - end + def make_set_cookie_header(header) + header = @set_cookies.inject(header) { |m, (k, v)| + if write_cookie?(v) + ::Rack::Utils.add_cookie_to_header(m, k, v) + else + m + end + } + @delete_cookies.inject(header) { |m, (k, v)| + ::Rack::Utils.add_remove_cookie_to_header(m, k, v) + } + end - def write_cookie?(cookie) - request.ssl? || !cookie[:secure] || always_write_cookie - end + def write_cookie?(cookie) + request.ssl? || !cookie[:secure] || always_write_cookie + end end class AbstractCookieJar # :nodoc: diff --git a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb index 83c095b616..d585e7042e 100644 --- a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb @@ -69,129 +69,129 @@ module ActionDispatch private - def render_exception(request, exception) - backtrace_cleaner = request.get_header("action_dispatch.backtrace_cleaner") - wrapper = ExceptionWrapper.new(backtrace_cleaner, exception) - log_error(request, wrapper) - - if request.get_header("action_dispatch.show_detailed_exceptions") - content_type = request.formats.first - - if api_request?(content_type) - render_for_api_request(content_type, wrapper) + def render_exception(request, exception) + backtrace_cleaner = request.get_header("action_dispatch.backtrace_cleaner") + wrapper = ExceptionWrapper.new(backtrace_cleaner, exception) + log_error(request, wrapper) + + if request.get_header("action_dispatch.show_detailed_exceptions") + content_type = request.formats.first + + if api_request?(content_type) + render_for_api_request(content_type, wrapper) + else + render_for_browser_request(request, wrapper) + end else - render_for_browser_request(request, wrapper) + raise exception end - else - raise exception end - end - def render_for_browser_request(request, wrapper) - template = create_template(request, wrapper) - file = "rescues/#{wrapper.rescue_template}" + def render_for_browser_request(request, wrapper) + template = create_template(request, wrapper) + file = "rescues/#{wrapper.rescue_template}" - if request.xhr? - body = template.render(template: file, layout: false, formats: [:text]) - format = "text/plain" - else - body = template.render(template: file, layout: "rescues/layout") - format = "text/html" + if request.xhr? + body = template.render(template: file, layout: false, formats: [:text]) + format = "text/plain" + else + body = template.render(template: file, layout: "rescues/layout") + format = "text/html" + end + render(wrapper.status_code, body, format) end - render(wrapper.status_code, body, format) - end - def render_for_api_request(content_type, wrapper) - body = { - status: wrapper.status_code, - error: Rack::Utils::HTTP_STATUS_CODES.fetch( - wrapper.status_code, - Rack::Utils::HTTP_STATUS_CODES[500] - ), - exception: wrapper.exception.inspect, - traces: wrapper.traces - } - - to_format = "to_#{content_type.to_sym}" + def render_for_api_request(content_type, wrapper) + body = { + status: wrapper.status_code, + error: Rack::Utils::HTTP_STATUS_CODES.fetch( + wrapper.status_code, + Rack::Utils::HTTP_STATUS_CODES[500] + ), + exception: wrapper.exception.inspect, + traces: wrapper.traces + } + + to_format = "to_#{content_type.to_sym}" + + if content_type && body.respond_to?(to_format) + formatted_body = body.public_send(to_format) + format = content_type + else + formatted_body = body.to_json + format = Mime[:json] + end - if content_type && body.respond_to?(to_format) - formatted_body = body.public_send(to_format) - format = content_type - else - formatted_body = body.to_json - format = Mime[:json] + render(wrapper.status_code, formatted_body, format) end - render(wrapper.status_code, formatted_body, format) - end + def create_template(request, wrapper) + traces = wrapper.traces - def create_template(request, wrapper) - traces = wrapper.traces + trace_to_show = "Application Trace" + if traces[trace_to_show].empty? && wrapper.rescue_template != "routing_error" + trace_to_show = "Full Trace" + end - trace_to_show = "Application Trace" - if traces[trace_to_show].empty? && wrapper.rescue_template != "routing_error" - trace_to_show = "Full Trace" - end + if source_to_show = traces[trace_to_show].first + source_to_show_id = source_to_show[:id] + end - if source_to_show = traces[trace_to_show].first - source_to_show_id = source_to_show[:id] + DebugView.new([RESCUES_TEMPLATE_PATH], + request: request, + exception: wrapper.exception, + traces: traces, + show_source_idx: source_to_show_id, + trace_to_show: trace_to_show, + routes_inspector: routes_inspector(wrapper.exception), + source_extracts: wrapper.source_extracts, + line_number: wrapper.line_number, + file: wrapper.file + ) end - DebugView.new([RESCUES_TEMPLATE_PATH], - request: request, - exception: wrapper.exception, - traces: traces, - show_source_idx: source_to_show_id, - trace_to_show: trace_to_show, - routes_inspector: routes_inspector(wrapper.exception), - source_extracts: wrapper.source_extracts, - line_number: wrapper.line_number, - file: wrapper.file - ) - end - - def render(status, body, format) - [status, {"Content-Type" => "#{format}; charset=#{Response.default_charset}", "Content-Length" => body.bytesize.to_s}, [body]] - end + def render(status, body, format) + [status, {"Content-Type" => "#{format}; charset=#{Response.default_charset}", "Content-Length" => body.bytesize.to_s}, [body]] + end - def log_error(request, wrapper) - logger = logger(request) - return unless logger + def log_error(request, wrapper) + logger = logger(request) + return unless logger - exception = wrapper.exception + exception = wrapper.exception - trace = wrapper.application_trace - trace = wrapper.framework_trace if trace.empty? + trace = wrapper.application_trace + trace = wrapper.framework_trace if trace.empty? - ActiveSupport::Deprecation.silence do - logger.fatal " " - logger.fatal "#{exception.class} (#{exception.message}):" - log_array logger, exception.annoted_source_code if exception.respond_to?(:annoted_source_code) - logger.fatal " " - log_array logger, trace + ActiveSupport::Deprecation.silence do + logger.fatal " " + logger.fatal "#{exception.class} (#{exception.message}):" + log_array logger, exception.annoted_source_code if exception.respond_to?(:annoted_source_code) + logger.fatal " " + log_array logger, trace + end end - end - def log_array(logger, array) - array.map { |line| logger.fatal line } - end + def log_array(logger, array) + array.map { |line| logger.fatal line } + end - def logger(request) - request.logger || ActionView::Base.logger || stderr_logger - end + def logger(request) + request.logger || ActionView::Base.logger || stderr_logger + end - def stderr_logger - @stderr_logger ||= ActiveSupport::Logger.new($stderr) - end + def stderr_logger + @stderr_logger ||= ActiveSupport::Logger.new($stderr) + end - def routes_inspector(exception) - if @routes_app.respond_to?(:routes) && (exception.is_a?(ActionController::RoutingError) || exception.is_a?(ActionView::Template::Error)) - ActionDispatch::Routing::RoutesInspector.new(@routes_app.routes.routes) + def routes_inspector(exception) + if @routes_app.respond_to?(:routes) && (exception.is_a?(ActionController::RoutingError) || exception.is_a?(ActionView::Template::Error)) + ActionDispatch::Routing::RoutesInspector.new(@routes_app.routes.routes) + end end - end - def api_request?(content_type) - @response_format == :api && !content_type.html? - end + def api_request?(content_type) + @response_format == :api && !content_type.html? + end end end diff --git a/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb index 5570c229ef..9b44c4483e 100644 --- a/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb +++ b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb @@ -100,49 +100,49 @@ module ActionDispatch private - def backtrace - Array(@exception.backtrace) - end + def backtrace + Array(@exception.backtrace) + end - def original_exception(exception) - if @@rescue_responses.has_key?(exception.cause.class.name) - exception.cause - else - exception + def original_exception(exception) + if @@rescue_responses.has_key?(exception.cause.class.name) + exception.cause + else + exception + end end - end - def clean_backtrace(*args) - if backtrace_cleaner - backtrace_cleaner.clean(backtrace, *args) - else - backtrace + def clean_backtrace(*args) + if backtrace_cleaner + backtrace_cleaner.clean(backtrace, *args) + else + backtrace + end end - end - def source_fragment(path, line) - return unless Rails.respond_to?(:root) && Rails.root - full_path = Rails.root.join(path) - if File.exist?(full_path) - File.open(full_path, "r") do |file| - start = [line - 3, 0].max - lines = file.each_line.drop(start).take(6) - Hash[*(start+1..(lines.count+start)).zip(lines).flatten] + def source_fragment(path, line) + return unless Rails.respond_to?(:root) && Rails.root + full_path = Rails.root.join(path) + if File.exist?(full_path) + File.open(full_path, "r") do |file| + start = [line - 3, 0].max + lines = file.each_line.drop(start).take(6) + Hash[*(start+1..(lines.count+start)).zip(lines).flatten] + end end end - end - def extract_file_and_line_number(trace) - # Split by the first colon followed by some digits, which works for both - # Windows and Unix path styles. - file, line = trace.match(/^(.+?):(\d+).*$/, &:captures) || trace - [file, line.to_i] - end + def extract_file_and_line_number(trace) + # Split by the first colon followed by some digits, which works for both + # Windows and Unix path styles. + file, line = trace.match(/^(.+?):(\d+).*$/, &:captures) || trace + [file, line.to_i] + end - def expand_backtrace - @exception.backtrace.unshift( - @exception.to_s.split("\n") - ).flatten! - end + def expand_backtrace + @exception.backtrace.unshift( + @exception.to_s.split("\n") + ).flatten! + end end end diff --git a/actionpack/lib/action_dispatch/middleware/flash.rb b/actionpack/lib/action_dispatch/middleware/flash.rb index cee005ac10..6900934712 100644 --- a/actionpack/lib/action_dispatch/middleware/flash.rb +++ b/actionpack/lib/action_dispatch/middleware/flash.rb @@ -277,15 +277,15 @@ module ActionDispatch end protected - def now_is_loaded? - @now - end + def now_is_loaded? + @now + end - def stringify_array(array) - array.map do |item| - item.kind_of?(Symbol) ? item.to_s : item + def stringify_array(array) + array.map do |item| + item.kind_of?(Symbol) ? item.to_s : item + end end - end end def self.new(app) app; end diff --git a/actionpack/lib/action_dispatch/middleware/public_exceptions.rb b/actionpack/lib/action_dispatch/middleware/public_exceptions.rb index 5f356daba8..e3555ce638 100644 --- a/actionpack/lib/action_dispatch/middleware/public_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/public_exceptions.rb @@ -27,29 +27,29 @@ module ActionDispatch private - def render(status, content_type, body) - format = "to_#{content_type.to_sym}" if content_type - if format && body.respond_to?(format) - render_format(status, content_type, body.public_send(format)) - else - render_html(status) + def render(status, content_type, body) + format = "to_#{content_type.to_sym}" if content_type + if format && body.respond_to?(format) + render_format(status, content_type, body.public_send(format)) + else + render_html(status) + end end - 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]] - 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]] + end - def render_html(status) - path = "#{public_path}/#{status}.#{I18n.locale}.html" - path = "#{public_path}/#{status}.html" unless (found = File.exist?(path)) + def render_html(status) + path = "#{public_path}/#{status}.#{I18n.locale}.html" + path = "#{public_path}/#{status}.html" unless (found = File.exist?(path)) - if found || File.exist?(path) - render_format(status, "text/html", File.read(path)) - else - [404, { "X-Cascade" => "pass" }, []] + if found || File.exist?(path) + render_format(status, "text/html", File.read(path)) + else + [404, { "X-Cascade" => "pass" }, []] + end end - end end end diff --git a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb index 430258e296..d903338a2b 100644 --- a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb +++ b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb @@ -46,9 +46,9 @@ module ActionDispatch end private - def make_request(env) - ActionDispatch::Request.new env - end + def make_request(env) + ActionDispatch::Request.new env + end end module StaleSessionCheck @@ -94,9 +94,9 @@ module ActionDispatch private - def set_cookie(request, session_id, cookie) - request.cookie_jar[key] = cookie - end + def set_cookie(request, session_id, cookie) + request.cookie_jar[key] = cookie + end end end end diff --git a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb index 6148547cef..8409109ede 100644 --- a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb +++ b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb @@ -84,46 +84,46 @@ module ActionDispatch private - def extract_session_id(req) - stale_session_check! do - unpacked_cookie_data(req)["session_id"] + def extract_session_id(req) + stale_session_check! do + unpacked_cookie_data(req)["session_id"] + end end - end - def unpacked_cookie_data(req) - req.fetch_header("action_dispatch.request.unsigned_session_cookie") do |k| - v = stale_session_check! do - if data = get_cookie(req) - data.stringify_keys! + def unpacked_cookie_data(req) + req.fetch_header("action_dispatch.request.unsigned_session_cookie") do |k| + v = stale_session_check! do + if data = get_cookie(req) + data.stringify_keys! + end + data || {} end - data || {} + req.set_header k, v end - req.set_header k, v end - end - def persistent_session_id!(data, sid=nil) - data ||= {} - data["session_id"] ||= sid || generate_sid - data - end + def persistent_session_id!(data, sid=nil) + data ||= {} + data["session_id"] ||= sid || generate_sid + data + end - def write_session(req, sid, session_data, options) - session_data["session_id"] = sid - session_data - end + def write_session(req, sid, session_data, options) + session_data["session_id"] = sid + session_data + end - def set_cookie(request, session_id, cookie) - cookie_jar(request)[@key] = cookie - end + def set_cookie(request, session_id, cookie) + cookie_jar(request)[@key] = cookie + end - def get_cookie(req) - cookie_jar(req)[@key] - end + def get_cookie(req) + cookie_jar(req)[@key] + end - def cookie_jar(request) - request.cookie_jar.signed_or_encrypted - end + def cookie_jar(request) + request.cookie_jar.signed_or_encrypted + end end end end diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb index 126b627631..5aff130bc3 100644 --- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb @@ -39,22 +39,22 @@ module ActionDispatch private - def render_exception(request, exception) - backtrace_cleaner = request.get_header "action_dispatch.backtrace_cleaner" - wrapper = ExceptionWrapper.new(backtrace_cleaner, exception) - status = wrapper.status_code - request.set_header "action_dispatch.exception", wrapper.exception - request.set_header "action_dispatch.original_path", request.path_info - request.path_info = "/#{status}" - response = @exceptions_app.call(request.env) - response[1]["X-Cascade"] == "pass" ? pass_response(status) : response - rescue Exception => failsafe_error - $stderr.puts "Error during failsafe response: #{failsafe_error}\n #{failsafe_error.backtrace * "\n "}" - FAILSAFE_RESPONSE - end + def render_exception(request, exception) + backtrace_cleaner = request.get_header "action_dispatch.backtrace_cleaner" + wrapper = ExceptionWrapper.new(backtrace_cleaner, exception) + status = wrapper.status_code + request.set_header "action_dispatch.exception", wrapper.exception + request.set_header "action_dispatch.original_path", request.path_info + request.path_info = "/#{status}" + response = @exceptions_app.call(request.env) + response[1]["X-Cascade"] == "pass" ? pass_response(status) : response + rescue Exception => failsafe_error + $stderr.puts "Error during failsafe response: #{failsafe_error}\n #{failsafe_error.backtrace * "\n "}" + FAILSAFE_RESPONSE + end - def pass_response(status) - [status, {"Content-Type" => "text/html; charset=#{Response.default_charset}", "Content-Length" => "0"}, []] - end + def pass_response(status) + [status, {"Content-Type" => "text/html; charset=#{Response.default_charset}", "Content-Length" => "0"}, []] + end end end diff --git a/actionpack/lib/action_dispatch/middleware/stack.rb b/actionpack/lib/action_dispatch/middleware/stack.rb index 0b4bee5462..e49bf54115 100644 --- a/actionpack/lib/action_dispatch/middleware/stack.rb +++ b/actionpack/lib/action_dispatch/middleware/stack.rb @@ -102,32 +102,32 @@ module ActionDispatch private - def assert_index(index, where) - index = get_class index - i = index.is_a?(Integer) ? index : middlewares.index { |m| m.klass == index } - raise "No such middleware to insert #{where}: #{index.inspect}" unless i - i - end + def assert_index(index, where) + index = get_class index + i = index.is_a?(Integer) ? index : middlewares.index { |m| m.klass == index } + raise "No such middleware to insert #{where}: #{index.inspect}" unless i + i + end - def get_class(klass) - if klass.is_a?(String) || klass.is_a?(Symbol) - classcache = ActiveSupport::Dependencies::Reference - converted_klass = classcache[klass.to_s] - ActiveSupport::Deprecation.warn <<-eowarn + def get_class(klass) + if klass.is_a?(String) || klass.is_a?(Symbol) + classcache = ActiveSupport::Dependencies::Reference + converted_klass = classcache[klass.to_s] + ActiveSupport::Deprecation.warn <<-eowarn Passing strings or symbols to the middleware builder is deprecated, please change them to actual class references. For example: "#{klass}" => #{converted_klass} eowarn - converted_klass - else - klass + converted_klass + else + klass + end end - end - def build_middleware(klass, args, block) - Middleware.new(get_class(klass), args, block) - end + def build_middleware(klass, args, block) + Middleware.new(get_class(klass), args, block) + end end end diff --git a/actionpack/lib/action_dispatch/request/session.rb b/actionpack/lib/action_dispatch/request/session.rb index f9d6e94504..b883ca0f61 100644 --- a/actionpack/lib/action_dispatch/request/session.rb +++ b/actionpack/lib/action_dispatch/request/session.rb @@ -204,26 +204,26 @@ module ActionDispatch private - def load_for_read! - load! if !loaded? && exists? - end + def load_for_read! + load! if !loaded? && exists? + end - def load_for_write! - load! unless loaded? - end + def load_for_write! + load! unless loaded? + end - def load! - id, session = @by.load_session @req - options[:id] = id - @delegate.replace(stringify_keys(session)) - @loaded = true - end + def load! + id, session = @by.load_session @req + options[:id] = id + @delegate.replace(stringify_keys(session)) + @loaded = true + end - def stringify_keys(other) - other.each_with_object({}) { |(key, value), hash| - hash[key.to_s] = value - } - end + def stringify_keys(other) + other.each_with_object({}) { |(key, value), hash| + hash[key.to_s] = value + } + end end end end diff --git a/actionpack/lib/action_dispatch/request/utils.rb b/actionpack/lib/action_dispatch/request/utils.rb index bb3df3c311..ba622131e7 100644 --- a/actionpack/lib/action_dispatch/request/utils.rb +++ b/actionpack/lib/action_dispatch/request/utils.rb @@ -64,4 +64,3 @@ module ActionDispatch end end end - diff --git a/actionpack/lib/action_dispatch/routing/inspector.rb b/actionpack/lib/action_dispatch/routing/inspector.rb index a66a1d4ca4..b91ffb8419 100644 --- a/actionpack/lib/action_dispatch/routing/inspector.rb +++ b/actionpack/lib/action_dispatch/routing/inspector.rb @@ -80,48 +80,48 @@ module ActionDispatch private - def normalize_filter(filter) - if filter.is_a?(Hash) && filter[:controller] - { controller: /#{filter[:controller].downcase.sub(/_?controller\z/, '').sub('::', '/')}/ } - elsif filter - { controller: /#{filter}/, action: /#{filter}/, verb: /#{filter}/, name: /#{filter}/, path: /#{filter}/ } + def normalize_filter(filter) + if filter.is_a?(Hash) && filter[:controller] + { controller: /#{filter[:controller].downcase.sub(/_?controller\z/, '').sub('::', '/')}/ } + elsif filter + { controller: /#{filter}/, action: /#{filter}/, verb: /#{filter}/, name: /#{filter}/, path: /#{filter}/ } + end end - end - def filter_routes(filter) - if filter - @routes.select do |route| - route_wrapper = RouteWrapper.new(route) - filter.any? { |default, value| route_wrapper.send(default) =~ value } + def filter_routes(filter) + if filter + @routes.select do |route| + route_wrapper = RouteWrapper.new(route) + filter.any? { |default, value| route_wrapper.send(default) =~ value } + end + else + @routes end - else - @routes end - end - def collect_routes(routes) - routes.collect do |route| - RouteWrapper.new(route) - end.reject(&:internal?).collect do |route| - collect_engine_routes(route) + def collect_routes(routes) + routes.collect do |route| + RouteWrapper.new(route) + end.reject(&:internal?).collect do |route| + collect_engine_routes(route) - { name: route.name, - verb: route.verb, - path: route.path, - reqs: route.reqs } + { name: route.name, + verb: route.verb, + path: route.path, + reqs: route.reqs } + end end - end - def collect_engine_routes(route) - name = route.endpoint - return unless route.engine? - return if @engines[name] + def collect_engine_routes(route) + name = route.endpoint + return unless route.engine? + return if @engines[name] - routes = route.rack_app.routes - if routes.is_a?(ActionDispatch::Routing::RouteSet) - @engines[name] = collect_routes(routes.routes) + routes = route.rack_app.routes + if routes.is_a?(ActionDispatch::Routing::RouteSet) + @engines[name] = collect_routes(routes.routes) + end end - end end class ConsoleFormatter diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 7034f25b09..a6b177480d 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -1684,7 +1684,7 @@ to this: end as = if !options.fetch(:as, true) # if it's set to nil or false - options.delete(:as) + options.delete(:as) else name_for_action(options.delete(:as), action) end @@ -1914,24 +1914,24 @@ to this: end private - def path_scope(path) - @scope = @scope.new(path: merge_path_scope(@scope[:path], path)) - yield - ensure - @scope = @scope.parent - end + def path_scope(path) + @scope = @scope.new(path: merge_path_scope(@scope[:path], path)) + yield + ensure + @scope = @scope.parent + end - def match_root_route(options) - name = has_named_route?(:root) ? nil : :root - defaults_option = options.delete(:defaults) - args = ["/", { as: name, via: :get }.merge!(options)] + def match_root_route(options) + name = has_named_route?(:root) ? nil : :root + defaults_option = options.delete(:defaults) + args = ["/", { as: name, via: :get }.merge!(options)] - if defaults_option - defaults(defaults_option) { match(*args) } - else - match(*args) + if defaults_option + defaults(defaults_option) { match(*args) } + else + match(*args) + end end - end end # Routing Concerns allow you to declare common routes that can be reused diff --git a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb index a0874d6be3..3e2b21ac72 100644 --- a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb +++ b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb @@ -149,176 +149,176 @@ module ActionDispatch private - def polymorphic_url_for_action(action, record_or_hash, options) - polymorphic_url(record_or_hash, options.merge(action: action)) - end + def polymorphic_url_for_action(action, record_or_hash, options) + polymorphic_url(record_or_hash, options.merge(action: action)) + end - def polymorphic_path_for_action(action, record_or_hash, options) - polymorphic_path(record_or_hash, options.merge(action: action)) - end + def polymorphic_path_for_action(action, record_or_hash, options) + polymorphic_path(record_or_hash, options.merge(action: action)) + end - class HelperMethodBuilder # :nodoc: - CACHE = { "path" => {}, "url" => {} } + class HelperMethodBuilder # :nodoc: + CACHE = { "path" => {}, "url" => {} } - def self.get(action, type) - type = type.to_s - CACHE[type].fetch(action) { build action, type } - end + def self.get(action, type) + type = type.to_s + CACHE[type].fetch(action) { build action, type } + end - def self.url; CACHE["url".freeze][nil]; end - def self.path; CACHE["path".freeze][nil]; end + def self.url; CACHE["url".freeze][nil]; end + def self.path; CACHE["path".freeze][nil]; end - def self.build(action, type) - prefix = action ? "#{action}_" : "" - suffix = type - if action.to_s == "new" - HelperMethodBuilder.singular prefix, suffix - else - HelperMethodBuilder.plural prefix, suffix + def self.build(action, type) + prefix = action ? "#{action}_" : "" + suffix = type + if action.to_s == "new" + HelperMethodBuilder.singular prefix, suffix + else + HelperMethodBuilder.plural prefix, suffix + end end - end - def self.singular(prefix, suffix) - new(->(name) { name.singular_route_key }, prefix, suffix) - end + def self.singular(prefix, suffix) + new(->(name) { name.singular_route_key }, prefix, suffix) + end - def self.plural(prefix, suffix) - new(->(name) { name.route_key }, prefix, suffix) - end + def self.plural(prefix, suffix) + new(->(name) { name.route_key }, prefix, suffix) + end - def self.polymorphic_method(recipient, record_or_hash_or_array, action, type, options) - builder = get action, type + def self.polymorphic_method(recipient, record_or_hash_or_array, action, type, options) + builder = get action, type + + case record_or_hash_or_array + when Array + record_or_hash_or_array = record_or_hash_or_array.compact + if record_or_hash_or_array.empty? + raise ArgumentError, "Nil location provided. Can't build URI." + end + if record_or_hash_or_array.first.is_a?(ActionDispatch::Routing::RoutesProxy) + recipient = record_or_hash_or_array.shift + end + + method, args = builder.handle_list record_or_hash_or_array + when String, Symbol + method, args = builder.handle_string record_or_hash_or_array + when Class + method, args = builder.handle_class record_or_hash_or_array - case record_or_hash_or_array - when Array - record_or_hash_or_array = record_or_hash_or_array.compact - if record_or_hash_or_array.empty? + when nil raise ArgumentError, "Nil location provided. Can't build URI." - end - if record_or_hash_or_array.first.is_a?(ActionDispatch::Routing::RoutesProxy) - recipient = record_or_hash_or_array.shift + else + method, args = builder.handle_model record_or_hash_or_array end - method, args = builder.handle_list record_or_hash_or_array - when String, Symbol - method, args = builder.handle_string record_or_hash_or_array - when Class - method, args = builder.handle_class record_or_hash_or_array - when nil - raise ArgumentError, "Nil location provided. Can't build URI." - else - method, args = builder.handle_model record_or_hash_or_array + if options.empty? + recipient.send(method, *args) + else + recipient.send(method, *args, options) + end end + attr_reader :suffix, :prefix - if options.empty? - recipient.send(method, *args) - else - recipient.send(method, *args, options) + def initialize(key_strategy, prefix, suffix) + @key_strategy = key_strategy + @prefix = prefix + @suffix = suffix end - end - - attr_reader :suffix, :prefix - - def initialize(key_strategy, prefix, suffix) - @key_strategy = key_strategy - @prefix = prefix - @suffix = suffix - end - - def handle_string(record) - [get_method_for_string(record), []] - end - - def handle_string_call(target, str) - target.send get_method_for_string str - end - def handle_class(klass) - [get_method_for_class(klass), []] - end + def handle_string(record) + [get_method_for_string(record), []] + end - def handle_class_call(target, klass) - target.send get_method_for_class klass - end + def handle_string_call(target, str) + target.send get_method_for_string str + end - def handle_model(record) - args = [] + def handle_class(klass) + [get_method_for_class(klass), []] + end - model = record.to_model - named_route = if model.persisted? - args << model - get_method_for_string model.model_name.singular_route_key - else - get_method_for_class model - end + def handle_class_call(target, klass) + target.send get_method_for_class klass + end - [named_route, args] - end + def handle_model(record) + args = [] - def handle_model_call(target, model) - method, args = handle_model model - target.send(method, *args) - end + model = record.to_model + named_route = if model.persisted? + args << model + get_method_for_string model.model_name.singular_route_key + else + get_method_for_class model + end - def handle_list(list) - record_list = list.dup - record = record_list.pop + [named_route, args] + end - args = [] + def handle_model_call(target, model) + method, args = handle_model model + target.send(method, *args) + end - route = record_list.map { |parent| - case parent + def handle_list(list) + record_list = list.dup + record = record_list.pop + + args = [] + + route = record_list.map { |parent| + case parent + when Symbol, String + parent.to_s + when Class + args << parent + parent.model_name.singular_route_key + else + args << parent.to_model + parent.to_model.model_name.singular_route_key + end + } + + route << + case record when Symbol, String - parent.to_s + record.to_s when Class - args << parent - parent.model_name.singular_route_key + @key_strategy.call record.model_name else - args << parent.to_model - parent.to_model.model_name.singular_route_key + model = record.to_model + if model.persisted? + args << model + model.model_name.singular_route_key + else + @key_strategy.call model.model_name + end end - } - - route << - case record - when Symbol, String - record.to_s - when Class - @key_strategy.call record.model_name - else - model = record.to_model - if model.persisted? - args << model - model.model_name.singular_route_key - else - @key_strategy.call model.model_name - end - end - route << suffix + route << suffix - named_route = prefix + route.join("_") - [named_route, args] - end + named_route = prefix + route.join("_") + [named_route, args] + end - private + private - def get_method_for_class(klass) - name = @key_strategy.call klass.model_name - get_method_for_string name - end + def get_method_for_class(klass) + name = @key_strategy.call klass.model_name + get_method_for_string name + end - def get_method_for_string(str) - "#{prefix}#{str}_#{suffix}" - end + def get_method_for_string(str) + "#{prefix}#{str}_#{suffix}" + end - [nil, "new", "edit"].each do |action| - CACHE["url"][action] = build action, "url" - CACHE["path"][action] = build action, "path" + [nil, "new", "edit"].each do |action| + CACHE["url"][action] = build action, "url" + CACHE["path"][action] = build action, "path" + end end - end end end end diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index c1ea23e36d..b9eda039a1 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -59,7 +59,7 @@ module ActionDispatch private - def controller(_); @controller_class; end + def controller(_); @controller_class; end end # A NamedRouteCollection instance is a collection of named routes, and also @@ -180,40 +180,40 @@ module ActionDispatch private - def optimized_helper(args) - params = parameterize_args(args) do - raise_generation_error(args) - end + def optimized_helper(args) + params = parameterize_args(args) do + raise_generation_error(args) + end - @route.format params - end + @route.format params + end - def optimize_routes_generation?(t) - t.send(:optimize_routes_generation?) - end + def optimize_routes_generation?(t) + t.send(:optimize_routes_generation?) + end - def parameterize_args(args) - params = {} - @arg_size.times { |i| - key = @required_parts[i] - value = args[i].to_param - yield key if value.nil? || value.empty? - params[key] = value - } - params - end + def parameterize_args(args) + params = {} + @arg_size.times { |i| + key = @required_parts[i] + value = args[i].to_param + yield key if value.nil? || value.empty? + params[key] = value + } + params + end - def raise_generation_error(args) - missing_keys = [] - params = parameterize_args(args) { |missing_key| - missing_keys << missing_key - } - 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}" + def raise_generation_error(args) + missing_keys = [] + params = parameterize_args(args) { |missing_key| + missing_keys << missing_key + } + 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}" - raise ActionController::UrlGenerationError, message - end + raise ActionController::UrlGenerationError, message + end end def initialize(route, options, route_name, url_strategy) @@ -277,25 +277,25 @@ module ActionDispatch # # foo_url(bar, baz, bang, sort_by: 'baz') # - def define_url_helper(mod, route, name, opts, route_key, url_strategy) - helper = UrlHelper.create(route, opts, route_key, url_strategy) - mod.module_eval do - define_method(name) do |*args| - last = args.last - options = case last - when Hash - args.pop - when ActionController::Parameters - if last.permitted? - args.pop.to_h - else - raise ArgumentError, ActionDispatch::Routing::INSECURE_URL_PARAMETERS_MESSAGE + def define_url_helper(mod, route, name, opts, route_key, url_strategy) + helper = UrlHelper.create(route, opts, route_key, url_strategy) + mod.module_eval do + define_method(name) do |*args| + last = args.last + options = case last + when Hash + args.pop + when ActionController::Parameters + if last.permitted? + args.pop.to_h + else + raise ArgumentError, ActionDispatch::Routing::INSECURE_URL_PARAMETERS_MESSAGE + end end - end - helper.call self, args, options + helper.call self, args, options + end end end - end end # strategy for building urls to send to the client diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb index 5ee138e6c6..a1ac5a2b6c 100644 --- a/actionpack/lib/action_dispatch/routing/url_for.rb +++ b/actionpack/lib/action_dispatch/routing/url_for.rb @@ -194,20 +194,20 @@ module ActionDispatch protected - def optimize_routes_generation? - _routes.optimize_routes_generation? && default_url_options.empty? - end + def optimize_routes_generation? + _routes.optimize_routes_generation? && default_url_options.empty? + end - def _with_routes(routes) - old_routes, @_routes = @_routes, routes - yield - ensure - @_routes = old_routes - end + def _with_routes(routes) + old_routes, @_routes = @_routes, routes + yield + ensure + @_routes = old_routes + end - def _routes_context - self - end + def _routes_context + self + end end end end diff --git a/actionpack/lib/action_dispatch/testing/assertion_response.rb b/actionpack/lib/action_dispatch/testing/assertion_response.rb index 404b96bbcd..c37726957e 100644 --- a/actionpack/lib/action_dispatch/testing/assertion_response.rb +++ b/actionpack/lib/action_dispatch/testing/assertion_response.rb @@ -34,12 +34,12 @@ module ActionDispatch private - def code_from_name(name) - GENERIC_RESPONSE_CODES[name] || Rack::Utils::SYMBOL_TO_STATUS_CODE[name] - end + def code_from_name(name) + GENERIC_RESPONSE_CODES[name] || Rack::Utils::SYMBOL_TO_STATUS_CODE[name] + end - def name_from_code(code) - GENERIC_RESPONSE_CODES.invert[code] || Rack::Utils::HTTP_STATUS_CODES[code] - end + def name_from_code(code) + GENERIC_RESPONSE_CODES.invert[code] || Rack::Utils::HTTP_STATUS_CODES[code] + end end end diff --git a/actionpack/test/abstract/callbacks_test.rb b/actionpack/test/abstract/callbacks_test.rb index 14d73e8372..be68dc49bd 100644 --- a/actionpack/test/abstract/callbacks_test.rb +++ b/actionpack/test/abstract/callbacks_test.rb @@ -126,14 +126,14 @@ module AbstractController end private - def list - @list = ["Hello", "World"] - end - - def authenticate - @list ||= [] - @authenticated = "true" - end + def list + @list = ["Hello", "World"] + end + + def authenticate + @list ||= [] + @authenticated = "true" + end end class TestCallbacksWithConditions < ActiveSupport::TestCase @@ -170,14 +170,14 @@ module AbstractController end private - def list - @list = ["Hello", "World"] - end - - def authenticate - @list = [] - @authenticated = "true" - end + def list + @list = ["Hello", "World"] + end + + def authenticate + @list = [] + @authenticated = "true" + end end class TestCallbacksWithArrayConditions < ActiveSupport::TestCase diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index 075ebd3974..c887b868d2 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -254,11 +254,11 @@ end module ActionDispatch class DebugExceptions private - remove_method :stderr_logger + remove_method :stderr_logger # Silence logger - def stderr_logger - nil - end + def stderr_logger + nil + end end end @@ -348,9 +348,9 @@ module RoutingTestHelpers private - def make_request(env) - Request.new super, url_helpers, @block, strict - end + def make_request(env) + Request.new super, url_helpers, @block, strict + end end end @@ -426,18 +426,18 @@ class ForkingExecutor end private - def translate_exceptions(result) - result.failures.map! { |e| - begin - Marshal.dump e - e - rescue TypeError - ex = Exception.new e.message - ex.set_backtrace e.backtrace - Minitest::UnexpectedError.new ex - end - } - end + def translate_exceptions(result) + result.failures.map! { |e| + begin + Marshal.dump e + e + rescue TypeError + ex = Exception.new e.message + ex.set_backtrace e.backtrace + Minitest::UnexpectedError.new ex + end + } + end end if RUBY_ENGINE == "ruby" && PROCESS_COUNT > 0 diff --git a/actionpack/test/controller/api/conditional_get_test.rb b/actionpack/test/controller/api/conditional_get_test.rb index 330bfac1c9..7b70829101 100644 --- a/actionpack/test/controller/api/conditional_get_test.rb +++ b/actionpack/test/controller/api/conditional_get_test.rb @@ -17,9 +17,9 @@ class ConditionalGetApiController < ActionController::API private - def handle_last_modified_and_etags - fresh_when(last_modified: Time.now.utc.beginning_of_day, etag: [ :foo, 123 ]) - end + def handle_last_modified_and_etags + fresh_when(last_modified: Time.now.utc.beginning_of_day, etag: [ :foo, 123 ]) + end end class ConditionalGetApiTest < ActionController::TestCase diff --git a/actionpack/test/controller/content_type_test.rb b/actionpack/test/controller/content_type_test.rb index 47bc8c4983..fcb2632b80 100644 --- a/actionpack/test/controller/content_type_test.rb +++ b/actionpack/test/controller/content_type_test.rb @@ -131,13 +131,13 @@ class ContentTypeTest < ActionController::TestCase private - def with_default_charset(charset) - old_default_charset = ActionDispatch::Response.default_charset - ActionDispatch::Response.default_charset = charset - yield - ensure - ActionDispatch::Response.default_charset = old_default_charset - end + def with_default_charset(charset) + old_default_charset = ActionDispatch::Response.default_charset + ActionDispatch::Response.default_charset = charset + yield + ensure + ActionDispatch::Response.default_charset = old_default_charset + end end class AcceptBasedContentTypeTest < ActionController::TestCase diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb index 0ddf825864..fc4083d611 100644 --- a/actionpack/test/controller/filters_test.rb +++ b/actionpack/test/controller/filters_test.rb @@ -56,14 +56,14 @@ class FilterTest < ActionController::TestCase end protected - (1..3).each do |i| - define_method "try_#{i}" do - instance_variable_set :@try, i - if action_name == "fail_#{i}" - head(404) + (1..3).each do |i| + define_method "try_#{i}" do + instance_variable_set :@try, i + if action_name == "fail_#{i}" + head(404) + end end end - end end class RenderingController < ActionController::Base @@ -531,13 +531,13 @@ class FilterTest < ActionController::TestCase private - def find_only - @only = "Only" - end + def find_only + @only = "Only" + end - def find_except - @except = "Except" - end + def find_except + @except = "Except" + end end def test_non_yielding_around_actions_do_not_raise @@ -931,26 +931,26 @@ class ControllerWithAllTypesOfFilters < PostsController around_action :around_again private - def before - @ran_filter ||= [] - @ran_filter << "before" - end + def before + @ran_filter ||= [] + @ran_filter << "before" + end - def around - @ran_filter << "around (before yield)" - yield - @ran_filter << "around (after yield)" - end + def around + @ran_filter << "around (before yield)" + yield + @ran_filter << "around (after yield)" + end - def after - @ran_filter << "after" - end + def after + @ran_filter << "after" + end - def around_again - @ran_filter << "around_again (before yield)" - yield - @ran_filter << "around_again (after yield)" - end + def around_again + @ran_filter << "around_again (before yield)" + yield + @ran_filter << "around_again (after yield)" + end end class ControllerWithTwoLessFilters < ControllerWithAllTypesOfFilters diff --git a/actionpack/test/controller/http_basic_authentication_test.rb b/actionpack/test/controller/http_basic_authentication_test.rb index c980d0ed35..d9ae787689 100644 --- a/actionpack/test/controller/http_basic_authentication_test.rb +++ b/actionpack/test/controller/http_basic_authentication_test.rb @@ -31,31 +31,31 @@ class HttpBasicAuthenticationTest < ActionController::TestCase private - def authenticate - authenticate_or_request_with_http_basic do |username, password| - username == "lifo" && password == "world" + def authenticate + authenticate_or_request_with_http_basic do |username, password| + username == "lifo" && password == "world" + end end - end - def authenticate_with_request - if authenticate_with_http_basic { |username, password| username == "pretty" && password == "please" } - @logged_in = true - else - request_http_basic_authentication("SuperSecret", "Authentication Failed\n") + def authenticate_with_request + if authenticate_with_http_basic { |username, password| username == "pretty" && password == "please" } + @logged_in = true + else + request_http_basic_authentication("SuperSecret", "Authentication Failed\n") + end end - end - def auth_with_special_chars - authenticate_or_request_with_http_basic do |username, password| - username == 'login!@#$%^&*()_+{}[];"\',./<>?`~ \n\r\t' && password == 'pwd:!@#$%^&*()_+{}[];"\',./<>?`~ \n\r\t' + def auth_with_special_chars + authenticate_or_request_with_http_basic do |username, password| + username == 'login!@#$%^&*()_+{}[];"\',./<>?`~ \n\r\t' && password == 'pwd:!@#$%^&*()_+{}[];"\',./<>?`~ \n\r\t' + end end - end - def authenticate_long_credentials - authenticate_or_request_with_http_basic do |username, password| - username == "1234567890123456789012345678901234567890" && password == "1234567890123456789012345678901234567890" + def authenticate_long_credentials + authenticate_or_request_with_http_basic do |username, password| + username == "1234567890123456789012345678901234567890" && password == "1234567890123456789012345678901234567890" + end end - end end AUTH_HEADERS = ["HTTP_AUTHORIZATION", "X-HTTP_AUTHORIZATION", "X_HTTP_AUTHORIZATION", "REDIRECT_X_HTTP_AUTHORIZATION"] @@ -171,7 +171,7 @@ class HttpBasicAuthenticationTest < ActionController::TestCase private - def encode_credentials(username, password) - "Basic #{::Base64.encode64("#{username}:#{password}")}" - end + def encode_credentials(username, password) + "Basic #{::Base64.encode64("#{username}:#{password}")}" + end end diff --git a/actionpack/test/controller/http_digest_authentication_test.rb b/actionpack/test/controller/http_digest_authentication_test.rb index 854ec62774..5e9b801f8b 100644 --- a/actionpack/test/controller/http_digest_authentication_test.rb +++ b/actionpack/test/controller/http_digest_authentication_test.rb @@ -19,20 +19,20 @@ class HttpDigestAuthenticationTest < ActionController::TestCase private - def authenticate - authenticate_or_request_with_http_digest("SuperSecret") do |username| - # Returns the password - USERS[username] + def authenticate + authenticate_or_request_with_http_digest("SuperSecret") do |username| + # Returns the password + USERS[username] + end end - end - def authenticate_with_request - if authenticate_with_http_digest("SuperSecret") { |username| USERS[username] } - @logged_in = true - else - request_http_digest_authentication("SuperSecret", "Authentication Failed") + def authenticate_with_request + if authenticate_with_http_digest("SuperSecret") { |username| USERS[username] } + @logged_in = true + else + request_http_digest_authentication("SuperSecret", "Authentication Failed") + end end - end end AUTH_HEADERS = ["HTTP_AUTHORIZATION", "X-HTTP_AUTHORIZATION", "X_HTTP_AUTHORIZATION", "REDIRECT_X_HTTP_AUTHORIZATION"] @@ -249,32 +249,32 @@ class HttpDigestAuthenticationTest < ActionController::TestCase private - def encode_credentials(options) - options.reverse_merge!(nc: "00000001", cnonce: "0a4f113b", password_is_ha1: false) - password = options.delete(:password) + def encode_credentials(options) + options.reverse_merge!(nc: "00000001", cnonce: "0a4f113b", password_is_ha1: false) + password = options.delete(:password) - # Perform unauthenticated request to retrieve digest parameters to use on subsequent request - method = options.delete(:method) || "GET" + # Perform unauthenticated request to retrieve digest parameters to use on subsequent request + method = options.delete(:method) || "GET" - case method.to_s.upcase - when "GET" - get :index - when "POST" - post :index - end + case method.to_s.upcase + when "GET" + get :index + when "POST" + post :index + end - assert_response :unauthorized + assert_response :unauthorized - credentials = decode_credentials(@response.headers["WWW-Authenticate"]) - credentials.merge!(options) - path_info = @request.env["PATH_INFO"].to_s - uri = options[:uri] || path_info - credentials.merge!(uri: uri) - @request.env["ORIGINAL_FULLPATH"] = path_info - ActionController::HttpAuthentication::Digest.encode_credentials(method, credentials, password, options[:password_is_ha1]) - end + credentials = decode_credentials(@response.headers["WWW-Authenticate"]) + credentials.merge!(options) + path_info = @request.env["PATH_INFO"].to_s + uri = options[:uri] || path_info + credentials.merge!(uri: uri) + @request.env["ORIGINAL_FULLPATH"] = path_info + ActionController::HttpAuthentication::Digest.encode_credentials(method, credentials, password, options[:password_is_ha1]) + end - def decode_credentials(header) - ActionController::HttpAuthentication::Digest.decode_credentials(header) - end + def decode_credentials(header) + ActionController::HttpAuthentication::Digest.decode_credentials(header) + end end diff --git a/actionpack/test/controller/http_token_authentication_test.rb b/actionpack/test/controller/http_token_authentication_test.rb index 206fe18eda..b7a4c550d7 100644 --- a/actionpack/test/controller/http_token_authentication_test.rb +++ b/actionpack/test/controller/http_token_authentication_test.rb @@ -20,25 +20,25 @@ class HttpTokenAuthenticationTest < ActionController::TestCase private - def authenticate - authenticate_or_request_with_http_token do |token, _| - token == "lifo" + def authenticate + authenticate_or_request_with_http_token do |token, _| + token == "lifo" + end end - end - def authenticate_with_request - if authenticate_with_http_token { |token, options| token == '"quote" pretty' && options[:algorithm] == "test" } - @logged_in = true - else - request_http_token_authentication("SuperSecret", "Authentication Failed\n") + def authenticate_with_request + if authenticate_with_http_token { |token, options| token == '"quote" pretty' && options[:algorithm] == "test" } + @logged_in = true + else + request_http_token_authentication("SuperSecret", "Authentication Failed\n") + end end - end - def authenticate_long_credentials - authenticate_or_request_with_http_token do |token, options| - token == "1234567890123456789012345678901234567890" && options[:algorithm] == "test" + def authenticate_long_credentials + authenticate_or_request_with_http_token do |token, options| + token == "1234567890123456789012345678901234567890" && options[:algorithm] == "test" + end end - end end AUTH_HEADERS = ["HTTP_AUTHORIZATION", "X-HTTP_AUTHORIZATION", "X_HTTP_AUTHORIZATION", "REDIRECT_X_HTTP_AUTHORIZATION"] diff --git a/actionpack/test/controller/new_base/render_context_test.rb b/actionpack/test/controller/new_base/render_context_test.rb index 5df25d136c..40149a41d3 100644 --- a/actionpack/test/controller/new_base/render_context_test.rb +++ b/actionpack/test/controller/new_base/render_context_test.rb @@ -29,13 +29,13 @@ module RenderContext protected # 3) Set view_context to self - def view_context - self - end + def view_context + self + end - def __controller_method__ - "controller context!" - end + def __controller_method__ + "controller context!" + end end class RenderContextTest < Rack::TestCase diff --git a/actionpack/test/controller/new_base/render_template_test.rb b/actionpack/test/controller/new_base/render_template_test.rb index 13e4bbc1ea..e56cefbda1 100644 --- a/actionpack/test/controller/new_base/render_template_test.rb +++ b/actionpack/test/controller/new_base/render_template_test.rb @@ -67,9 +67,9 @@ module RenderTemplate private - def show_detailed_exceptions? - request.local? - end + def show_detailed_exceptions? + request.local? + end end class TestWithoutLayout < Rack::TestCase diff --git a/actionpack/test/controller/new_base/render_test.rb b/actionpack/test/controller/new_base/render_test.rb index 57006b2da0..cea3f9b5fd 100644 --- a/actionpack/test/controller/new_base/render_test.rb +++ b/actionpack/test/controller/new_base/render_test.rb @@ -36,9 +36,9 @@ module Render private - def secretz - render plain: "FAIL WHALE!" - end + def secretz + render plain: "FAIL WHALE!" + end end class DoubleRenderController < ActionController::Base 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 a6e48b8ded..bf2c3d1ed2 100644 --- a/actionpack/test/controller/parameters/log_on_unpermitted_params_test.rb +++ b/actionpack/test/controller/parameters/log_on_unpermitted_params_test.rb @@ -47,18 +47,18 @@ class LogOnUnpermittedParamsTest < ActiveSupport::TestCase private - def assert_logged(message) - old_logger = ActionController::Base.logger - log = StringIO.new - ActionController::Base.logger = Logger.new(log) + def assert_logged(message) + old_logger = ActionController::Base.logger + log = StringIO.new + ActionController::Base.logger = Logger.new(log) - begin - yield + begin + yield - log.rewind - assert_match message, log.read - ensure - ActionController::Base.logger = old_logger + log.rewind + assert_match message, log.read + ensure + ActionController::Base.logger = old_logger + end end - end end diff --git a/actionpack/test/controller/params_wrapper_test.rb b/actionpack/test/controller/params_wrapper_test.rb index 7d49e8d114..3b30fb2574 100644 --- a/actionpack/test/controller/params_wrapper_test.rb +++ b/actionpack/test/controller/params_wrapper_test.rb @@ -356,11 +356,11 @@ class IrregularInflectionParamsWrapperTest < ActionController::TestCase private - def with_dup - original = ActiveSupport::Inflector::Inflections.instance_variable_get(:@__instance__)[:en] - ActiveSupport::Inflector::Inflections.instance_variable_set(:@__instance__, en: original.dup) - yield - ensure - ActiveSupport::Inflector::Inflections.instance_variable_set(:@__instance__, en: original) - end + def with_dup + original = ActiveSupport::Inflector::Inflections.instance_variable_get(:@__instance__)[:en] + ActiveSupport::Inflector::Inflections.instance_variable_set(:@__instance__, en: original.dup) + yield + ensure + ActiveSupport::Inflector::Inflections.instance_variable_set(:@__instance__, en: original) + end end diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb index a0e92c1a4a..e2724ded83 100644 --- a/actionpack/test/controller/request_forgery_protection_test.rb +++ b/actionpack/test/controller/request_forgery_protection_test.rb @@ -95,19 +95,19 @@ class PrependProtectForgeryBaseController < ActionController::Base protected - def add_called_callback(name) - @called_callbacks ||= [] - @called_callbacks << name - end + def add_called_callback(name) + @called_callbacks ||= [] + @called_callbacks << name + end - def custom_action - add_called_callback("custom_action") - end + def custom_action + add_called_callback("custom_action") + end - def verify_authenticity_token - add_called_callback("verify_authenticity_token") - end + def verify_authenticity_token + add_called_callback("verify_authenticity_token") + end end class FreeCookieController < RequestForgeryProtectionControllerUsingResetSession diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb index 36df54e1ff..6cb4b83208 100644 --- a/actionpack/test/controller/resources_test.rb +++ b/actionpack/test/controller/resources_test.rb @@ -770,25 +770,25 @@ class ResourcesTest < ActionController::TestCase assert_recognizes({controller: "messages", action: "index"}, "/messages/") end - with_routing do |set| - set.draw do - 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/") - end + with_routing do |set| + set.draw do + 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/") + end end def test_multiple_with_path_segment_and_controller with_routing do |set| set.draw do - resources :products do - resources :product_reviews, path: "reviews", controller: "messages" - end - resources :tutors do - resources :tutor_reviews, path: "reviews", controller: "comments" - end + resources :products do + resources :product_reviews, path: "reviews", controller: "messages" + end + resources :tutors do + resources :tutor_reviews, path: "reviews", controller: "comments" + end end assert_simply_restful_for :product_reviews, controller: "messages", as: "reviews", name_prefix: "product_", path_prefix: "products/1/", options: {product_id: "1"} @@ -1314,7 +1314,7 @@ class ResourcesTest < ActionController::TestCase 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}" + "#{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 0b2c7b7a4f..192a1540a7 100644 --- a/actionpack/test/controller/routing_test.rb +++ b/actionpack/test/controller/routing_test.rb @@ -739,7 +739,7 @@ class LegacyRouteSetTests < ActiveSupport::TestCase def test_named_root_url_generation_with_controller_and_action rs.draw do - root to: "content#index", as: "home" + root to: "content#index", as: "home" end assert_equal "/", url_for(rs, controller: "content", action: "index") diff --git a/actionpack/test/controller/show_exceptions_test.rb b/actionpack/test/controller/show_exceptions_test.rb index 9b93afd303..38c601ee81 100644 --- a/actionpack/test/controller/show_exceptions_test.rb +++ b/actionpack/test/controller/show_exceptions_test.rb @@ -50,9 +50,9 @@ module ShowExceptions class ShowExceptionsOverriddenController < ShowExceptionsController private - def show_detailed_exceptions? - params["detailed"] == "1" - end + def show_detailed_exceptions? + params["detailed"] == "1" + end end class ShowExceptionsOverriddenTest < ActionDispatch::IntegrationTest diff --git a/actionpack/test/controller/url_rewriter_test.rb b/actionpack/test/controller/url_rewriter_test.rb index 81dc230929..d64ff4d6ce 100644 --- a/actionpack/test/controller/url_rewriter_test.rb +++ b/actionpack/test/controller/url_rewriter_test.rb @@ -88,4 +88,3 @@ class UrlRewriterTests < ActionController::TestCase assert_equal "/foo/bar/3/?query=string", @rewriter.rewrite(@routes, options) end end - diff --git a/actionpack/test/dispatch/request/session_test.rb b/actionpack/test/dispatch/request/session_test.rb index b599fe5437..cc3c4d48f3 100644 --- a/actionpack/test/dispatch/request/session_test.rb +++ b/actionpack/test/dispatch/request/session_test.rb @@ -106,13 +106,13 @@ module ActionDispatch end private - def store - Class.new { - def load_session(env); [1, {}]; end - def session_exists?(env); true; end - def delete_session(env, id, options); 123; end - }.new - end + def store + Class.new { + def load_session(env); [1, {}]; end + def session_exists?(env); true; end + def delete_session(env, id, options); 123; end + }.new + end end class SessionIntegrationTest < ActionDispatch::IntegrationTest diff --git a/actionpack/test/dispatch/request_id_test.rb b/actionpack/test/dispatch/request_id_test.rb index d64ee7607d..793ce67db4 100644 --- a/actionpack/test/dispatch/request_id_test.rb +++ b/actionpack/test/dispatch/request_id_test.rb @@ -23,10 +23,10 @@ class RequestIdTest < ActiveSupport::TestCase private - def stub_request(env = {}) - ActionDispatch::RequestId.new(lambda { |environment| [ 200, environment, [] ] }).call(env) - ActionDispatch::Request.new(env) - end + def stub_request(env = {}) + ActionDispatch::RequestId.new(lambda { |environment| [ 200, environment, [] ] }).call(env) + ActionDispatch::Request.new(env) + end end class RequestIdResponseTest < ActionDispatch::IntegrationTest @@ -53,17 +53,17 @@ class RequestIdResponseTest < ActionDispatch::IntegrationTest private - def with_test_route_set - with_routing do |set| - set.draw do - get "/", to: ::RequestIdResponseTest::TestController.action(:index) - end + def with_test_route_set + with_routing do |set| + set.draw do + get "/", to: ::RequestIdResponseTest::TestController.action(:index) + end - @app = self.class.build_app(set) do |middleware| - middleware.use ActionDispatch::RequestId - end + @app = self.class.build_app(set) do |middleware| + middleware.use ActionDispatch::RequestId + end - yield + yield + end end - end end diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb index 6994c7e897..486c0e162d 100644 --- a/actionpack/test/dispatch/routing_test.rb +++ b/actionpack/test/dispatch/routing_test.rb @@ -4781,9 +4781,9 @@ class TestPartialDynamicPathSegments < ActionDispatch::IntegrationTest private - def assert_params(params) - assert_equal(params, request.path_parameters) - end + def assert_params(params) + assert_equal(params, request.path_parameters) + end end class TestPathParameters < ActionDispatch::IntegrationTest diff --git a/actionpack/test/dispatch/session/abstract_store_test.rb b/actionpack/test/dispatch/session/abstract_store_test.rb index df81f7d7e3..fd4d359cf8 100644 --- a/actionpack/test/dispatch/session/abstract_store_test.rb +++ b/actionpack/test/dispatch/session/abstract_store_test.rb @@ -47,10 +47,10 @@ module ActionDispatch end private - def app(&block) - @env = nil - lambda { |env| @env = env } - end + def app(&block) + @env = nil + lambda { |env| @env = env } + end end end end diff --git a/actionpack/test/dispatch/url_generation_test.rb b/actionpack/test/dispatch/url_generation_test.rb index b5a792b456..0472be0d6a 100644 --- a/actionpack/test/dispatch/url_generation_test.rb +++ b/actionpack/test/dispatch/url_generation_test.rb @@ -138,4 +138,3 @@ module TestUrlGeneration end end - diff --git a/actionpack/test/fixtures/helpers/fun/games_helper.rb b/actionpack/test/fixtures/helpers/fun/games_helper.rb index 3b7adce086..2d5e50f5a5 100644 --- a/actionpack/test/fixtures/helpers/fun/games_helper.rb +++ b/actionpack/test/fixtures/helpers/fun/games_helper.rb @@ -2,4 +2,4 @@ module Fun module GamesHelper def stratego() "Iz guuut!" end end -end \ No newline at end of file +end diff --git a/actionpack/test/fixtures/helpers/just_me_helper.rb b/actionpack/test/fixtures/helpers/just_me_helper.rb index b140a7b9b4..9b43fc6d49 100644 --- a/actionpack/test/fixtures/helpers/just_me_helper.rb +++ b/actionpack/test/fixtures/helpers/just_me_helper.rb @@ -1,3 +1,3 @@ module JustMeHelper def me() "mine!" end -end \ No newline at end of file +end diff --git a/actionpack/test/fixtures/helpers/me_too_helper.rb b/actionpack/test/fixtures/helpers/me_too_helper.rb index ce56042143..8e312e7cd0 100644 --- a/actionpack/test/fixtures/helpers/me_too_helper.rb +++ b/actionpack/test/fixtures/helpers/me_too_helper.rb @@ -1,3 +1,3 @@ module MeTooHelper def me() "me too!" end -end \ No newline at end of file +end diff --git a/actionpack/test/fixtures/helpers_typo/admin/users_helper.rb b/actionpack/test/fixtures/helpers_typo/admin/users_helper.rb index 7d2326e04d..64aa1a0476 100644 --- a/actionpack/test/fixtures/helpers_typo/admin/users_helper.rb +++ b/actionpack/test/fixtures/helpers_typo/admin/users_helper.rb @@ -2,4 +2,3 @@ module Admin module UsersHelpeR end end - diff --git a/actionpack/test/journey/gtg/builder_test.rb b/actionpack/test/journey/gtg/builder_test.rb index 270bc7d741..5861cd2414 100644 --- a/actionpack/test/journey/gtg/builder_test.rb +++ b/actionpack/test/journey/gtg/builder_test.rb @@ -59,20 +59,20 @@ module ActionDispatch end private - def ast strings - parser = Journey::Parser.new - asts = strings.map { |string| - memo = Object.new - ast = parser.parse string - ast.each { |n| n.memo = memo } - ast - } - Nodes::Or.new asts - end + def ast strings + parser = Journey::Parser.new + asts = strings.map { |string| + memo = Object.new + ast = parser.parse string + ast.each { |n| n.memo = memo } + ast + } + Nodes::Or.new asts + end - def tt strings - Builder.new(ast(strings)).transition_table - end + def tt strings + Builder.new(ast(strings)).transition_table + end end end end diff --git a/actionpack/test/journey/gtg/transition_table_test.rb b/actionpack/test/journey/gtg/transition_table_test.rb index 00be1c2da6..566eb4d186 100644 --- a/actionpack/test/journey/gtg/transition_table_test.rb +++ b/actionpack/test/journey/gtg/transition_table_test.rb @@ -91,24 +91,24 @@ module ActionDispatch end private - def asts paths - parser = Journey::Parser.new - paths.map { |x| - ast = parser.parse x - ast.each { |n| n.memo = ast} - ast - } - end + def asts paths + parser = Journey::Parser.new + paths.map { |x| + ast = parser.parse x + ast.each { |n| n.memo = ast} + ast + } + end - def tt paths - x = asts paths - builder = GTG::Builder.new Nodes::Or.new x - builder.transition_table - end + def tt paths + x = asts paths + builder = GTG::Builder.new Nodes::Or.new x + builder.transition_table + end - def simulator_for paths - GTG::Simulator.new tt(paths) - end + def simulator_for paths + GTG::Simulator.new tt(paths) + end end end end diff --git a/actionpack/test/journey/nfa/transition_table_test.rb b/actionpack/test/journey/nfa/transition_table_test.rb index 81f9501688..c948880c47 100644 --- a/actionpack/test/journey/nfa/transition_table_test.rb +++ b/actionpack/test/journey/nfa/transition_table_test.rb @@ -61,11 +61,11 @@ module ActionDispatch end private - def tt string - ast = @parser.parse string - builder = Builder.new ast - builder.transition_table - end + def tt string + ast = @parser.parse string + builder = Builder.new ast + builder.transition_table + end end end end diff --git a/actionpack/test/journey/router_test.rb b/actionpack/test/journey/router_test.rb index 83cd999352..efe7bef5c5 100644 --- a/actionpack/test/journey/router_test.rb +++ b/actionpack/test/journey/router_test.rb @@ -493,41 +493,41 @@ module ActionDispatch private - def get *args - ActiveSupport::Deprecation.silence do - mapper.get(*args) + def get *args + ActiveSupport::Deprecation.silence do + mapper.get(*args) + end end - end - def match *args - ActiveSupport::Deprecation.silence do - mapper.match(*args) + def match *args + ActiveSupport::Deprecation.silence do + mapper.match(*args) + end end - end - def rails_env env, klass = ActionDispatch::Request - klass.new(rack_env(env)) - end - - def rack_env env - { - "rack.version" => [1, 1], - "rack.input" => StringIO.new, - "rack.errors" => StringIO.new, - "rack.multithread" => true, - "rack.multiprocess" => true, - "rack.run_once" => false, - "REQUEST_METHOD" => "GET", - "SERVER_NAME" => "example.org", - "SERVER_PORT" => "80", - "QUERY_STRING" => "", - "PATH_INFO" => "/content", - "rack.url_scheme" => "http", - "HTTPS" => "off", - "SCRIPT_NAME" => "", - "CONTENT_LENGTH" => "0" - }.merge env - end + def rails_env env, klass = ActionDispatch::Request + klass.new(rack_env(env)) + end + + def rack_env env + { + "rack.version" => [1, 1], + "rack.input" => StringIO.new, + "rack.errors" => StringIO.new, + "rack.multithread" => true, + "rack.multiprocess" => true, + "rack.run_once" => false, + "REQUEST_METHOD" => "GET", + "SERVER_NAME" => "example.org", + "SERVER_PORT" => "80", + "QUERY_STRING" => "", + "PATH_INFO" => "/content", + "rack.url_scheme" => "http", + "HTTPS" => "off", + "SCRIPT_NAME" => "", + "CONTENT_LENGTH" => "0" + }.merge env + end end end end diff --git a/actionview/lib/action_view/flows.rb b/actionview/lib/action_view/flows.rb index 73ebf8dd55..ed30afb83d 100644 --- a/actionview/lib/action_view/flows.rb +++ b/actionview/lib/action_view/flows.rb @@ -68,8 +68,8 @@ module ActionView private - def inside_fiber? - Fiber.current.object_id != @root - end + def inside_fiber? + Fiber.current.object_id != @root + end end end diff --git a/actionview/lib/action_view/helpers/active_model_helper.rb b/actionview/lib/action_view/helpers/active_model_helper.rb index 4f76195760..4bb5788a16 100644 --- a/actionview/lib/action_view/helpers/active_model_helper.rb +++ b/actionview/lib/action_view/helpers/active_model_helper.rb @@ -37,13 +37,13 @@ module ActionView private - def object_has_errors? - object.respond_to?(:errors) && object.errors.respond_to?(:[]) && error_message.present? - end + def object_has_errors? + object.respond_to?(:errors) && object.errors.respond_to?(:[]) && error_message.present? + end - def tag_generate_errors?(options) - options["type"] != "hidden" - end + def tag_generate_errors?(options) + options["type"] != "hidden" + end end end end diff --git a/actionview/lib/action_view/helpers/csrf_helper.rb b/actionview/lib/action_view/helpers/csrf_helper.rb index d07115a5ee..2a15d2aa5a 100644 --- a/actionview/lib/action_view/helpers/csrf_helper.rb +++ b/actionview/lib/action_view/helpers/csrf_helper.rb @@ -14,7 +14,7 @@ module ActionView # # You don't need to use these tags for regular forms as they generate their own hidden fields. # - # For AJAX requests other than GETs, extract the "csrf-token" from the meta-tag and send as the + # For AJAX requests other than GETs, extract the "csrf-token" from the meta-tag and send as the # "X-CSRF-Token" HTTP header. If you are using jQuery with jquery-rails this happens automatically. # def csrf_meta_tags diff --git a/actionview/lib/action_view/helpers/form_helper.rb b/actionview/lib/action_view/helpers/form_helper.rb index 3f7b6c0f9c..f470375988 100644 --- a/actionview/lib/action_view/helpers/form_helper.rb +++ b/actionview/lib/action_view/helpers/form_helper.rb @@ -467,7 +467,7 @@ module ActionView ) options[:url] ||= if options.key?(:format) - polymorphic_path(record, format: options.delete(:format)) + polymorphic_path(record, format: options.delete(:format)) else polymorphic_path(record, {}) end @@ -1573,7 +1573,7 @@ module ActionView end record_name = if index - "#{object_name}[#{index}][#{record_name}]" + "#{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}" diff --git a/actionview/lib/action_view/helpers/number_helper.rb b/actionview/lib/action_view/helpers/number_helper.rb index 3f665b39a3..9540850004 100644 --- a/actionview/lib/action_view/helpers/number_helper.rb +++ b/actionview/lib/action_view/helpers/number_helper.rb @@ -393,53 +393,53 @@ module ActionView private - def delegate_number_helper_method(method, number, options) - return unless number - options = escape_unsafe_options(options.symbolize_keys) + def delegate_number_helper_method(method, number, options) + return unless number + options = escape_unsafe_options(options.symbolize_keys) - wrap_with_output_safety_handling(number, options.delete(:raise)) { - ActiveSupport::NumberHelper.public_send(method, number, options) - } - end + wrap_with_output_safety_handling(number, options.delete(:raise)) { + ActiveSupport::NumberHelper.public_send(method, number, options) + } + end - def escape_unsafe_options(options) - options[:format] = ERB::Util.html_escape(options[:format]) if options[:format] - options[:negative_format] = ERB::Util.html_escape(options[:negative_format]) if options[:negative_format] - options[:separator] = ERB::Util.html_escape(options[:separator]) if options[:separator] - options[:delimiter] = ERB::Util.html_escape(options[:delimiter]) if options[:delimiter] - options[:unit] = ERB::Util.html_escape(options[:unit]) if options[:unit] && !options[:unit].html_safe? - options[:units] = escape_units(options[:units]) if options[:units] && Hash === options[:units] - options - end + def escape_unsafe_options(options) + options[:format] = ERB::Util.html_escape(options[:format]) if options[:format] + options[:negative_format] = ERB::Util.html_escape(options[:negative_format]) if options[:negative_format] + options[:separator] = ERB::Util.html_escape(options[:separator]) if options[:separator] + options[:delimiter] = ERB::Util.html_escape(options[:delimiter]) if options[:delimiter] + options[:unit] = ERB::Util.html_escape(options[:unit]) if options[:unit] && !options[:unit].html_safe? + options[:units] = escape_units(options[:units]) if options[:units] && Hash === options[:units] + options + end - def escape_units(units) - Hash[units.map do |k, v| - [k, ERB::Util.html_escape(v)] - end] - end + def escape_units(units) + Hash[units.map do |k, v| + [k, ERB::Util.html_escape(v)] + end] + end - def wrap_with_output_safety_handling(number, raise_on_invalid, &block) - valid_float = valid_float?(number) - raise InvalidNumberError, number if raise_on_invalid && !valid_float + def wrap_with_output_safety_handling(number, raise_on_invalid, &block) + valid_float = valid_float?(number) + raise InvalidNumberError, number if raise_on_invalid && !valid_float - formatted_number = yield + formatted_number = yield - if valid_float || number.html_safe? - formatted_number.html_safe - else - formatted_number + if valid_float || number.html_safe? + formatted_number.html_safe + else + formatted_number + end end - end - def valid_float?(number) - !parse_float(number, false).nil? - end + def valid_float?(number) + !parse_float(number, false).nil? + end - def parse_float(number, raise_error) - Float(number) - rescue ArgumentError, TypeError - raise InvalidNumberError, number if raise_error - end + def parse_float(number, raise_error) + Float(number) + rescue ArgumentError, TypeError + raise InvalidNumberError, number if raise_error + end end end end diff --git a/actionview/lib/action_view/helpers/tags/base.rb b/actionview/lib/action_view/helpers/tags/base.rb index a86600aeb9..43335023ce 100644 --- a/actionview/lib/action_view/helpers/tags/base.rb +++ b/actionview/lib/action_view/helpers/tags/base.rb @@ -24,136 +24,136 @@ module ActionView private - def value(object) - object.public_send @method_name if object - end + def value(object) + object.public_send @method_name if object + end - def value_before_type_cast(object) - unless object.nil? - method_before_type_cast = @method_name + "_before_type_cast" + def value_before_type_cast(object) + unless object.nil? + method_before_type_cast = @method_name + "_before_type_cast" - if value_came_from_user?(object) && object.respond_to?(method_before_type_cast) - object.public_send(method_before_type_cast) - else - value(object) + if value_came_from_user?(object) && object.respond_to?(method_before_type_cast) + object.public_send(method_before_type_cast) + else + value(object) + end end end - end - def value_came_from_user?(object) - method_name = "#{@method_name}_came_from_user?" - !object.respond_to?(method_name) || object.public_send(method_name) - end + def value_came_from_user?(object) + method_name = "#{@method_name}_came_from_user?" + !object.respond_to?(method_name) || object.public_send(method_name) + end - def retrieve_object(object) - if object - object - elsif @template_object.instance_variable_defined?("@#{@object_name}") - @template_object.instance_variable_get("@#{@object_name}") + def retrieve_object(object) + if object + object + elsif @template_object.instance_variable_defined?("@#{@object_name}") + @template_object.instance_variable_get("@#{@object_name}") + end + rescue NameError + # As @object_name may contain the nested syntax (item[subobject]) we need to fallback to nil. + nil end - rescue NameError - # As @object_name may contain the nested syntax (item[subobject]) we need to fallback to nil. - nil - end - def retrieve_autoindex(pre_match) - object = self.object || @template_object.instance_variable_get("@#{pre_match}") - if object && object.respond_to?(:to_param) - object.to_param - else - raise ArgumentError, "object[] naming but object param and @object var don't exist or don't respond to to_param: #{object.inspect}" + def retrieve_autoindex(pre_match) + object = self.object || @template_object.instance_variable_get("@#{pre_match}") + if object && object.respond_to?(:to_param) + object.to_param + else + raise ArgumentError, "object[] naming but object param and @object var don't exist or don't respond to to_param: #{object.inspect}" + end end - end - def add_default_name_and_id_for_value(tag_value, options) - if tag_value.nil? - add_default_name_and_id(options) - else - specified_id = options["id"] - add_default_name_and_id(options) + def add_default_name_and_id_for_value(tag_value, options) + if tag_value.nil? + add_default_name_and_id(options) + else + specified_id = options["id"] + add_default_name_and_id(options) - if specified_id.blank? && options["id"].present? - options["id"] += "_#{sanitized_value(tag_value)}" + if specified_id.blank? && options["id"].present? + options["id"] += "_#{sanitized_value(tag_value)}" + end end end - end - 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) } - if namespace = options.delete("namespace") - options["id"] = options["id"] ? "#{namespace}_#{options['id']}" : namespace + 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) } + if namespace = options.delete("namespace") + options["id"] = options["id"] ? "#{namespace}_#{options['id']}" : namespace + end end - end - def tag_name(multiple = false, index = nil) - # a little duplication to construct less strings - if index - "#{@object_name}[#{index}][#{sanitized_method_name}]#{"[]" if multiple}" - else - "#{@object_name}[#{sanitized_method_name}]#{"[]" if multiple}" + def tag_name(multiple = false, index = nil) + # a little duplication to construct less strings + if index + "#{@object_name}[#{index}][#{sanitized_method_name}]#{"[]" if multiple}" + else + "#{@object_name}[#{sanitized_method_name}]#{"[]" if multiple}" + end end - end - def tag_id(index = nil) - # a little duplication to construct less strings - if index - "#{sanitized_object_name}_#{index}_#{sanitized_method_name}" - else - "#{sanitized_object_name}_#{sanitized_method_name}" + def tag_id(index = nil) + # a little duplication to construct less strings + if index + "#{sanitized_object_name}_#{index}_#{sanitized_method_name}" + else + "#{sanitized_object_name}_#{sanitized_method_name}" + end end - end - def sanitized_object_name - @sanitized_object_name ||= @object_name.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "") - end + def sanitized_object_name + @sanitized_object_name ||= @object_name.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "") + end - def sanitized_method_name - @sanitized_method_name ||= @method_name.sub(/\?$/,"") - end + def sanitized_method_name + @sanitized_method_name ||= @method_name.sub(/\?$/,"") + end - def sanitized_value(value) - value.to_s.gsub(/\s/, "_").gsub(/[^-\w]/, "").downcase - end + def sanitized_value(value) + value.to_s.gsub(/\s/, "_").gsub(/[^-\w]/, "").downcase + end - def select_content_tag(option_tags, options, html_options) - html_options = html_options.stringify_keys - add_default_name_and_id(html_options) + def select_content_tag(option_tags, options, html_options) + html_options = html_options.stringify_keys + add_default_name_and_id(html_options) - if placeholder_required?(html_options) - raise ArgumentError, "include_blank cannot be false for a required field." if options[:include_blank] == false - options[:include_blank] ||= true unless options[:prompt] - end + if placeholder_required?(html_options) + raise ArgumentError, "include_blank cannot be false for a required field." if options[:include_blank] == false + options[:include_blank] ||= true unless options[:prompt] + end - value = options.fetch(:selected) { value(object) } - select = content_tag("select", add_options(option_tags, options, value), html_options) + value = options.fetch(:selected) { value(object) } + select = content_tag("select", add_options(option_tags, options, value), html_options) - if html_options["multiple"] && options.fetch(:include_hidden, true) - tag("input", disabled: html_options["disabled"], name: html_options["name"], type: "hidden", value: "") + select - else - select + if html_options["multiple"] && options.fetch(:include_hidden, true) + tag("input", disabled: html_options["disabled"], name: html_options["name"], type: "hidden", value: "") + select + else + select + end end - end - def placeholder_required?(html_options) - # See https://html.spec.whatwg.org/multipage/forms.html#attr-select-required - html_options["required"] && !html_options["multiple"] && html_options.fetch("size", 1).to_i == 1 - end - - def add_options(option_tags, options, value = nil) - if options[:include_blank] - option_tags = tag_builder.content_tag_string("option", options[:include_blank].kind_of?(String) ? options[:include_blank] : nil, value: "") + "\n" + option_tags + def placeholder_required?(html_options) + # See https://html.spec.whatwg.org/multipage/forms.html#attr-select-required + html_options["required"] && !html_options["multiple"] && html_options.fetch("size", 1).to_i == 1 end - if value.blank? && options[:prompt] - option_tags = tag_builder.content_tag_string("option", prompt_text(options[:prompt]), value: "") + "\n" + option_tags + + def add_options(option_tags, options, value = nil) + if options[:include_blank] + option_tags = tag_builder.content_tag_string("option", options[:include_blank].kind_of?(String) ? options[:include_blank] : nil, value: "") + "\n" + option_tags + end + if value.blank? && options[:prompt] + option_tags = tag_builder.content_tag_string("option", prompt_text(options[:prompt]), value: "") + "\n" + option_tags + end + option_tags end - option_tags - end - def name_and_id_index(options) - options.key?("index") ? options.delete("index") || "" : @auto_index - end + def name_and_id_index(options) + options.key?("index") ? options.delete("index") || "" : @auto_index + end end end end diff --git a/actionview/lib/action_view/helpers/tags/check_box.rb b/actionview/lib/action_view/helpers/tags/check_box.rb index 653643d692..02f87fc89f 100644 --- a/actionview/lib/action_view/helpers/tags/check_box.rb +++ b/actionview/lib/action_view/helpers/tags/check_box.rb @@ -38,26 +38,26 @@ module ActionView private - def checked?(value) - case value - when TrueClass, FalseClass - value == !!@checked_value - when NilClass - false - when String - value == @checked_value - else - if value.respond_to?(:include?) - value.include?(@checked_value) + def checked?(value) + case value + when TrueClass, FalseClass + value == !!@checked_value + when NilClass + false + when String + value == @checked_value else - value.to_i == @checked_value.to_i + if value.respond_to?(:include?) + value.include?(@checked_value) + else + value.to_i == @checked_value.to_i + end end end - end - def hidden_field_for_checkbox(options) - @unchecked_value ? tag("input", options.slice("name", "disabled", "form").merge!("type" => "hidden", "value" => @unchecked_value)) : "".html_safe - end + def hidden_field_for_checkbox(options) + @unchecked_value ? tag("input", options.slice("name", "disabled", "form").merge!("type" => "hidden", "value" => @unchecked_value)) : "".html_safe + end end end end diff --git a/actionview/lib/action_view/helpers/tags/collection_check_boxes.rb b/actionview/lib/action_view/helpers/tags/collection_check_boxes.rb index 59eacbff8b..2a6bf49567 100644 --- a/actionview/lib/action_view/helpers/tags/collection_check_boxes.rb +++ b/actionview/lib/action_view/helpers/tags/collection_check_boxes.rb @@ -20,13 +20,13 @@ module ActionView private - def render_component(builder) - builder.check_box + builder.label - end + def render_component(builder) + builder.check_box + builder.label + end - def hidden_field_name #:nodoc: - "#{super}[]" - end + def hidden_field_name #:nodoc: + "#{super}[]" + end end end end diff --git a/actionview/lib/action_view/helpers/tags/collection_helpers.rb b/actionview/lib/action_view/helpers/tags/collection_helpers.rb index 7607fe64d0..70d7c484eb 100644 --- a/actionview/lib/action_view/helpers/tags/collection_helpers.rb +++ b/actionview/lib/action_view/helpers/tags/collection_helpers.rb @@ -36,81 +36,81 @@ module ActionView private - def instantiate_builder(builder_class, item, value, text, html_options) - builder_class.new(@template_object, @object_name, @method_name, item, - sanitize_attribute_name(value), text, value, html_options) - end + def instantiate_builder(builder_class, item, value, text, html_options) + builder_class.new(@template_object, @object_name, @method_name, item, + sanitize_attribute_name(value), text, value, html_options) + end # Generate default options for collection helpers, such as :checked and # :disabled. - def default_html_options_for_collection(item, value) #:nodoc: - html_options = @html_options.dup - - [:checked, :selected, :disabled, :readonly].each do |option| - current_value = @options[option] - next if current_value.nil? - - accept = if current_value.respond_to?(:call) - current_value.call(item) - else - Array(current_value).map(&:to_s).include?(value.to_s) + def default_html_options_for_collection(item, value) #:nodoc: + html_options = @html_options.dup + + [:checked, :selected, :disabled, :readonly].each do |option| + current_value = @options[option] + next if current_value.nil? + + accept = if current_value.respond_to?(:call) + current_value.call(item) + else + Array(current_value).map(&:to_s).include?(value.to_s) + end + + if accept + html_options[option] = true + elsif option == :checked + html_options[option] = false + end end - if accept - html_options[option] = true - elsif option == :checked - html_options[option] = false - end + html_options[:object] = @object + html_options end - html_options[:object] = @object - html_options - end + def sanitize_attribute_name(value) #:nodoc: + "#{sanitized_method_name}_#{sanitized_value(value)}" + end - def sanitize_attribute_name(value) #:nodoc: - "#{sanitized_method_name}_#{sanitized_value(value)}" - end + def render_collection #:nodoc: + @collection.map do |item| + value = value_for_collection(item, @value_method) + text = value_for_collection(item, @text_method) + default_html_options = default_html_options_for_collection(item, value) + additional_html_options = option_html_attributes(item) - def render_collection #:nodoc: - @collection.map do |item| - value = value_for_collection(item, @value_method) - text = value_for_collection(item, @text_method) - default_html_options = default_html_options_for_collection(item, value) - additional_html_options = option_html_attributes(item) + yield item, value, text, default_html_options.merge(additional_html_options) + end.join.html_safe + end - yield item, value, text, default_html_options.merge(additional_html_options) - end.join.html_safe - end + def render_collection_for(builder_class, &block) #:nodoc: + options = @options.stringify_keys + rendered_collection = render_collection do |item, value, text, default_html_options| + builder = instantiate_builder(builder_class, item, value, text, default_html_options) - def render_collection_for(builder_class, &block) #:nodoc: - options = @options.stringify_keys - rendered_collection = render_collection do |item, value, text, default_html_options| - builder = instantiate_builder(builder_class, item, value, text, default_html_options) + if block_given? + @template_object.capture(builder, &block) + else + render_component(builder) + end + end - if block_given? - @template_object.capture(builder, &block) + # Prepend a hidden field to make sure something will be sent back to the + # server if all radio buttons are unchecked. + if options.fetch("include_hidden", true) + hidden_field + rendered_collection else - render_component(builder) + rendered_collection end end - # Prepend a hidden field to make sure something will be sent back to the - # server if all radio buttons are unchecked. - if options.fetch("include_hidden", true) - hidden_field + rendered_collection - else - rendered_collection + def hidden_field #:nodoc: + hidden_name = @html_options[:name] || hidden_field_name + @template_object.hidden_field_tag(hidden_name, "", id: nil) end - end - def hidden_field #:nodoc: - hidden_name = @html_options[:name] || hidden_field_name - @template_object.hidden_field_tag(hidden_name, "", id: nil) - end - - def hidden_field_name #:nodoc: - "#{tag_name(false, @options[:index])}" - end + def hidden_field_name #:nodoc: + "#{tag_name(false, @options[:index])}" + end end end end diff --git a/actionview/lib/action_view/helpers/tags/date_select.rb b/actionview/lib/action_view/helpers/tags/date_select.rb index 602f393ddb..006605885a 100644 --- a/actionview/lib/action_view/helpers/tags/date_select.rb +++ b/actionview/lib/action_view/helpers/tags/date_select.rb @@ -22,50 +22,50 @@ module ActionView private - def select_type - self.class.select_type - end + def select_type + self.class.select_type + end - def datetime_selector(options, html_options) - datetime = options.fetch(:selected) { value(object) || default_datetime(options) } - @auto_index ||= nil + def datetime_selector(options, html_options) + datetime = options.fetch(:selected) { value(object) || default_datetime(options) } + @auto_index ||= nil - options = options.dup - options[:field_name] = @method_name - options[:include_position] = true - options[:prefix] ||= @object_name - options[:index] = @auto_index if @auto_index && !options.has_key?(:index) + options = options.dup + options[:field_name] = @method_name + options[:include_position] = true + options[:prefix] ||= @object_name + options[:index] = @auto_index if @auto_index && !options.has_key?(:index) - DateTimeSelector.new(datetime, options, html_options) - end + DateTimeSelector.new(datetime, options, html_options) + end - def default_datetime(options) - return if options[:include_blank] || options[:prompt] + def default_datetime(options) + return if options[:include_blank] || options[:prompt] - case options[:default] - when nil - Time.current - when Date, Time - options[:default] - else - default = options[:default].dup + case options[:default] + when nil + Time.current + when Date, Time + options[:default] + else + default = options[:default].dup - # Rename :minute and :second to :min and :sec - default[:min] ||= default[:minute] - default[:sec] ||= default[:second] + # Rename :minute and :second to :min and :sec + default[:min] ||= default[:minute] + default[:sec] ||= default[:second] - time = Time.current + time = Time.current - [:year, :month, :day, :hour, :min, :sec].each do |key| - default[key] ||= time.send(key) - end + [:year, :month, :day, :hour, :min, :sec].each do |key| + default[key] ||= time.send(key) + end - Time.utc( - default[:year], default[:month], default[:day], - default[:hour], default[:min], default[:sec] - ) + Time.utc( + default[:year], default[:month], default[:day], + default[:hour], default[:min], default[:sec] + ) + end end - end end end end diff --git a/actionview/lib/action_view/helpers/tags/radio_button.rb b/actionview/lib/action_view/helpers/tags/radio_button.rb index 1232183dee..43dbd32083 100644 --- a/actionview/lib/action_view/helpers/tags/radio_button.rb +++ b/actionview/lib/action_view/helpers/tags/radio_button.rb @@ -22,9 +22,9 @@ module ActionView private - def checked?(value) - value.to_s == @tag_value.to_s - end + def checked?(value) + value.to_s == @tag_value.to_s + end end end end diff --git a/actionview/lib/action_view/helpers/tags/select.rb b/actionview/lib/action_view/helpers/tags/select.rb index dcfe8ae757..8cc34e3180 100644 --- a/actionview/lib/action_view/helpers/tags/select.rb +++ b/actionview/lib/action_view/helpers/tags/select.rb @@ -32,9 +32,9 @@ module ActionView # # [nil, []] # { nil => [] } - def grouped_choices? - !@choices.empty? && @choices.first.respond_to?(:last) && Array === @choices.first.last - end + def grouped_choices? + !@choices.empty? && @choices.first.respond_to?(:last) && Array === @choices.first.last + end end end end diff --git a/actionview/lib/action_view/helpers/tags/text_field.rb b/actionview/lib/action_view/helpers/tags/text_field.rb index 9201f8d491..4306c3543d 100644 --- a/actionview/lib/action_view/helpers/tags/text_field.rb +++ b/actionview/lib/action_view/helpers/tags/text_field.rb @@ -23,9 +23,9 @@ module ActionView private - def field_type - self.class.field_type - end + def field_type + self.class.field_type + end end end end diff --git a/actionview/lib/action_view/helpers/tags/translator.rb b/actionview/lib/action_view/helpers/tags/translator.rb index 8b6655481d..62b1df81c6 100644 --- a/actionview/lib/action_view/helpers/tags/translator.rb +++ b/actionview/lib/action_view/helpers/tags/translator.rb @@ -16,24 +16,24 @@ module ActionView protected - attr_reader :object_name, :method_and_value, :scope, :model + attr_reader :object_name, :method_and_value, :scope, :model private - def i18n_default - if model - key = model.model_name.i18n_key - ["#{key}.#{method_and_value}".to_sym, ""] - else - "" + def i18n_default + if model + key = model.model_name.i18n_key + ["#{key}.#{method_and_value}".to_sym, ""] + else + "" + end end - end - def human_attribute_name - if model && model.class.respond_to?(:human_attribute_name) - model.class.human_attribute_name(method_and_value) + def human_attribute_name + if model && model.class.respond_to?(:human_attribute_name) + model.class.human_attribute_name(method_and_value) + end end - end end end end diff --git a/actionview/lib/action_view/helpers/text_helper.rb b/actionview/lib/action_view/helpers/text_helper.rb index cb812bd5ba..0fea4df09c 100644 --- a/actionview/lib/action_view/helpers/text_helper.rb +++ b/actionview/lib/action_view/helpers/text_helper.rb @@ -432,17 +432,17 @@ module ActionView private - def next_index - step_index(1) - end + def next_index + step_index(1) + end - def previous_index - step_index(-1) - end + def previous_index + step_index(-1) + end - def step_index(n) - (@index + n) % @values.size - end + def step_index(n) + (@index + n) % @values.size + end end private diff --git a/actionview/lib/action_view/layouts.rb b/actionview/lib/action_view/layouts.rb index f1730a5aae..bf36dde181 100644 --- a/actionview/lib/action_view/layouts.rb +++ b/actionview/lib/action_view/layouts.rb @@ -230,19 +230,19 @@ module ActionView # # ==== Returns # * Boolean - True if the action has a layout definition, false otherwise. - def _conditional_layout? - return unless super + def _conditional_layout? + return unless super - conditions = _layout_conditions + conditions = _layout_conditions - if only = conditions[:only] - only.include?(action_name) - elsif except = conditions[:except] - !except.include?(action_name) - else - true + if only = conditions[:only] + only.include?(action_name) + elsif except = conditions[:except] + !except.include?(action_name) + else + true + end end - end end # Specify the layout to use for this class. @@ -338,9 +338,9 @@ module ActionView # # ==== Returns # * String - A template name - def _implied_layout_name # :nodoc: - controller_path - end + def _implied_layout_name # :nodoc: + controller_path + end end def _normalize_options(options) # :nodoc: diff --git a/actionview/lib/action_view/path_set.rb b/actionview/lib/action_view/path_set.rb index f68d2a77ed..6688519ffd 100644 --- a/actionview/lib/action_view/path_set.rb +++ b/actionview/lib/action_view/path_set.rb @@ -69,30 +69,30 @@ module ActionView #:nodoc: private - def _find_all(path, prefixes, args, outside_app) - prefixes = [prefixes] if String === prefixes - prefixes.each do |prefix| - paths.each do |resolver| - if outside_app - templates = resolver.find_all_anywhere(path, prefix, *args) - else - templates = resolver.find_all(path, prefix, *args) + def _find_all(path, prefixes, args, outside_app) + prefixes = [prefixes] if String === prefixes + prefixes.each do |prefix| + paths.each do |resolver| + if outside_app + templates = resolver.find_all_anywhere(path, prefix, *args) + else + templates = resolver.find_all(path, prefix, *args) + end + return templates unless templates.empty? end - return templates unless templates.empty? end + [] end - [] - end - def typecast(paths) - paths.map do |path| - case path - when Pathname, String - OptimizedFileSystemResolver.new path.to_s - else - path + def typecast(paths) + paths.map do |path| + case path + when Pathname, String + OptimizedFileSystemResolver.new path.to_s + else + path + end end end - end end end diff --git a/actionview/lib/action_view/renderer/abstract_renderer.rb b/actionview/lib/action_view/renderer/abstract_renderer.rb index baff791987..3c85be49cd 100644 --- a/actionview/lib/action_view/renderer/abstract_renderer.rb +++ b/actionview/lib/action_view/renderer/abstract_renderer.rb @@ -27,27 +27,27 @@ module ActionView protected - def extract_details(options) - @lookup_context.registered_details.each_with_object({}) do |key, details| - value = options[key] + def extract_details(options) + @lookup_context.registered_details.each_with_object({}) do |key, details| + value = options[key] - details[key] = Array(value) if value + details[key] = Array(value) if value + end end - end - def instrument(name, **options) - options[:identifier] ||= (@template && @template.identifier) || @path + def instrument(name, **options) + options[:identifier] ||= (@template && @template.identifier) || @path - ActiveSupport::Notifications.instrument("render_#{name}.action_view", options) do |payload| - yield payload + ActiveSupport::Notifications.instrument("render_#{name}.action_view", options) do |payload| + yield payload + end end - end - def prepend_formats(formats) - formats = Array(formats) - return if formats.empty? || @lookup_context.html_fallback_for_js + def prepend_formats(formats) + formats = Array(formats) + return if formats.empty? || @lookup_context.html_fallback_for_js - @lookup_context.formats = formats | @lookup_context.formats - end + @lookup_context.formats = formats | @lookup_context.formats + end end end diff --git a/actionview/lib/action_view/renderer/partial_renderer.rb b/actionview/lib/action_view/renderer/partial_renderer.rb index 114e4092af..1509726a37 100644 --- a/actionview/lib/action_view/renderer/partial_renderer.rb +++ b/actionview/lib/action_view/renderer/partial_renderer.rb @@ -316,38 +316,38 @@ module ActionView private - def render_collection - instrument(:collection, count: @collection.size) do |payload| - return nil if @collection.blank? + def render_collection + instrument(:collection, count: @collection.size) do |payload| + return nil if @collection.blank? - if @options.key?(:spacer_template) - spacer = find_template(@options[:spacer_template], @locals.keys).render(@view, @locals) - end + if @options.key?(:spacer_template) + spacer = find_template(@options[:spacer_template], @locals.keys).render(@view, @locals) + end - cache_collection_render(payload) do - @template ? collection_with_template : collection_without_template - end.join(spacer).html_safe + cache_collection_render(payload) do + @template ? collection_with_template : collection_without_template + end.join(spacer).html_safe + end end - end - def render_partial - view, locals, block = @view, @locals, @block - object, as = @object, @variable + def render_partial + view, locals, block = @view, @locals, @block + object, as = @object, @variable - if !block && (layout = @options[:layout]) - layout = find_template(layout.to_s, @template_keys) - end + if !block && (layout = @options[:layout]) + layout = find_template(layout.to_s, @template_keys) + end - object = locals[as] if object.nil? # Respect object when object is false - locals[as] = object if @has_object + object = locals[as] if object.nil? # Respect object when object is false + locals[as] = object if @has_object - content = @template.render(view, locals) do |*name| - view._layout_for(*name, &block) - end + content = @template.render(view, locals) do |*name| + view._layout_for(*name, &block) + end - content = layout.render(view, locals){ content } if layout - content - end + content = layout.render(view, locals){ content } if layout + content + end # Sets up instance variables needed for rendering a partial. This method # finds the options and details and extracts them. The method also contains @@ -356,114 +356,114 @@ module ActionView # If +options[:partial]+ is a string, then the +@path+ instance variable is # set to that string. Otherwise, the +options[:partial]+ object must # respond to +to_partial_path+ in order to setup the path. - def setup(context, options, block) - @view = context - @options = options - @block = block + def setup(context, options, block) + @view = context + @options = options + @block = block - @locals = options[:locals] || {} - @details = extract_details(options) + @locals = options[:locals] || {} + @details = extract_details(options) - prepend_formats(options[:formats]) + prepend_formats(options[:formats]) - partial = options[:partial] + partial = options[:partial] - if String === partial - @has_object = options.key?(:object) - @object = options[:object] - @collection = collection_from_options - @path = partial - else - @has_object = true - @object = partial - @collection = collection_from_object || collection_from_options + if String === partial + @has_object = options.key?(:object) + @object = options[:object] + @collection = collection_from_options + @path = partial + else + @has_object = true + @object = partial + @collection = collection_from_object || collection_from_options + + if @collection + paths = @collection_data = @collection.map { |o| partial_path(o) } + @path = paths.uniq.one? ? paths.first : nil + else + @path = partial_path + end + end - if @collection - paths = @collection_data = @collection.map { |o| partial_path(o) } - @path = paths.uniq.one? ? paths.first : nil + if as = options[:as] + raise_invalid_option_as(as) unless /\A[a-z_]\w*\z/.match?(as.to_s) + as = as.to_sym + end + + if @path + @variable, @variable_counter, @variable_iteration = retrieve_variable(@path, as) + @template_keys = retrieve_template_keys else - @path = partial_path + paths.map! { |path| retrieve_variable(path, as).unshift(path) } end + + self end - if as = options[:as] - raise_invalid_option_as(as) unless /\A[a-z_]\w*\z/.match?(as.to_s) - as = as.to_sym + def collection_from_options + if @options.key?(:collection) + collection = @options[:collection] + collection ? collection.to_a : [] + end end - if @path - @variable, @variable_counter, @variable_iteration = retrieve_variable(@path, as) - @template_keys = retrieve_template_keys - else - paths.map! { |path| retrieve_variable(path, as).unshift(path) } + def collection_from_object + @object.to_ary if @object.respond_to?(:to_ary) end - self - end + def find_partial + find_template(@path, @template_keys) if @path + end - def collection_from_options - if @options.key?(:collection) - collection = @options[:collection] - collection ? collection.to_a : [] + def find_template(path, locals) + prefixes = path.include?(?/) ? [] : @lookup_context.prefixes + @lookup_context.find_template(path, prefixes, true, locals, @details) end - end - def collection_from_object - @object.to_ary if @object.respond_to?(:to_ary) - end + def collection_with_template + view, locals, template = @view, @locals, @template + as, counter, iteration = @variable, @variable_counter, @variable_iteration - def find_partial - find_template(@path, @template_keys) if @path - end + if layout = @options[:layout] + layout = find_template(layout, @template_keys) + end - def find_template(path, locals) - prefixes = path.include?(?/) ? [] : @lookup_context.prefixes - @lookup_context.find_template(path, prefixes, true, locals, @details) - end + partial_iteration = PartialIteration.new(@collection.size) + locals[iteration] = partial_iteration - def collection_with_template - view, locals, template = @view, @locals, @template - as, counter, iteration = @variable, @variable_counter, @variable_iteration + @collection.map do |object| + locals[as] = object + locals[counter] = partial_iteration.index - if layout = @options[:layout] - layout = find_template(layout, @template_keys) + content = template.render(view, locals) + content = layout.render(view, locals) { content } if layout + partial_iteration.iterate! + content + end end - partial_iteration = PartialIteration.new(@collection.size) - locals[iteration] = partial_iteration - - @collection.map do |object| - locals[as] = object - locals[counter] = partial_iteration.index - - content = template.render(view, locals) - content = layout.render(view, locals) { content } if layout - partial_iteration.iterate! - content - end - end + def collection_without_template + view, locals, collection_data = @view, @locals, @collection_data + cache = {} + keys = @locals.keys - def collection_without_template - view, locals, collection_data = @view, @locals, @collection_data - cache = {} - keys = @locals.keys + partial_iteration = PartialIteration.new(@collection.size) - partial_iteration = PartialIteration.new(@collection.size) + @collection.map do |object| + index = partial_iteration.index + path, as, counter, iteration = collection_data[index] - @collection.map do |object| - index = partial_iteration.index - path, as, counter, iteration = collection_data[index] + locals[as] = object + locals[counter] = index + locals[iteration] = partial_iteration - locals[as] = object - locals[counter] = index - locals[iteration] = partial_iteration - - template = (cache[path] ||= find_template(path, keys + [as, counter])) - content = template.render(view, locals) - partial_iteration.iterate! - content + template = (cache[path] ||= find_template(path, keys + [as, counter])) + content = template.render(view, locals) + partial_iteration.iterate! + content + end end - end # Obtains the path to where the object's partial is located. If the object # responds to +to_partial_path+, then +to_partial_path+ will be called and @@ -472,79 +472,79 @@ module ActionView # # If +prefix_partial_path_with_controller_namespace+ is true, then this # method will prefix the partial paths with a namespace. - def partial_path(object = @object) - object = object.to_model if object.respond_to?(:to_model) + def partial_path(object = @object) + object = object.to_model if object.respond_to?(:to_model) - path = if object.respond_to?(:to_partial_path) - object.to_partial_path - else - raise ArgumentError.new("'#{object.inspect}' is not an ActiveModel-compatible object. It must implement :to_partial_path.") + path = if object.respond_to?(:to_partial_path) + object.to_partial_path + else + raise ArgumentError.new("'#{object.inspect}' is not an ActiveModel-compatible object. It must implement :to_partial_path.") + end + + if @view.prefix_partial_path_with_controller_namespace + prefixed_partial_names[path] ||= merge_prefix_into_object_path(@context_prefix, path.dup) + else + path + end end - if @view.prefix_partial_path_with_controller_namespace - prefixed_partial_names[path] ||= merge_prefix_into_object_path(@context_prefix, path.dup) - else - path + def prefixed_partial_names + @prefixed_partial_names ||= PREFIXED_PARTIAL_NAMES[@context_prefix] end - end - def prefixed_partial_names - @prefixed_partial_names ||= PREFIXED_PARTIAL_NAMES[@context_prefix] - end + def merge_prefix_into_object_path(prefix, object_path) + if prefix.include?(?/) && object_path.include?(?/) + prefixes = [] + prefix_array = File.dirname(prefix).split("/") + object_path_array = object_path.split("/")[0..-3] # skip model dir & partial - def merge_prefix_into_object_path(prefix, object_path) - if prefix.include?(?/) && object_path.include?(?/) - prefixes = [] - prefix_array = File.dirname(prefix).split("/") - object_path_array = object_path.split("/")[0..-3] # skip model dir & partial + prefix_array.each_with_index do |dir, index| + break if dir == object_path_array[index] + prefixes << dir + end - prefix_array.each_with_index do |dir, index| - break if dir == object_path_array[index] - prefixes << dir + (prefixes << object_path).join("/") + else + object_path end - - (prefixes << object_path).join("/") - else - object_path end - end - def retrieve_template_keys - keys = @locals.keys - keys << @variable if @has_object || @collection - if @collection - keys << @variable_counter - keys << @variable_iteration + def retrieve_template_keys + keys = @locals.keys + keys << @variable if @has_object || @collection + if @collection + keys << @variable_counter + keys << @variable_iteration + end + keys end - keys - end - def retrieve_variable(path, as) - variable = as || begin - base = path[-1] == "/".freeze ? "".freeze : File.basename(path) - raise_invalid_identifier(path) unless base =~ /\A_?(.*?)(?:\.\w+)*\z/ - $1.to_sym - end - if @collection - variable_counter = :"#{variable}_counter" - variable_iteration = :"#{variable}_iteration" + def retrieve_variable(path, as) + variable = as || begin + base = path[-1] == "/".freeze ? "".freeze : File.basename(path) + raise_invalid_identifier(path) unless base =~ /\A_?(.*?)(?:\.\w+)*\z/ + $1.to_sym + end + if @collection + variable_counter = :"#{variable}_counter" + variable_iteration = :"#{variable}_iteration" + end + [variable, variable_counter, variable_iteration] end - [variable, variable_counter, variable_iteration] - end - IDENTIFIER_ERROR_MESSAGE = "The partial name (%s) is not a valid Ruby identifier; " + - "make sure your partial name starts with underscore." + IDENTIFIER_ERROR_MESSAGE = "The partial name (%s) is not a valid Ruby identifier; " + + "make sure your partial name starts with underscore." - OPTION_AS_ERROR_MESSAGE = "The value (%s) of the option `as` is not a valid Ruby identifier; " + - "make sure it starts with lowercase letter, " + - "and is followed by any combination of letters, numbers and underscores." + OPTION_AS_ERROR_MESSAGE = "The value (%s) of the option `as` is not a valid Ruby identifier; " + + "make sure it starts with lowercase letter, " + + "and is followed by any combination of letters, numbers and underscores." - def raise_invalid_identifier(path) - raise ArgumentError.new(IDENTIFIER_ERROR_MESSAGE % (path)) - end + def raise_invalid_identifier(path) + raise ArgumentError.new(IDENTIFIER_ERROR_MESSAGE % (path)) + end - def raise_invalid_option_as(as) - raise ArgumentError.new(OPTION_AS_ERROR_MESSAGE % (as)) - end + def raise_invalid_option_as(as) + raise ArgumentError.new(OPTION_AS_ERROR_MESSAGE % (as)) + end end end diff --git a/actionview/lib/action_view/renderer/streaming_template_renderer.rb b/actionview/lib/action_view/renderer/streaming_template_renderer.rb index f49cf589f8..0323ebef6a 100644 --- a/actionview/lib/action_view/renderer/streaming_template_renderer.rb +++ b/actionview/lib/action_view/renderer/streaming_template_renderer.rb @@ -29,15 +29,15 @@ module ActionView # This is the same logging logic as in ShowExceptions middleware. # TODO Once "exceptron" is in, refactor this piece to simply re-use exceptron. - def log_error(exception) #:nodoc: - logger = ActionView::Base.logger - return unless logger - - message = "\n#{exception.class} (#{exception.message}):\n" - message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code) - message << " " << exception.backtrace.join("\n ") - logger.fatal("#{message}\n\n") - end + def log_error(exception) #:nodoc: + logger = ActionView::Base.logger + return unless logger + + message = "\n#{exception.class} (#{exception.message}):\n" + message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code) + message << " " << exception.backtrace.join("\n ") + logger.fatal("#{message}\n\n") + end end # For streaming, instead of rendering a given a template, we return a Body @@ -56,48 +56,48 @@ module ActionView private - def delayed_render(buffer, template, layout, view, locals) - # Wrap the given buffer in the StreamingBuffer and pass it to the - # underlying template handler. Now, every time something is concatenated - # to the buffer, it is not appended to an array, but streamed straight - # to the client. - output = ActionView::StreamingBuffer.new(buffer) - yielder = lambda { |*name| view._layout_for(*name) } - - instrument(:template, identifier: template.identifier, layout: layout.try(:virtual_path)) do - fiber = Fiber.new do - if layout - layout.render(view, locals, output, &yielder) - else - # If you don't have a layout, just render the thing - # and concatenate the final result. This is the same - # as a layout with just <%= yield %> - output.safe_concat view._layout_for + def delayed_render(buffer, template, layout, view, locals) + # Wrap the given buffer in the StreamingBuffer and pass it to the + # underlying template handler. Now, every time something is concatenated + # to the buffer, it is not appended to an array, but streamed straight + # to the client. + output = ActionView::StreamingBuffer.new(buffer) + yielder = lambda { |*name| view._layout_for(*name) } + + instrument(:template, identifier: template.identifier, layout: layout.try(:virtual_path)) do + fiber = Fiber.new do + if layout + layout.render(view, locals, output, &yielder) + else + # If you don't have a layout, just render the thing + # and concatenate the final result. This is the same + # as a layout with just <%= yield %> + output.safe_concat view._layout_for + end end - end - # Set the view flow to support streaming. It will be aware - # when to stop rendering the layout because it needs to search - # something in the template and vice-versa. - view.view_flow = StreamingFlow.new(view, fiber) + # Set the view flow to support streaming. It will be aware + # when to stop rendering the layout because it needs to search + # something in the template and vice-versa. + view.view_flow = StreamingFlow.new(view, fiber) - # Yo! Start the fiber! - fiber.resume + # Yo! Start the fiber! + fiber.resume - # If the fiber is still alive, it means we need something - # from the template, so start rendering it. If not, it means - # the layout exited without requiring anything from the template. - if fiber.alive? - content = template.render(view, locals, &yielder) + # If the fiber is still alive, it means we need something + # from the template, so start rendering it. If not, it means + # the layout exited without requiring anything from the template. + if fiber.alive? + content = template.render(view, locals, &yielder) - # Once rendering the template is done, sets its content in the :layout key. - view.view_flow.set(:layout, content) + # Once rendering the template is done, sets its content in the :layout key. + view.view_flow.set(:layout, content) - # In case the layout continues yielding, we need to resume - # the fiber until all yields are handled. - fiber.resume while fiber.alive? + # In case the layout continues yielding, we need to resume + # the fiber until all yields are handled. + fiber.resume while fiber.alive? + end end end - end end end diff --git a/actionview/lib/action_view/renderer/template_renderer.rb b/actionview/lib/action_view/renderer/template_renderer.rb index 333413c4a1..0151653b73 100644 --- a/actionview/lib/action_view/renderer/template_renderer.rb +++ b/actionview/lib/action_view/renderer/template_renderer.rb @@ -17,86 +17,86 @@ module ActionView private # Determine the template to be rendered using the given options. - def determine_template(options) - keys = options.has_key?(:locals) ? options[:locals].keys : [] + def determine_template(options) + keys = options.has_key?(:locals) ? options[:locals].keys : [] - if options.key?(:body) - Template::Text.new(options[:body]) - elsif options.key?(:text) - Template::Text.new(options[:text], formats.first) - elsif options.key?(:plain) - Template::Text.new(options[:plain]) - elsif options.key?(:html) - Template::HTML.new(options[:html], formats.first) - elsif options.key?(:file) - with_fallbacks { find_file(options[:file], nil, false, keys, @details) } - elsif options.key?(:inline) - handler = Template.handler_for_extension(options[:type] || "erb") - Template.new(options[:inline], "inline template", handler, locals: keys) - elsif options.key?(:template) - if options[:template].respond_to?(:render) - options[:template] + if options.key?(:body) + Template::Text.new(options[:body]) + elsif options.key?(:text) + Template::Text.new(options[:text], formats.first) + elsif options.key?(:plain) + Template::Text.new(options[:plain]) + elsif options.key?(:html) + Template::HTML.new(options[:html], formats.first) + elsif options.key?(:file) + with_fallbacks { find_file(options[:file], nil, false, keys, @details) } + elsif options.key?(:inline) + handler = Template.handler_for_extension(options[:type] || "erb") + Template.new(options[:inline], "inline template", handler, locals: keys) + elsif options.key?(:template) + if options[:template].respond_to?(:render) + options[:template] + else + find_template(options[:template], options[:prefixes], false, keys, @details) + end else - find_template(options[:template], options[:prefixes], false, keys, @details) + raise ArgumentError, "You invoked render but did not give any of :partial, :template, :inline, :file, :plain, :html, :text or :body option." end - else - raise ArgumentError, "You invoked render but did not give any of :partial, :template, :inline, :file, :plain, :html, :text or :body option." end - end # Renders the given template. A string representing the layout can be # supplied as well. - def render_template(template, layout_name = nil, locals = nil) #:nodoc: - view, locals = @view, locals || {} + def render_template(template, layout_name = nil, locals = nil) #:nodoc: + view, locals = @view, locals || {} - render_with_layout(layout_name, locals) do |layout| - instrument(:template, identifier: template.identifier, layout: layout.try(:virtual_path)) do - template.render(view, locals) { |*name| view._layout_for(*name) } + render_with_layout(layout_name, locals) do |layout| + instrument(:template, identifier: template.identifier, layout: layout.try(:virtual_path)) do + template.render(view, locals) { |*name| view._layout_for(*name) } + end end end - end - def render_with_layout(path, locals) #:nodoc: - layout = path && find_layout(path, locals.keys, [formats.first]) - content = yield(layout) + def render_with_layout(path, locals) #:nodoc: + layout = path && find_layout(path, locals.keys, [formats.first]) + content = yield(layout) - if layout - view = @view - view.view_flow.set(:layout, content) - layout.render(view, locals){ |*name| view._layout_for(*name) } - else - content + if layout + view = @view + view.view_flow.set(:layout, content) + layout.render(view, locals){ |*name| view._layout_for(*name) } + else + content + end end - end # This is the method which actually finds the layout using details in the lookup # context object. If no layout is found, it checks if at least a layout with # the given name exists across all details before raising the error. - def find_layout(layout, keys, formats) - resolve_layout(layout, keys, formats) - end + def find_layout(layout, keys, formats) + resolve_layout(layout, keys, formats) + end - def resolve_layout(layout, keys, formats) - details = @details.dup - details[:formats] = formats + def resolve_layout(layout, keys, formats) + details = @details.dup + details[:formats] = formats - case layout - when String - begin - if layout.start_with?("/") - with_fallbacks { find_template(layout, nil, false, [], details) } - else - find_template(layout, nil, false, [], details) + case layout + when String + begin + if layout.start_with?("/") + with_fallbacks { find_template(layout, nil, false, [], details) } + else + find_template(layout, nil, false, [], details) + end + rescue ActionView::MissingTemplate + all_details = @details.merge(formats: @lookup_context.default_formats) + raise unless template_exists?(layout, nil, false, [], all_details) end - rescue ActionView::MissingTemplate - all_details = @details.merge(formats: @lookup_context.default_formats) - raise unless template_exists?(layout, nil, false, [], all_details) + when Proc + resolve_layout(layout.call(formats), keys, formats) + else + layout end - when Proc - resolve_layout(layout.call(formats), keys, formats) - else - layout end - end end end diff --git a/actionview/lib/action_view/template/handlers/builder.rb b/actionview/lib/action_view/template/handlers/builder.rb index d90b0c6378..e08a5b5db8 100644 --- a/actionview/lib/action_view/template/handlers/builder.rb +++ b/actionview/lib/action_view/template/handlers/builder.rb @@ -15,12 +15,12 @@ module ActionView protected - def require_engine - @required ||= begin - require "builder" - true + def require_engine + @required ||= begin + require "builder" + true + end end - end end end end diff --git a/actionview/lib/action_view/template/resolver.rb b/actionview/lib/action_view/template/resolver.rb index 6a7baf4fbc..33d60be144 100644 --- a/actionview/lib/action_view/template/resolver.rb +++ b/actionview/lib/action_view/template/resolver.rb @@ -107,22 +107,22 @@ module ActionView private - def canonical_no_templates(templates) - templates.empty? ? NO_TEMPLATES : templates - end - - def templates_have_changed?(cached_templates, fresh_templates) - # if either the old or new template list is empty, we don't need to (and can't) - # compare modification times, and instead just check whether the lists are different - if cached_templates.blank? || fresh_templates.blank? - return fresh_templates.blank? != cached_templates.blank? + def canonical_no_templates(templates) + templates.empty? ? NO_TEMPLATES : templates end - cached_templates_max_updated_at = cached_templates.map(&:updated_at).max + def templates_have_changed?(cached_templates, fresh_templates) + # if either the old or new template list is empty, we don't need to (and can't) + # compare modification times, and instead just check whether the lists are different + if cached_templates.blank? || fresh_templates.blank? + return fresh_templates.blank? != cached_templates.blank? + end - # if a template has changed, it will be now be newer than all the cached templates - fresh_templates.any? { |t| t.updated_at > cached_templates_max_updated_at } - end + cached_templates_max_updated_at = cached_templates.map(&:updated_at).max + + # if a template has changed, it will be now be newer than all the cached templates + fresh_templates.any? { |t| t.updated_at > cached_templates_max_updated_at } + end end cattr_accessor :caching @@ -214,93 +214,93 @@ module ActionView private - def find_templates(name, prefix, partial, details, outside_app_allowed = false) - path = Path.build(name, prefix, partial) - query(path, details, details[:formats], outside_app_allowed) - end + def find_templates(name, prefix, partial, details, outside_app_allowed = false) + path = Path.build(name, prefix, partial) + query(path, details, details[:formats], outside_app_allowed) + end - def query(path, details, formats, outside_app_allowed) - query = build_query(path, details) + def query(path, details, formats, outside_app_allowed) + query = build_query(path, details) - template_paths = find_template_paths(query) - template_paths = reject_files_external_to_app(template_paths) unless outside_app_allowed + template_paths = find_template_paths(query) + template_paths = reject_files_external_to_app(template_paths) unless outside_app_allowed - template_paths.map do |template| - handler, format, variant = extract_handler_and_format_and_variant(template, formats) - contents = File.binread(template) + template_paths.map do |template| + handler, format, variant = extract_handler_and_format_and_variant(template, formats) + contents = File.binread(template) - Template.new(contents, File.expand_path(template), handler, - virtual_path: path.virtual, - format: format, - variant: variant, - updated_at: mtime(template) - ) + Template.new(contents, File.expand_path(template), handler, + virtual_path: path.virtual, + format: format, + variant: variant, + updated_at: mtime(template) + ) + end end - end - def reject_files_external_to_app(files) - files.reject { |filename| !inside_path?(@path, filename) } - end + def reject_files_external_to_app(files) + files.reject { |filename| !inside_path?(@path, filename) } + end - def find_template_paths(query) - Dir[query].uniq.reject do |filename| - File.directory?(filename) || - # deals with case-insensitive file systems. - !File.fnmatch(query, filename, File::FNM_EXTGLOB) + def find_template_paths(query) + Dir[query].uniq.reject do |filename| + File.directory?(filename) || + # deals with case-insensitive file systems. + !File.fnmatch(query, filename, File::FNM_EXTGLOB) + end end - end - def inside_path?(path, filename) - filename = File.expand_path(filename) - path = File.join(path, "") - filename.start_with?(path) - end + def inside_path?(path, filename) + filename = File.expand_path(filename) + path = File.join(path, "") + filename.start_with?(path) + end # Helper for building query glob string based on resolver's pattern. - def build_query(path, details) - query = @pattern.dup + def build_query(path, details) + query = @pattern.dup - prefix = path.prefix.empty? ? "" : "#{escape_entry(path.prefix)}\\1" - query.gsub!(/:prefix(\/)?/, prefix) + prefix = path.prefix.empty? ? "" : "#{escape_entry(path.prefix)}\\1" + query.gsub!(/:prefix(\/)?/, prefix) - partial = escape_entry(path.partial? ? "_#{path.name}" : path.name) - query.gsub!(/:action/, partial) + partial = escape_entry(path.partial? ? "_#{path.name}" : path.name) + query.gsub!(/:action/, partial) - details.each do |ext, candidates| - if ext == :variants && candidates == :any - query.gsub!(/:#{ext}/, "*") - else - query.gsub!(/:#{ext}/, "{#{candidates.compact.uniq.join(',')}}") + details.each do |ext, candidates| + if ext == :variants && candidates == :any + query.gsub!(/:#{ext}/, "*") + else + query.gsub!(/:#{ext}/, "{#{candidates.compact.uniq.join(',')}}") + end end - end - File.expand_path(query, @path) - end + File.expand_path(query, @path) + end - def escape_entry(entry) - entry.gsub(/[*?{}\[\]]/, '\\\\\\&'.freeze) - end + def escape_entry(entry) + entry.gsub(/[*?{}\[\]]/, '\\\\\\&'.freeze) + end # Returns the file mtime from the filesystem. - def mtime(p) - File.mtime(p) - end + def mtime(p) + File.mtime(p) + end # Extract handler, formats and variant from path. If a format cannot be found neither # from the path, or the handler, we should return the array of formats given # to the resolver. - def extract_handler_and_format_and_variant(path, default_formats) - pieces = File.basename(path).split(".".freeze) - pieces.shift + def extract_handler_and_format_and_variant(path, default_formats) + pieces = File.basename(path).split(".".freeze) + pieces.shift - extension = pieces.pop + extension = pieces.pop - handler = Template.handler_for_extension(extension) - format, variant = pieces.last.split(EXTENSIONS[:variants], 2) if pieces.last - format &&= Template::Types[format] + handler = Template.handler_for_extension(extension) + format, variant = pieces.last.split(EXTENSIONS[:variants], 2) if pieces.last + format &&= Template::Types[format] - [handler, format, variant] - end + [handler, format, variant] + end end # A resolver that loads files from the filesystem. It allows setting your own diff --git a/actionview/lib/action_view/view_paths.rb b/actionview/lib/action_view/view_paths.rb index b07940195d..6b6cbcf06a 100644 --- a/actionview/lib/action_view/view_paths.rb +++ b/actionview/lib/action_view/view_paths.rb @@ -24,9 +24,9 @@ module ActionView # Override this method in your controller if you want to change paths prefixes for finding views. # Prefixes defined here will still be added to parents' ._prefixes. - def local_prefixes - [controller_path] - end + def local_prefixes + [controller_path] + end end # The prefixes used in render "foo" shortcuts. diff --git a/actionview/test/abstract_unit.rb b/actionview/test/abstract_unit.rb index 92989dfbe8..1d1e938557 100644 --- a/actionview/test/abstract_unit.rb +++ b/actionview/test/abstract_unit.rb @@ -164,13 +164,13 @@ class ActionDispatch::IntegrationTest < ActiveSupport::TestCase # simply return the controller#action as Rack::Body. class StubDispatcher < ::ActionDispatch::Routing::RouteSet::Dispatcher protected - def controller_reference(controller_param) - controller_param - end + def controller_reference(controller_param) + controller_param + end - def dispatch(controller, action, env) - [200, {"Content-Type" => "text/html"}, ["#{controller}##{action}"]] - end + def dispatch(controller, action, env) + [200, {"Content-Type" => "text/html"}, ["#{controller}##{action}"]] + end end def self.stub_controllers @@ -263,11 +263,11 @@ end module ActionDispatch class DebugExceptions private - remove_method :stderr_logger + remove_method :stderr_logger # Silence logger - def stderr_logger - nil - end + def stderr_logger + nil + end end end diff --git a/actionview/test/actionpack/abstract/abstract_controller_test.rb b/actionview/test/actionpack/abstract/abstract_controller_test.rb index 1480445fc5..9989b5a377 100644 --- a/actionview/test/actionpack/abstract/abstract_controller_test.rb +++ b/actionview/test/actionpack/abstract/abstract_controller_test.rb @@ -114,13 +114,13 @@ module AbstractController # * self._prefix is used when defined class PrefixedViews < RenderingController private - def self.prefix - name.underscore - end + def self.prefix + name.underscore + end - def _prefixes - [self.class.prefix] - end + def _prefixes + [self.class.prefix] + end end class Me3 < PrefixedViews @@ -189,19 +189,19 @@ module AbstractController include ActionView::Layouts private - def self.layout(formats) - find_template(name.underscore, {formats: formats}, _prefixes: ["layouts"]) - rescue ActionView::MissingTemplate - begin - find_template("application", {formats: formats}, _prefixes: ["layouts"]) + def self.layout(formats) + find_template(name.underscore, {formats: formats}, _prefixes: ["layouts"]) rescue ActionView::MissingTemplate + begin + find_template("application", {formats: formats}, _prefixes: ["layouts"]) + rescue ActionView::MissingTemplate + end end - end - def render_to_body(options = {}) - options[:_layout] = options[:layout] || _default_layout({}) - super - end + def render_to_body(options = {}) + options[:_layout] = options[:layout] || _default_layout({}) + super + end end class Me4 < WithLayouts diff --git a/actionview/test/actionpack/abstract/layouts_test.rb b/actionview/test/actionpack/abstract/layouts_test.rb index e9352dcc35..e4abac1315 100644 --- a/actionview/test/actionpack/abstract/layouts_test.rb +++ b/actionview/test/actionpack/abstract/layouts_test.rb @@ -422,16 +422,16 @@ module AbstractControllerTests test "when a grandchild has no layout specified, the child has an implied layout, and the " \ "parent has specified a layout, use the child controller layout" do - controller = WithChildOfImplied.new - controller.process(:index) - assert_equal "With Implied Hello string!", controller.response_body + controller = WithChildOfImplied.new + controller.process(:index) + assert_equal "With Implied Hello string!", controller.response_body end test "when a grandchild has nil layout specified, the child has an implied layout, and the " \ "parent has specified a layout, use the grand child controller layout" do - controller = WithGrandChildOfImplied.new - controller.process(:index) - assert_equal "With Grand Child Hello string!", controller.response_body + controller = WithGrandChildOfImplied.new + controller.process(:index) + assert_equal "With Grand Child Hello string!", controller.response_body end test "a child inherits layout from abstract controller" do diff --git a/actionview/test/activerecord/form_helper_activerecord_test.rb b/actionview/test/activerecord/form_helper_activerecord_test.rb index 8c83c536c1..6152ec4720 100644 --- a/actionview/test/activerecord/form_helper_activerecord_test.rb +++ b/actionview/test/activerecord/form_helper_activerecord_test.rb @@ -54,35 +54,35 @@ class FormHelperActiveRecordTest < ActionView::TestCase protected - def hidden_fields(method = nil) - txt = %{} + def hidden_fields(method = nil) + txt = %{} - if method && !%w(get post).include?(method.to_s) - txt << %{} + if method && !%w(get post).include?(method.to_s) + txt << %{} + end + + txt end - txt - end + def form_text(action = "/", id = nil, html_class = nil, remote = nil, multipart = nil, method = nil) + txt = %{
} + end - def form_text(action = "/", id = nil, html_class = nil, remote = nil, multipart = nil, method = nil) - txt = %{} - end + def whole_form(action = "/", id = nil, html_class = nil, options = nil) + contents = block_given? ? yield : "" - def whole_form(action = "/", id = nil, html_class = nil, options = nil) - contents = block_given? ? yield : "" + if options.is_a?(Hash) + method, remote, multipart = options.values_at(:method, :remote, :multipart) + else + method = options + end - if options.is_a?(Hash) - method, remote, multipart = options.values_at(:method, :remote, :multipart) - else - method = options + form_text(action, id, html_class, remote, multipart, method) + hidden_fields(method) + contents + "
" end - - form_text(action, id, html_class, remote, multipart, method) + hidden_fields(method) + contents + "" - end end diff --git a/actionview/test/fixtures/helpers_missing/invalid_require_helper.rb b/actionview/test/fixtures/helpers_missing/invalid_require_helper.rb index 93927f1bdb..6ac6677daa 100644 --- a/actionview/test/fixtures/helpers_missing/invalid_require_helper.rb +++ b/actionview/test/fixtures/helpers_missing/invalid_require_helper.rb @@ -2,4 +2,3 @@ require "very_invalid_file_name" module InvalidRequireHelper end - diff --git a/actionview/test/fixtures/mascot.rb b/actionview/test/fixtures/mascot.rb index f9f1448b8f..1c0bd7c8fd 100644 --- a/actionview/test/fixtures/mascot.rb +++ b/actionview/test/fixtures/mascot.rb @@ -1,3 +1,3 @@ class Mascot < ActiveRecord::Base belongs_to :company -end \ No newline at end of file +end diff --git a/actionview/test/template/atom_feed_helper_test.rb b/actionview/test/template/atom_feed_helper_test.rb index a8b95acdea..e9a923dd72 100644 --- a/actionview/test/template/atom_feed_helper_test.rb +++ b/actionview/test/template/atom_feed_helper_test.rb @@ -28,7 +28,7 @@ class ScrollsController < ActionController::Base end end EOT - FEEDS["entry_options"] = <<-EOT + FEEDS["entry_options"] = <<-EOT atom_feed do |feed| feed.title("My great blog!") feed.updated(@scrolls.first.created_at) @@ -45,7 +45,7 @@ class ScrollsController < ActionController::Base end end EOT - FEEDS["entry_type_options"] = <<-EOT + FEEDS["entry_type_options"] = <<-EOT atom_feed(:schema_date => '2008') do |feed| feed.title("My great blog!") feed.updated(@scrolls.first.created_at) @@ -62,7 +62,7 @@ class ScrollsController < ActionController::Base end end EOT - FEEDS["entry_url_false_option"] = <<-EOT + FEEDS["entry_url_false_option"] = <<-EOT atom_feed do |feed| feed.title("My great blog!") feed.updated(@scrolls.first.created_at) @@ -79,7 +79,7 @@ class ScrollsController < ActionController::Base end end EOT - FEEDS["xml_block"] = <<-EOT + FEEDS["xml_block"] = <<-EOT atom_feed do |feed| feed.title("My great blog!") feed.updated(@scrolls.first.created_at) @@ -96,7 +96,7 @@ class ScrollsController < ActionController::Base end end EOT - FEEDS["feed_with_atomPub_namespace"] = <<-EOT + FEEDS["feed_with_atomPub_namespace"] = <<-EOT atom_feed({'xmlns:app' => 'http://www.w3.org/2007/app', 'xmlns:openSearch' => 'http://a9.com/-/spec/opensearch/1.1/'}) do |feed| feed.title("My great blog!") @@ -115,7 +115,7 @@ class ScrollsController < ActionController::Base end end EOT - FEEDS["feed_with_overridden_ids"] = <<-EOT + FEEDS["feed_with_overridden_ids"] = <<-EOT atom_feed({:id => 'tag:test.rubyonrails.org,2008:test/'}) do |feed| feed.title("My great blog!") feed.updated(@scrolls.first.created_at) @@ -169,7 +169,7 @@ class ScrollsController < ActionController::Base end end EOT - FEEDS["feed_with_xhtml_content"] = <<-'EOT' + FEEDS["feed_with_xhtml_content"] = <<-'EOT' atom_feed do |feed| feed.title("My great blog!") feed.updated(@scrolls.first.created_at) @@ -191,7 +191,7 @@ class ScrollsController < ActionController::Base end end EOT - FEEDS["provide_builder"] = <<-'EOT' + FEEDS["provide_builder"] = <<-'EOT' # we pass in the new_xml to the helper so it doesn't # call anything on the original builder new_xml = Builder::XmlMarkup.new(:target=>'') diff --git a/actionview/test/template/date_helper_test.rb b/actionview/test/template/date_helper_test.rb index 0f1f22c43a..a40bc1c131 100644 --- a/actionview/test/template/date_helper_test.rb +++ b/actionview/test/template/date_helper_test.rb @@ -534,7 +534,7 @@ class DateHelperTest < ActionView::TestCase assert_dom_equal expected, select_year(nil, start_year: 2003, end_year: 2005, with_css_classes: { year: "my-year" }) end - + def test_select_year_with_position expected = %(\n" expected << " : " expected << %(\n" @@ -2524,7 +2524,7 @@ class DateHelperTest < ActionView::TestCase expected << "\n" expected << " : " expected << %(\n" diff --git a/actionview/test/template/form_helper_test.rb b/actionview/test/template/form_helper_test.rb index 716cb3a00a..ed58818602 100644 --- a/actionview/test/template/form_helper_test.rb +++ b/actionview/test/template/form_helper_test.rb @@ -805,9 +805,9 @@ class FormHelperTest < ActionView::TestCase end def test_radio_button_respects_passed_in_id - assert_dom_equal('', - radio_button("post", "secret", "1", id: "foo") - ) + assert_dom_equal('', + radio_button("post", "secret", "1", id: "foo") + ) end def test_radio_button_with_booleans @@ -1443,10 +1443,10 @@ class FormHelperTest < ActionView::TestCase %{}, check_box("post[]", "secret") ) - assert_dom_equal( - %{}, - radio_button("post[]", "title", "Hello World") - ) + assert_dom_equal( + %{}, + radio_button("post[]", "title", "Hello World") + ) assert_dom_equal( %{}, radio_button("post[]", "title", "Goodbye World") @@ -1467,10 +1467,10 @@ class FormHelperTest < ActionView::TestCase %{}, check_box("post[]", "secret", id: nil) ) - assert_dom_equal( - %{}, - radio_button("post[]", "title", "Hello World", id: nil) - ) + assert_dom_equal( + %{}, + radio_button("post[]", "title", "Hello World", id: nil) + ) assert_dom_equal( %{}, radio_button("post[]", "title", "Goodbye World", id: nil) @@ -2187,7 +2187,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do - "" + "" end assert_dom_equal expected, output_buffer @@ -2201,7 +2201,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form do - "" + "" end assert_dom_equal expected, output_buffer @@ -2215,7 +2215,7 @@ class FormHelperTest < ActionView::TestCase end expected = whole_form("/posts/123", "edit_another_post", "edit_another_post", method: "patch") do - "" + "" end assert_dom_equal expected, output_buffer @@ -2419,11 +2419,11 @@ class FormHelperTest < ActionView::TestCase } end - expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do - '' + - '' + - '' - end + expected = whole_form("/posts/123", "edit_post_123", "edit_post", method: "patch") do + '' + + '' + + '' + end assert_dom_equal expected, output_buffer end @@ -3443,48 +3443,48 @@ class FormHelperTest < ActionView::TestCase protected - def hidden_fields(options = {}) - method = options[:method] + def hidden_fields(options = {}) + method = options[:method] - if options.fetch(:enforce_utf8, true) - txt = %{} - else - txt = "" - end + if options.fetch(:enforce_utf8, true) + txt = %{} + else + txt = "" + end - if method && !%w(get post).include?(method.to_s) - txt << %{} - end + if method && !%w(get post).include?(method.to_s) + txt << %{} + end - txt - end + txt + end - def form_text(action = "/", id = nil, html_class = nil, remote = nil, multipart = nil, method = nil) - txt = %{
} - end + def form_text(action = "/", id = nil, html_class = nil, remote = nil, multipart = nil, method = nil) + txt = %{} + end - def whole_form(action = "/", id = nil, html_class = nil, options = {}) - contents = block_given? ? yield : "" + def whole_form(action = "/", id = nil, html_class = nil, options = {}) + contents = block_given? ? yield : "" - method, remote, multipart = options.values_at(:method, :remote, :multipart) + method, remote, multipart = options.values_at(:method, :remote, :multipart) - form_text(action, id, html_class, remote, multipart, method) + hidden_fields(options.slice :method, :enforce_utf8) + contents + "
" - end + form_text(action, id, html_class, remote, multipart, method) + hidden_fields(options.slice :method, :enforce_utf8) + contents + "" + end - def protect_against_forgery? - false - end + def protect_against_forgery? + false + end - def with_locale(testing_locale = :label) - old_locale, I18n.locale = I18n.locale, testing_locale - yield - ensure - I18n.locale = old_locale - end + def with_locale(testing_locale = :label) + old_locale, I18n.locale = I18n.locale, testing_locale + yield + ensure + I18n.locale = old_locale + end end diff --git a/actionview/test/template/form_options_helper_test.rb b/actionview/test/template/form_options_helper_test.rb index 69c43dacb0..f588fb2fd2 100644 --- a/actionview/test/template/form_options_helper_test.rb +++ b/actionview/test/template/form_options_helper_test.rb @@ -66,10 +66,10 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_collection_options_with_preselected_value_array - assert_dom_equal( - "\n\n", - options_from_collection_for_select(dummy_posts, "author_name", "title", [ "Babe", "Cabe" ]) - ) + assert_dom_equal( + "\n\n", + options_from_collection_for_select(dummy_posts, "author_name", "title", [ "Babe", "Cabe" ]) + ) end def test_collection_options_with_proc_for_selected @@ -171,10 +171,10 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_array_options_for_select_with_selection_array - assert_dom_equal( - "\n\n", - options_for_select([ "Denmark", "", "Sweden" ], [ "", "Sweden" ]) - ) + assert_dom_equal( + "\n\n", + options_for_select([ "Denmark", "", "Sweden" ], [ "", "Sweden" ]) + ) end def test_array_options_for_select_with_disabled_value @@ -213,18 +213,18 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_array_options_for_string_include_in_other_string_bug_fix - assert_dom_equal( - "\n", - options_for_select([ "ruby", "rubyonrails" ], "rubyonrails") - ) - assert_dom_equal( - "\n", - options_for_select([ "ruby", "rubyonrails" ], "ruby") - ) - assert_dom_equal( - %(\n\n), - options_for_select([ "ruby", "rubyonrails", nil ], "ruby") - ) + assert_dom_equal( + "\n", + options_for_select([ "ruby", "rubyonrails" ], "rubyonrails") + ) + assert_dom_equal( + "\n", + options_for_select([ "ruby", "rubyonrails" ], "ruby") + ) + assert_dom_equal( + %(\n\n), + options_for_select([ "ruby", "rubyonrails", nil ], "ruby") + ) end def test_hash_options_for_select @@ -1234,18 +1234,18 @@ class FormOptionsHelperTest < ActionView::TestCase end def test_time_zone_select_with_default_time_zone_and_nil_value - @firm = Firm.new() - @firm.time_zone = nil + @firm = Firm.new() + @firm.time_zone = nil - html = time_zone_select( "firm", "time_zone", nil, default: "B" ) - assert_dom_equal "", - html + html = time_zone_select( "firm", "time_zone", nil, default: "B" ) + assert_dom_equal "", + html end def test_time_zone_select_with_default_time_zone_and_value @@ -1386,14 +1386,14 @@ class FormOptionsHelperTest < ActionView::TestCase private - def dummy_posts - [ Post.new(" went home", "", "To a little house", "shh!"), - Post.new("Babe went home", "Babe", "To a little house", "shh!"), - Post.new("Cabe went home", "Cabe", "To a little house", "shh!") ] - end + def dummy_posts + [ Post.new(" went home", "", "To a little house", "shh!"), + Post.new("Babe went home", "Babe", "To a little house", "shh!"), + Post.new("Cabe went home", "Cabe", "To a little house", "shh!") ] + end - def dummy_continents - [ Continent.new("", [Country.new("", ""), Country.new("so", "Somalia")]), - Continent.new("Europe", [Country.new("dk", "Denmark"), Country.new("ie", "Ireland")]) ] - end + def dummy_continents + [ Continent.new("", [Country.new("", ""), Country.new("so", "Somalia")]), + Continent.new("Europe", [Country.new("dk", "Denmark"), Country.new("ie", "Ireland")]) ] + end end diff --git a/actionview/test/template/form_tag_helper_test.rb b/actionview/test/template/form_tag_helper_test.rb index 603fddc09e..52f32e9f0e 100644 --- a/actionview/test/template/form_tag_helper_test.rb +++ b/actionview/test/template/form_tag_helper_test.rb @@ -728,7 +728,7 @@ class FormTagHelperTest < ActionView::TestCase private - def root_elem(rendered_content) - Nokogiri::HTML::DocumentFragment.parse(rendered_content).children.first # extract from nodeset - end + def root_elem(rendered_content) + Nokogiri::HTML::DocumentFragment.parse(rendered_content).children.first # extract from nodeset + end end diff --git a/actionview/test/template/tag_helper_test.rb b/actionview/test/template/tag_helper_test.rb index 4e691c9490..3e060d0246 100644 --- a/actionview/test/template/tag_helper_test.rb +++ b/actionview/test/template/tag_helper_test.rb @@ -314,7 +314,7 @@ class TagHelperTest < ActionView::TestCase 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}) - assert_dom_equal div_type1, div_type2 + assert_dom_equal div_type1, div_type2 end def test_tag_builder_link_to_data_nil_equal diff --git a/activejob/lib/active_job/logging.rb b/activejob/lib/active_job/logging.rb index fd77c94d4f..9900e10181 100644 --- a/activejob/lib/active_job/logging.rb +++ b/activejob/lib/active_job/logging.rb @@ -51,70 +51,70 @@ module ActiveJob logger.formatter.current_tags.include?("ActiveJob") end - class LogSubscriber < ActiveSupport::LogSubscriber #:nodoc: - def enqueue(event) - info do - job = event.payload[:job] - "Enqueued #{job.class.name} (Job ID: #{job.job_id}) to #{queue_name(event)}" + args_info(job) + class LogSubscriber < ActiveSupport::LogSubscriber #:nodoc: + def enqueue(event) + info do + job = event.payload[:job] + "Enqueued #{job.class.name} (Job ID: #{job.job_id}) to #{queue_name(event)}" + args_info(job) + end end - end - def enqueue_at(event) - info do - job = event.payload[:job] - "Enqueued #{job.class.name} (Job ID: #{job.job_id}) to #{queue_name(event)} at #{scheduled_at(event)}" + args_info(job) + def enqueue_at(event) + info do + job = event.payload[:job] + "Enqueued #{job.class.name} (Job ID: #{job.job_id}) to #{queue_name(event)} at #{scheduled_at(event)}" + args_info(job) + end end - end - def perform_start(event) - info do - job = event.payload[:job] - "Performing #{job.class.name} from #{queue_name(event)}" + args_info(job) + def perform_start(event) + info do + job = event.payload[:job] + "Performing #{job.class.name} from #{queue_name(event)}" + args_info(job) + end end - end - def perform(event) - info do - job = event.payload[:job] - "Performed #{job.class.name} from #{queue_name(event)} in #{event.duration.round(2)}ms" + def perform(event) + info do + job = event.payload[:job] + "Performed #{job.class.name} from #{queue_name(event)} in #{event.duration.round(2)}ms" + end end - end - private - def queue_name(event) - event.payload[:adapter].class.name.demodulize.remove("Adapter") + "(#{event.payload[:job].queue_name})" - end + private + def queue_name(event) + event.payload[:adapter].class.name.demodulize.remove("Adapter") + "(#{event.payload[:job].queue_name})" + end - def args_info(job) - if job.arguments.any? - " with arguments: " + - job.arguments.map { |arg| format(arg).inspect }.join(", ") - else - "" + def args_info(job) + if job.arguments.any? + " with arguments: " + + job.arguments.map { |arg| format(arg).inspect }.join(", ") + else + "" + end end - end - def format(arg) - case arg - when Hash - arg.transform_values { |value| format(value) } - when Array - arg.map { |value| format(value) } - when GlobalID::Identification - arg.to_global_id rescue arg - else - arg + def format(arg) + case arg + when Hash + arg.transform_values { |value| format(value) } + when Array + arg.map { |value| format(value) } + when GlobalID::Identification + arg.to_global_id rescue arg + else + arg + end end - end - def scheduled_at(event) - Time.at(event.payload[:job].scheduled_at).utc - end + def scheduled_at(event) + Time.at(event.payload[:job].scheduled_at).utc + end - def logger - ActiveJob::Base.logger - end - end + def logger + ActiveJob::Base.logger + end + end end end diff --git a/activejob/lib/active_job/queue_adapter.rb b/activejob/lib/active_job/queue_adapter.rb index b651b30134..7f9a2da4b0 100644 --- a/activejob/lib/active_job/queue_adapter.rb +++ b/activejob/lib/active_job/queue_adapter.rb @@ -30,34 +30,34 @@ module ActiveJob private - def interpret_adapter(name_or_adapter_or_class) - case name_or_adapter_or_class - when Symbol, String - ActiveJob::QueueAdapters.lookup(name_or_adapter_or_class).new - else - if queue_adapter?(name_or_adapter_or_class) - name_or_adapter_or_class - elsif queue_adapter_class?(name_or_adapter_or_class) - ActiveSupport::Deprecation.warn "Passing an adapter class is deprecated " \ - "and will be removed in Rails 5.1. Please pass an adapter name " \ - "(.queue_adapter = :#{name_or_adapter_or_class.name.demodulize.remove('Adapter').underscore}) " \ - "or an instance (.queue_adapter = #{name_or_adapter_or_class.name}.new) instead." - name_or_adapter_or_class.new + def interpret_adapter(name_or_adapter_or_class) + case name_or_adapter_or_class + when Symbol, String + ActiveJob::QueueAdapters.lookup(name_or_adapter_or_class).new else - raise ArgumentError + if queue_adapter?(name_or_adapter_or_class) + name_or_adapter_or_class + elsif queue_adapter_class?(name_or_adapter_or_class) + ActiveSupport::Deprecation.warn "Passing an adapter class is deprecated " \ + "and will be removed in Rails 5.1. Please pass an adapter name " \ + "(.queue_adapter = :#{name_or_adapter_or_class.name.demodulize.remove('Adapter').underscore}) " \ + "or an instance (.queue_adapter = #{name_or_adapter_or_class.name}.new) instead." + name_or_adapter_or_class.new + else + raise ArgumentError + end end end - end - QUEUE_ADAPTER_METHODS = [:enqueue, :enqueue_at].freeze + QUEUE_ADAPTER_METHODS = [:enqueue, :enqueue_at].freeze - def queue_adapter?(object) - QUEUE_ADAPTER_METHODS.all? { |meth| object.respond_to?(meth) } - end + def queue_adapter?(object) + QUEUE_ADAPTER_METHODS.all? { |meth| object.respond_to?(meth) } + end - def queue_adapter_class?(object) - object.is_a?(Class) && QUEUE_ADAPTER_METHODS.all? { |meth| object.public_method_defined?(meth) } - end + def queue_adapter_class?(object) + object.is_a?(Class) && QUEUE_ADAPTER_METHODS.all? { |meth| object.public_method_defined?(meth) } + end end end end diff --git a/activejob/lib/active_job/queue_adapters/qu_adapter.rb b/activejob/lib/active_job/queue_adapters/qu_adapter.rb index c5521bc7ea..20cc97ebc7 100644 --- a/activejob/lib/active_job/queue_adapters/qu_adapter.rb +++ b/activejob/lib/active_job/queue_adapters/qu_adapter.rb @@ -20,7 +20,7 @@ module ActiveJob qu_job = Qu::Payload.new(klass: JobWrapper, args: [job.serialize]).tap do |payload| payload.instance_variable_set(:@queue, job.queue_name) end.push - + # qu_job can be nil depending on the configured backend job.provider_job_id = qu_job.id unless qu_job.nil? qu_job diff --git a/activejob/lib/active_job/queue_adapters/test_adapter.rb b/activejob/lib/active_job/queue_adapters/test_adapter.rb index 28a6235429..da042cfebf 100644 --- a/activejob/lib/active_job/queue_adapters/test_adapter.rb +++ b/activejob/lib/active_job/queue_adapters/test_adapter.rb @@ -39,22 +39,22 @@ module ActiveJob private - def job_to_hash(job, extras = {}) - { job: job.class, args: job.serialize.fetch("arguments"), queue: job.queue_name }.merge!(extras) - end + def job_to_hash(job, extras = {}) + { job: job.class, args: job.serialize.fetch("arguments"), queue: job.queue_name }.merge!(extras) + end - def enqueue_or_perform(perform, job, job_data) - if perform - performed_jobs << job_data - Base.execute job.serialize - else - enqueued_jobs << job_data + def enqueue_or_perform(perform, job, job_data) + if perform + performed_jobs << job_data + Base.execute job.serialize + else + enqueued_jobs << job_data + end end - end - def filtered?(job) - filter && !Array(filter).include?(job.class) - end + def filtered?(job) + filter && !Array(filter).include?(job.class) + end end end end diff --git a/activejob/lib/rails/generators/job/job_generator.rb b/activejob/lib/rails/generators/job/job_generator.rb index 6a509056c8..97c11a9ea6 100644 --- a/activejob/lib/rails/generators/job/job_generator.rb +++ b/activejob/lib/rails/generators/job/job_generator.rb @@ -27,11 +27,11 @@ module Rails # :nodoc: private def application_job_file_name - @application_job_file_name ||= if mountable_engine? - "app/jobs/#{namespaced_path}/application_job.rb" - else - "app/jobs/application_job.rb" - end + @application_job_file_name ||= if mountable_engine? + "app/jobs/#{namespaced_path}/application_job.rb" + else + "app/jobs/application_job.rb" + end end end end diff --git a/activejob/test/adapters/backburner.rb b/activejob/test/adapters/backburner.rb index 0bd4aad5d3..17ba07b802 100644 --- a/activejob/test/adapters/backburner.rb +++ b/activejob/test/adapters/backburner.rb @@ -1,3 +1,3 @@ require "support/backburner/inline" -ActiveJob::Base.queue_adapter = :backburner \ No newline at end of file +ActiveJob::Base.queue_adapter = :backburner diff --git a/activejob/test/adapters/delayed_job.rb b/activejob/test/adapters/delayed_job.rb index afd9c9deb7..5f0ee2418c 100644 --- a/activejob/test/adapters/delayed_job.rb +++ b/activejob/test/adapters/delayed_job.rb @@ -4,4 +4,3 @@ $LOAD_PATH << File.dirname(__FILE__) + "/../support/delayed_job" Delayed::Worker.delay_jobs = false Delayed::Worker.backend = :test - diff --git a/activejob/test/adapters/inline.rb b/activejob/test/adapters/inline.rb index e0092552c4..24113dfa5a 100644 --- a/activejob/test/adapters/inline.rb +++ b/activejob/test/adapters/inline.rb @@ -1 +1 @@ -ActiveJob::Base.queue_adapter = :inline \ No newline at end of file +ActiveJob::Base.queue_adapter = :inline diff --git a/activejob/test/cases/exceptions_test.rb b/activejob/test/cases/exceptions_test.rb index 004e9f4305..30e43c99cb 100644 --- a/activejob/test/cases/exceptions_test.rb +++ b/activejob/test/cases/exceptions_test.rb @@ -65,7 +65,7 @@ class ExceptionsTest < ActiveJob::TestCase test "long wait job" do travel_to Time.now - + perform_enqueued_jobs do assert_performed_with at: (Time.now + 3600.seconds).to_i do RetryJob.perform_later "LongWaitError", 5 @@ -78,13 +78,13 @@ class ExceptionsTest < ActiveJob::TestCase perform_enqueued_jobs do assert_performed_with at: (Time.now + 3.seconds).to_i do - assert_performed_with at: (Time.now + 18.seconds).to_i do - assert_performed_with at: (Time.now + 83.seconds).to_i do - assert_performed_with at: (Time.now + 258.seconds).to_i do - RetryJob.perform_later "ExponentialWaitTenAttemptsError", 5 - end - end - end + assert_performed_with at: (Time.now + 18.seconds).to_i do + assert_performed_with at: (Time.now + 83.seconds).to_i do + assert_performed_with at: (Time.now + 258.seconds).to_i do + RetryJob.perform_later "ExponentialWaitTenAttemptsError", 5 + end + end + end end end end @@ -94,13 +94,13 @@ class ExceptionsTest < ActiveJob::TestCase perform_enqueued_jobs do assert_performed_with at: (Time.now + 2.seconds).to_i do - assert_performed_with at: (Time.now + 4.seconds).to_i do - assert_performed_with at: (Time.now + 6.seconds).to_i do - assert_performed_with at: (Time.now + 8.seconds).to_i do - RetryJob.perform_later "CustomWaitTenAttemptsError", 5 - end - end - end + assert_performed_with at: (Time.now + 4.seconds).to_i do + assert_performed_with at: (Time.now + 6.seconds).to_i do + assert_performed_with at: (Time.now + 8.seconds).to_i do + RetryJob.perform_later "CustomWaitTenAttemptsError", 5 + end + end + end end end end diff --git a/activejob/test/jobs/gid_job.rb b/activejob/test/jobs/gid_job.rb index 42484dc198..c7cfa6e7a2 100644 --- a/activejob/test/jobs/gid_job.rb +++ b/activejob/test/jobs/gid_job.rb @@ -5,4 +5,3 @@ class GidJob < ActiveJob::Base JobBuffer.add("Person with ID: #{person.id}") end end - diff --git a/activejob/test/jobs/logging_job.rb b/activejob/test/jobs/logging_job.rb index d84ed8589b..119b32fa67 100644 --- a/activejob/test/jobs/logging_job.rb +++ b/activejob/test/jobs/logging_job.rb @@ -7,4 +7,3 @@ class LoggingJob < ActiveJob::Base "LOGGING-JOB-ID" end end - diff --git a/activejob/test/jobs/nested_job.rb b/activejob/test/jobs/nested_job.rb index 8c4ec549a6..21b7692cd1 100644 --- a/activejob/test/jobs/nested_job.rb +++ b/activejob/test/jobs/nested_job.rb @@ -7,4 +7,3 @@ class NestedJob < ActiveJob::Base "NESTED-JOB-ID" end end - diff --git a/activejob/test/support/backburner/inline.rb b/activejob/test/support/backburner/inline.rb index 7b7954e8f7..647dbf317f 100644 --- a/activejob/test/support/backburner/inline.rb +++ b/activejob/test/support/backburner/inline.rb @@ -5,4 +5,4 @@ Backburner::Worker.class_eval do def self.enqueue(job_class, args=[], opts={}) job_class.perform(*args) end -end \ No newline at end of file +end diff --git a/activejob/test/support/integration/adapters/backburner.rb b/activejob/test/support/integration/adapters/backburner.rb index 2e82562948..263097c792 100644 --- a/activejob/test/support/integration/adapters/backburner.rb +++ b/activejob/test/support/integration/adapters/backburner.rb @@ -35,4 +35,3 @@ module BackburnerJobsManager true end end - diff --git a/activejob/test/support/integration/adapters/inline.rb b/activejob/test/support/integration/adapters/inline.rb index 83c38f706f..e06b34c976 100644 --- a/activejob/test/support/integration/adapters/inline.rb +++ b/activejob/test/support/integration/adapters/inline.rb @@ -12,4 +12,3 @@ module InlineJobsManager def stop_workers end end - diff --git a/activemodel/lib/active_model/attribute_assignment.rb b/activemodel/lib/active_model/attribute_assignment.rb index 541076486d..7dad3b6dff 100644 --- a/activemodel/lib/active_model/attribute_assignment.rb +++ b/activemodel/lib/active_model/attribute_assignment.rb @@ -35,18 +35,18 @@ module ActiveModel private - def _assign_attributes(attributes) - attributes.each do |k, v| - _assign_attribute(k, v) + def _assign_attributes(attributes) + attributes.each do |k, v| + _assign_attribute(k, v) + end end - end - def _assign_attribute(k, v) - if respond_to?("#{k}=") - public_send("#{k}=", v) - else - raise UnknownAttributeError.new(self, k) + def _assign_attribute(k, v) + if respond_to?("#{k}=") + public_send("#{k}=", v) + else + raise UnknownAttributeError.new(self, k) + end end - end end end diff --git a/activemodel/lib/active_model/callbacks.rb b/activemodel/lib/active_model/callbacks.rb index 8a87025536..283090e380 100644 --- a/activemodel/lib/active_model/callbacks.rb +++ b/activemodel/lib/active_model/callbacks.rb @@ -122,28 +122,28 @@ module ActiveModel private - def _define_before_model_callback(klass, callback) #:nodoc: - klass.define_singleton_method("before_#{callback}") do |*args, &block| - set_callback(:"#{callback}", :before, *args, &block) + def _define_before_model_callback(klass, callback) #:nodoc: + klass.define_singleton_method("before_#{callback}") do |*args, &block| + set_callback(:"#{callback}", :before, *args, &block) + end end - end - def _define_around_model_callback(klass, callback) #:nodoc: - klass.define_singleton_method("around_#{callback}") do |*args, &block| - set_callback(:"#{callback}", :around, *args, &block) + def _define_around_model_callback(klass, callback) #:nodoc: + klass.define_singleton_method("around_#{callback}") do |*args, &block| + set_callback(:"#{callback}", :around, *args, &block) + end end - end - def _define_after_model_callback(klass, callback) #:nodoc: - klass.define_singleton_method("after_#{callback}") do |*args, &block| - options = args.extract_options! - options[:prepend] = true - conditional = ActiveSupport::Callbacks::Conditionals::Value.new { |v| - v != false - } - options[:if] = Array(options[:if]) << conditional - set_callback(:"#{callback}", :after, *(args << options), &block) + def _define_after_model_callback(klass, callback) #:nodoc: + klass.define_singleton_method("after_#{callback}") do |*args, &block| + options = args.extract_options! + options[:prepend] = true + conditional = ActiveSupport::Callbacks::Conditionals::Value.new { |v| + v != false + } + options[:if] = Array(options[:if]) << conditional + set_callback(:"#{callback}", :after, *(args << options), &block) + end end - end end end diff --git a/activemodel/lib/active_model/naming.rb b/activemodel/lib/active_model/naming.rb index a9c62fc3a5..3830d1486d 100644 --- a/activemodel/lib/active_model/naming.rb +++ b/activemodel/lib/active_model/naming.rb @@ -191,9 +191,9 @@ module ActiveModel private - def _singularize(string) - ActiveSupport::Inflector.underscore(string).tr("/".freeze, "_".freeze) - end + def _singularize(string) + ActiveSupport::Inflector.underscore(string).tr("/".freeze, "_".freeze) + end end # == Active \Model \Naming diff --git a/activemodel/lib/active_model/type/big_integer.rb b/activemodel/lib/active_model/type/big_integer.rb index 6829736cff..3b629682fe 100644 --- a/activemodel/lib/active_model/type/big_integer.rb +++ b/activemodel/lib/active_model/type/big_integer.rb @@ -5,9 +5,9 @@ module ActiveModel class BigInteger < Integer # :nodoc: private - def max_value - ::Float::INFINITY - end + def max_value + ::Float::INFINITY + end end end end diff --git a/activemodel/lib/active_model/type/boolean.rb b/activemodel/lib/active_model/type/boolean.rb index 618423ba8a..f2a47370a3 100644 --- a/activemodel/lib/active_model/type/boolean.rb +++ b/activemodel/lib/active_model/type/boolean.rb @@ -20,13 +20,13 @@ module ActiveModel private - def cast_value(value) - if value == "" - nil - else - !FALSE_VALUES.include?(value) + def cast_value(value) + if value == "" + nil + else + !FALSE_VALUES.include?(value) + end end - end end end end diff --git a/activemodel/lib/active_model/type/date.rb b/activemodel/lib/active_model/type/date.rb index edd07ac38c..6e313fbca8 100644 --- a/activemodel/lib/active_model/type/date.rb +++ b/activemodel/lib/active_model/type/date.rb @@ -17,38 +17,38 @@ module ActiveModel private - def cast_value(value) - if value.is_a?(::String) - return if value.empty? - fast_string_to_date(value) || fallback_string_to_date(value) - elsif value.respond_to?(:to_date) - value.to_date - else - value + def cast_value(value) + if value.is_a?(::String) + return if value.empty? + fast_string_to_date(value) || fallback_string_to_date(value) + elsif value.respond_to?(:to_date) + value.to_date + else + value + end end - end - ISO_DATE = /\A(\d{4})-(\d\d)-(\d\d)\z/ - def fast_string_to_date(string) - if string =~ ISO_DATE - new_date $1.to_i, $2.to_i, $3.to_i + ISO_DATE = /\A(\d{4})-(\d\d)-(\d\d)\z/ + def fast_string_to_date(string) + if string =~ ISO_DATE + new_date $1.to_i, $2.to_i, $3.to_i + end end - end - def fallback_string_to_date(string) - new_date(*::Date._parse(string, false).values_at(:year, :mon, :mday)) - end + def fallback_string_to_date(string) + new_date(*::Date._parse(string, false).values_at(:year, :mon, :mday)) + end - def new_date(year, mon, mday) - if year && year != 0 - ::Date.new(year, mon, mday) rescue nil + def new_date(year, mon, mday) + if year && year != 0 + ::Date.new(year, mon, mday) rescue nil + end end - end - def value_from_multiparameter_assignment(*) - time = super - time && time.to_date - end + def value_from_multiparameter_assignment(*) + time = super + time && time.to_date + end end end end diff --git a/activemodel/lib/active_model/type/date_time.rb b/activemodel/lib/active_model/type/date_time.rb index 2f2df4320f..f88c9e5071 100644 --- a/activemodel/lib/active_model/type/date_time.rb +++ b/activemodel/lib/active_model/type/date_time.rb @@ -12,33 +12,33 @@ module ActiveModel private - def cast_value(value) - return apply_seconds_precision(value) unless value.is_a?(::String) - return if value.empty? + def cast_value(value) + return apply_seconds_precision(value) unless value.is_a?(::String) + return if value.empty? - fast_string_to_time(value) || fallback_string_to_time(value) - end + fast_string_to_time(value) || fallback_string_to_time(value) + end # '0.123456' -> 123456 # '1.123456' -> 123456 - def microseconds(time) - time[:sec_fraction] ? (time[:sec_fraction] * 1_000_000).to_i : 0 - end + def microseconds(time) + time[:sec_fraction] ? (time[:sec_fraction] * 1_000_000).to_i : 0 + end - def fallback_string_to_time(string) - time_hash = ::Date._parse(string) - time_hash[:sec_fraction] = microseconds(time_hash) + def fallback_string_to_time(string) + time_hash = ::Date._parse(string) + time_hash[:sec_fraction] = microseconds(time_hash) - new_time(*time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction, :offset)) - end + new_time(*time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction, :offset)) + end - def value_from_multiparameter_assignment(values_hash) - missing_parameter = (1..3).detect { |key| !values_hash.key?(key) } - if missing_parameter - raise ArgumentError, missing_parameter + def value_from_multiparameter_assignment(values_hash) + missing_parameter = (1..3).detect { |key| !values_hash.key?(key) } + if missing_parameter + raise ArgumentError, missing_parameter + end + super end - super - end end end end diff --git a/activemodel/lib/active_model/type/decimal.rb b/activemodel/lib/active_model/type/decimal.rb index 11ea327026..273798593b 100644 --- a/activemodel/lib/active_model/type/decimal.rb +++ b/activemodel/lib/active_model/type/decimal.rb @@ -15,46 +15,46 @@ module ActiveModel private - def cast_value(value) - casted_value = case value - when ::Float - convert_float_to_big_decimal(value) - when ::Numeric, ::String - BigDecimal(value, precision.to_i) - else - if value.respond_to?(:to_d) - value.to_d + def cast_value(value) + casted_value = case value + when ::Float + convert_float_to_big_decimal(value) + when ::Numeric, ::String + BigDecimal(value, precision.to_i) else - cast_value(value.to_s) + if value.respond_to?(:to_d) + value.to_d + else + cast_value(value.to_s) + end end - end - apply_scale(casted_value) - end + apply_scale(casted_value) + end - def convert_float_to_big_decimal(value) - if precision - BigDecimal(apply_scale(value), float_precision) - else - value.to_d + def convert_float_to_big_decimal(value) + if precision + BigDecimal(apply_scale(value), float_precision) + else + value.to_d + end end - end - def float_precision - if precision.to_i > ::Float::DIG + 1 - ::Float::DIG + 1 - else - precision.to_i + def float_precision + if precision.to_i > ::Float::DIG + 1 + ::Float::DIG + 1 + else + precision.to_i + end end - end - def apply_scale(value) - if scale - value.round(scale) - else - value + def apply_scale(value) + if scale + value.round(scale) + else + value + end end - end end end end diff --git a/activemodel/lib/active_model/type/float.rb b/activemodel/lib/active_model/type/float.rb index 0f925bc7e1..94bb7e700c 100644 --- a/activemodel/lib/active_model/type/float.rb +++ b/activemodel/lib/active_model/type/float.rb @@ -11,15 +11,15 @@ module ActiveModel private - def cast_value(value) - case value - when ::Float then value - when "Infinity" then ::Float::INFINITY - when "-Infinity" then -::Float::INFINITY - when "NaN" then ::Float::NAN - else value.to_f + def cast_value(value) + case value + when ::Float then value + when "Infinity" then ::Float::INFINITY + when "-Infinity" then -::Float::INFINITY + when "NaN" then ::Float::NAN + else value.to_f + end end - end end end end diff --git a/activemodel/lib/active_model/type/helpers/numeric.rb b/activemodel/lib/active_model/type/helpers/numeric.rb index c883010506..ec1d1daf1a 100644 --- a/activemodel/lib/active_model/type/helpers/numeric.rb +++ b/activemodel/lib/active_model/type/helpers/numeric.rb @@ -18,16 +18,16 @@ module ActiveModel private - def number_to_non_number?(old_value, new_value_before_type_cast) - old_value != nil && non_numeric_string?(new_value_before_type_cast) - end + def number_to_non_number?(old_value, new_value_before_type_cast) + old_value != nil && non_numeric_string?(new_value_before_type_cast) + end - def non_numeric_string?(value) - # 'wibble'.to_i will give zero, we want to make sure - # that we aren't marking int zero to string zero as - # changed. - value.to_s !~ /\A-?\d+\.?\d*\z/ - end + def non_numeric_string?(value) + # 'wibble'.to_i will give zero, we want to make sure + # that we aren't marking int zero to string zero as + # changed. + value.to_s !~ /\A-?\d+\.?\d*\z/ + end end end end diff --git a/activemodel/lib/active_model/type/helpers/time_value.rb b/activemodel/lib/active_model/type/helpers/time_value.rb index e4947fc75d..64780ebbdc 100644 --- a/activemodel/lib/active_model/type/helpers/time_value.rb +++ b/activemodel/lib/active_model/type/helpers/time_value.rb @@ -47,30 +47,30 @@ module ActiveModel private - def new_time(year, mon, mday, hour, min, sec, microsec, offset = nil) - # Treat 0000-00-00 00:00:00 as nil. - return if year.nil? || (year == 0 && mon == 0 && mday == 0) + def new_time(year, mon, mday, hour, min, sec, microsec, offset = nil) + # Treat 0000-00-00 00:00:00 as nil. + return if year.nil? || (year == 0 && mon == 0 && mday == 0) - if offset - time = ::Time.utc(year, mon, mday, hour, min, sec, microsec) rescue nil - return unless time + if offset + time = ::Time.utc(year, mon, mday, hour, min, sec, microsec) rescue nil + return unless time - time -= offset - is_utc? ? time : time.getlocal - else - ::Time.public_send(default_timezone, year, mon, mday, hour, min, sec, microsec) rescue nil + time -= offset + is_utc? ? time : time.getlocal + else + ::Time.public_send(default_timezone, year, mon, mday, hour, min, sec, microsec) rescue nil + end end - end - ISO_DATETIME = /\A(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)(\.\d+)?\z/ + ISO_DATETIME = /\A(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)(\.\d+)?\z/ # Doesn't handle time zones. - def fast_string_to_time(string) - if string =~ ISO_DATETIME - microsec = ($7.to_r * 1_000_000).to_i - new_time $1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i, microsec + def fast_string_to_time(string) + if string =~ ISO_DATETIME + microsec = ($7.to_r * 1_000_000).to_i + new_time $1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i, microsec + end end - end end end end diff --git a/activemodel/lib/active_model/type/immutable_string.rb b/activemodel/lib/active_model/type/immutable_string.rb index 20b8ca0cc4..41e4a2a1ac 100644 --- a/activemodel/lib/active_model/type/immutable_string.rb +++ b/activemodel/lib/active_model/type/immutable_string.rb @@ -16,14 +16,14 @@ module ActiveModel private - def cast_value(value) - result = case value - when true then "t" - when false then "f" - else value.to_s - end - result.freeze - end + def cast_value(value) + result = case value + when true then "t" + when false then "f" + else value.to_s + end + result.freeze + end end end end diff --git a/activemodel/lib/active_model/type/integer.rb b/activemodel/lib/active_model/type/integer.rb index eea2280b22..b76e9d96f6 100644 --- a/activemodel/lib/active_model/type/integer.rb +++ b/activemodel/lib/active_model/type/integer.rb @@ -31,36 +31,36 @@ module ActiveModel protected - attr_reader :range + attr_reader :range private - def cast_value(value) - case value - when true then 1 - when false then 0 - else - value.to_i rescue nil + def cast_value(value) + case value + when true then 1 + when false then 0 + else + value.to_i rescue nil + end end - end - def ensure_in_range(value) - unless range.cover?(value) - raise ActiveModel::RangeError, "#{value} is out of range for #{self.class} with limit #{_limit}" + def ensure_in_range(value) + unless range.cover?(value) + raise ActiveModel::RangeError, "#{value} is out of range for #{self.class} with limit #{_limit}" + end end - end - def max_value - 1 << (_limit * 8 - 1) # 8 bits per byte with one bit for sign - end + def max_value + 1 << (_limit * 8 - 1) # 8 bits per byte with one bit for sign + end - def min_value - -max_value - end + def min_value + -max_value + end - def _limit - self.limit || DEFAULT_LIMIT - end + def _limit + self.limit || DEFAULT_LIMIT + end end end end diff --git a/activemodel/lib/active_model/type/registry.rb b/activemodel/lib/active_model/type/registry.rb index adc88eb624..d25f1a129e 100644 --- a/activemodel/lib/active_model/type/registry.rb +++ b/activemodel/lib/active_model/type/registry.rb @@ -23,17 +23,17 @@ module ActiveModel protected - attr_reader :registrations + attr_reader :registrations private - def registration_klass - Registration - end + def registration_klass + Registration + end - def find_registration(symbol, *args) - registrations.find { |r| r.matches?(symbol, *args) } - end + def find_registration(symbol, *args) + registrations.find { |r| r.matches?(symbol, *args) } + end end class Registration @@ -57,7 +57,7 @@ module ActiveModel protected - attr_reader :name, :block + attr_reader :name, :block end end # :startdoc: diff --git a/activemodel/lib/active_model/type/string.rb b/activemodel/lib/active_model/type/string.rb index 8a91410998..c7e0208a5a 100644 --- a/activemodel/lib/active_model/type/string.rb +++ b/activemodel/lib/active_model/type/string.rb @@ -11,9 +11,9 @@ module ActiveModel private - def cast_value(value) - ::String.new(super) - end + def cast_value(value) + ::String.new(super) + end end end end diff --git a/activemodel/lib/active_model/type/time.rb b/activemodel/lib/active_model/type/time.rb index 5a7851ba29..54d6214e81 100644 --- a/activemodel/lib/active_model/type/time.rb +++ b/activemodel/lib/active_model/type/time.rb @@ -25,22 +25,22 @@ module ActiveModel private - def cast_value(value) - return value unless value.is_a?(::String) - return if value.empty? - - if value.start_with?("2000-01-01") - dummy_time_value = value - else - dummy_time_value = "2000-01-01 #{value}" + def cast_value(value) + return value unless value.is_a?(::String) + return if value.empty? + + if value.start_with?("2000-01-01") + dummy_time_value = value + else + dummy_time_value = "2000-01-01 #{value}" + end + + fast_string_to_time(dummy_time_value) || begin + time_hash = ::Date._parse(dummy_time_value) + return if time_hash[:hour].nil? + new_time(*time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction, :offset)) + end end - - fast_string_to_time(dummy_time_value) || begin - time_hash = ::Date._parse(dummy_time_value) - return if time_hash[:hour].nil? - new_time(*time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction, :offset)) - end - end end end end diff --git a/activemodel/lib/active_model/type/unsigned_integer.rb b/activemodel/lib/active_model/type/unsigned_integer.rb index 3f49f9f5f7..288fa23efe 100644 --- a/activemodel/lib/active_model/type/unsigned_integer.rb +++ b/activemodel/lib/active_model/type/unsigned_integer.rb @@ -3,13 +3,13 @@ module ActiveModel class UnsignedInteger < Integer # :nodoc: private - def max_value - super * 2 - end + def max_value + super * 2 + end - def min_value - 0 - end + def min_value + 0 + end end end end diff --git a/activemodel/lib/active_model/type/value.rb b/activemodel/lib/active_model/type/value.rb index 0d2d6873a8..4d3a1b29d6 100644 --- a/activemodel/lib/active_model/type/value.rb +++ b/activemodel/lib/active_model/type/value.rb @@ -108,9 +108,9 @@ module ActiveModel # Convenience method for types which do not need separate type casting # behavior for user and database inputs. Called by Value#cast for # values except +nil+. - def cast_value(value) # :doc: - value - end + def cast_value(value) # :doc: + value + end end end end diff --git a/activemodel/lib/active_model/validations/acceptance.rb b/activemodel/lib/active_model/validations/acceptance.rb index 998b05f565..8484413950 100644 --- a/activemodel/lib/active_model/validations/acceptance.rb +++ b/activemodel/lib/active_model/validations/acceptance.rb @@ -15,58 +15,58 @@ module ActiveModel private - def setup!(klass) - klass.include(LazilyDefineAttributes.new(AttributeDefinition.new(attributes))) - end + def setup!(klass) + klass.include(LazilyDefineAttributes.new(AttributeDefinition.new(attributes))) + end - def acceptable_option?(value) - Array(options[:accept]).include?(value) - end + def acceptable_option?(value) + Array(options[:accept]).include?(value) + end - class LazilyDefineAttributes < Module - def initialize(attribute_definition) - define_method(:respond_to_missing?) do |method_name, include_private=false| - super(method_name, include_private) || attribute_definition.matches?(method_name) - end + class LazilyDefineAttributes < Module + def initialize(attribute_definition) + define_method(:respond_to_missing?) do |method_name, include_private=false| + super(method_name, include_private) || attribute_definition.matches?(method_name) + end - define_method(:method_missing) do |method_name, *args, &block| - if attribute_definition.matches?(method_name) - attribute_definition.define_on(self.class) - send(method_name, *args, &block) - else - super(method_name, *args, &block) + define_method(:method_missing) do |method_name, *args, &block| + if attribute_definition.matches?(method_name) + attribute_definition.define_on(self.class) + send(method_name, *args, &block) + else + super(method_name, *args, &block) + end end end end - end - class AttributeDefinition - def initialize(attributes) - @attributes = attributes.map(&:to_s) - end + class AttributeDefinition + def initialize(attributes) + @attributes = attributes.map(&:to_s) + end - def matches?(method_name) - attr_name = convert_to_reader_name(method_name) - attributes.include?(attr_name) - end + def matches?(method_name) + attr_name = convert_to_reader_name(method_name) + attributes.include?(attr_name) + end - def define_on(klass) - attr_readers = attributes.reject { |name| klass.attribute_method?(name) } - attr_writers = attributes.reject { |name| klass.attribute_method?("#{name}=") } - klass.send(:attr_reader, *attr_readers) - klass.send(:attr_writer, *attr_writers) - end + def define_on(klass) + attr_readers = attributes.reject { |name| klass.attribute_method?(name) } + attr_writers = attributes.reject { |name| klass.attribute_method?("#{name}=") } + klass.send(:attr_reader, *attr_readers) + klass.send(:attr_writer, *attr_writers) + end - protected + protected - attr_reader :attributes + attr_reader :attributes - private + private - def convert_to_reader_name(method_name) - method_name.to_s.chomp("=") + def convert_to_reader_name(method_name) + method_name.to_s.chomp("=") + end end - end end module HelperMethods diff --git a/activemodel/lib/active_model/validations/clusivity.rb b/activemodel/lib/active_model/validations/clusivity.rb index 868c519229..a869dba672 100644 --- a/activemodel/lib/active_model/validations/clusivity.rb +++ b/activemodel/lib/active_model/validations/clusivity.rb @@ -16,7 +16,7 @@ module ActiveModel def include?(record, value) members = if delimiter.respond_to?(:call) - delimiter.call(record) + delimiter.call(record) elsif delimiter.respond_to?(:to_sym) record.send(delimiter) else diff --git a/activemodel/lib/active_model/validations/confirmation.rb b/activemodel/lib/active_model/validations/confirmation.rb index 8f8ade90bb..dcd0317f64 100644 --- a/activemodel/lib/active_model/validations/confirmation.rb +++ b/activemodel/lib/active_model/validations/confirmation.rb @@ -17,23 +17,23 @@ module ActiveModel end private - def setup!(klass) - klass.send(:attr_reader, *attributes.map do |attribute| - :"#{attribute}_confirmation" unless klass.method_defined?(:"#{attribute}_confirmation") - end.compact) + def setup!(klass) + klass.send(:attr_reader, *attributes.map do |attribute| + :"#{attribute}_confirmation" unless klass.method_defined?(:"#{attribute}_confirmation") + end.compact) - klass.send(:attr_writer, *attributes.map do |attribute| - :"#{attribute}_confirmation" unless klass.method_defined?(:"#{attribute}_confirmation=") - end.compact) - end + klass.send(:attr_writer, *attributes.map do |attribute| + :"#{attribute}_confirmation" unless klass.method_defined?(:"#{attribute}_confirmation=") + end.compact) + end - def confirmation_value_equal?(record, attribute, value, confirmed) - if !options[:case_sensitive] && value.is_a?(String) - value.casecmp(confirmed) == 0 - else - value == confirmed + def confirmation_value_equal?(record, attribute, value, confirmed) + if !options[:case_sensitive] && value.is_a?(String) + value.casecmp(confirmed) == 0 + else + value == confirmed + end end - end end module HelperMethods diff --git a/activemodel/lib/active_model/validations/format.rb b/activemodel/lib/active_model/validations/format.rb index 910d6c2d17..e4ea42f8f4 100644 --- a/activemodel/lib/active_model/validations/format.rb +++ b/activemodel/lib/active_model/validations/format.rb @@ -24,33 +24,33 @@ module ActiveModel private - def option_call(record, name) - option = options[name] - option.respond_to?(:call) ? option.call(record) : option - end + def option_call(record, name) + option = options[name] + option.respond_to?(:call) ? option.call(record) : option + end - def record_error(record, attribute, name, value) - record.errors.add(attribute, :invalid, options.except(name).merge!(value: value)) - end + def record_error(record, attribute, name, value) + record.errors.add(attribute, :invalid, options.except(name).merge!(value: value)) + end - def check_options_validity(name) - if option = options[name] - if option.is_a?(Regexp) - if options[:multiline] != true && regexp_using_multiline_anchors?(option) - raise ArgumentError, "The provided regular expression is using multiline anchors (^ or $), " \ - "which may present a security risk. Did you mean to use \\A and \\z, or forgot to add the " \ - ":multiline => true option?" + def check_options_validity(name) + if option = options[name] + if option.is_a?(Regexp) + if options[:multiline] != true && regexp_using_multiline_anchors?(option) + raise ArgumentError, "The provided regular expression is using multiline anchors (^ or $), " \ + "which may present a security risk. Did you mean to use \\A and \\z, or forgot to add the " \ + ":multiline => true option?" + end + elsif !option.respond_to?(:call) + raise ArgumentError, "A regular expression or a proc or lambda must be supplied as :#{name}" end - elsif !option.respond_to?(:call) - raise ArgumentError, "A regular expression or a proc or lambda must be supplied as :#{name}" end end - end - def regexp_using_multiline_anchors?(regexp) - source = regexp.source - source.start_with?("^") || (source.end_with?("$") && !source.end_with?("\\$")) - end + def regexp_using_multiline_anchors?(regexp) + source = regexp.source + source.start_with?("^") || (source.end_with?("$") && !source.end_with?("\\$")) + end end module HelperMethods diff --git a/activemodel/lib/active_model/validations/length.rb b/activemodel/lib/active_model/validations/length.rb index 257ea2e979..25a51c89cf 100644 --- a/activemodel/lib/active_model/validations/length.rb +++ b/activemodel/lib/active_model/validations/length.rb @@ -80,20 +80,20 @@ module ActiveModel end private - def tokenize(record, value) - tokenizer = options[:tokenizer] - if tokenizer && value.kind_of?(String) - if tokenizer.kind_of?(Proc) - tokenizer.call(value) - elsif record.respond_to?(tokenizer) - record.send(tokenizer, value) - end - end || value - end + def tokenize(record, value) + tokenizer = options[:tokenizer] + if tokenizer && value.kind_of?(String) + if tokenizer.kind_of?(Proc) + tokenizer.call(value) + elsif record.respond_to?(tokenizer) + record.send(tokenizer, value) + end + end || value + end - def skip_nil_check?(key) - key == :maximum && options[:allow_nil].nil? && options[:allow_blank].nil? - end + def skip_nil_check?(key) + key == :maximum && options[:allow_nil].nil? && options[:allow_blank].nil? + end end module HelperMethods diff --git a/activemodel/lib/active_model/validations/numericality.rb b/activemodel/lib/active_model/validations/numericality.rb index 9a0a0655de..21e6603ba4 100644 --- a/activemodel/lib/active_model/validations/numericality.rb +++ b/activemodel/lib/active_model/validations/numericality.rb @@ -99,10 +99,10 @@ module ActiveModel private - def record_attribute_changed_in_place?(record, attr_name) - record.respond_to?(:attribute_changed_in_place?) && - record.attribute_changed_in_place?(attr_name.to_s) - end + def record_attribute_changed_in_place?(record, attr_name) + record.respond_to?(:attribute_changed_in_place?) && + record.attribute_changed_in_place?(attr_name.to_s) + end end module HelperMethods diff --git a/activemodel/lib/active_model/validator.rb b/activemodel/lib/active_model/validator.rb index 4ea369e005..9ee38c1239 100644 --- a/activemodel/lib/active_model/validator.rb +++ b/activemodel/lib/active_model/validator.rb @@ -175,8 +175,8 @@ module ActiveModel private - def validate_each(record, attribute, value) - @block.call(record, attribute, value) - end + def validate_each(record, attribute, value) + @block.call(record, attribute, value) + end end end diff --git a/activemodel/test/cases/attribute_assignment_test.rb b/activemodel/test/cases/attribute_assignment_test.rb index 287bea719c..8eb389d331 100644 --- a/activemodel/test/cases/attribute_assignment_test.rb +++ b/activemodel/test/cases/attribute_assignment_test.rb @@ -18,7 +18,7 @@ class AttributeAssignmentTest < ActiveModel::TestCase protected - attr_writer :metadata + attr_writer :metadata end class ErrorFromAttributeWriter < StandardError diff --git a/activemodel/test/cases/attribute_methods_test.rb b/activemodel/test/cases/attribute_methods_test.rb index 676459cc8e..f59180cceb 100644 --- a/activemodel/test/cases/attribute_methods_test.rb +++ b/activemodel/test/cases/attribute_methods_test.rb @@ -245,8 +245,8 @@ class AttributeMethodsTest < ActiveModel::TestCase class ClassWithProtected protected - def protected_method - end + def protected_method + end end test "should not interfere with respond_to? if the attribute has a private/protected method" do diff --git a/activemodel/test/cases/forbidden_attributes_protection_test.rb b/activemodel/test/cases/forbidden_attributes_protection_test.rb index fdd349a0fb..d8cc72e662 100644 --- a/activemodel/test/cases/forbidden_attributes_protection_test.rb +++ b/activemodel/test/cases/forbidden_attributes_protection_test.rb @@ -37,6 +37,6 @@ class ActiveModelMassUpdateProtectionTest < ActiveSupport::TestCase end test "regular attributes should still be allowed" do - assert_equal({ a: "b" }, Account.new.sanitize_for_mass_assignment(a: "b")) + assert_equal({ a: "b" }, Account.new.sanitize_for_mass_assignment(a: "b")) end end diff --git a/activemodel/test/cases/translation_test.rb b/activemodel/test/cases/translation_test.rb index 69a3acd957..37d68de014 100644 --- a/activemodel/test/cases/translation_test.rb +++ b/activemodel/test/cases/translation_test.rb @@ -110,4 +110,3 @@ class ActiveModelI18nTests < ActiveModel::TestCase assert_equal({ default: "Cool gender" }, options) end end - diff --git a/activemodel/test/cases/types_test.rb b/activemodel/test/cases/types_test.rb index 900afe836a..c46775cb41 100644 --- a/activemodel/test/cases/types_test.rb +++ b/activemodel/test/cases/types_test.rb @@ -114,12 +114,12 @@ module ActiveModel private - def with_timezone_config(default:) - old_zone_default = ::Time.zone_default - ::Time.zone_default = ::Time.find_zone(default) - yield - ensure - ::Time.zone_default = old_zone_default - end + def with_timezone_config(default:) + old_zone_default = ::Time.zone_default + ::Time.zone_default = ::Time.find_zone(default) + yield + ensure + ::Time.zone_default = old_zone_default + end end end diff --git a/activemodel/test/cases/validations/numericality_validation_test.rb b/activemodel/test/cases/validations/numericality_validation_test.rb index 742a9fc679..56127f9286 100644 --- a/activemodel/test/cases/validations/numericality_validation_test.rb +++ b/activemodel/test/cases/validations/numericality_validation_test.rb @@ -94,7 +94,7 @@ class NumericalityValidationTest < ActiveModel::TestCase end def test_validates_numericality_with_greater_than_or_equal_using_differing_numeric_types - Topic.validates_numericality_of :approved, greater_than_or_equal_to: BigDecimal.new("97.18") + Topic.validates_numericality_of :approved, greater_than_or_equal_to: BigDecimal.new("97.18") invalid!([-97.18, 97.17, 97, BigDecimal.new("97.17"), BigDecimal.new("-97.18")], "must be greater than or equal to 97.18") valid!([97.18, 98, BigDecimal.new("97.19")]) @@ -264,25 +264,25 @@ class NumericalityValidationTest < ActiveModel::TestCase private - def invalid!(values, error = nil) - with_each_topic_approved_value(values) do |topic, value| - assert topic.invalid?, "#{value.inspect} not rejected as a number" - assert topic.errors[:approved].any?, "FAILED for #{value.inspect}" - assert_equal error, topic.errors[:approved].first if error + def invalid!(values, error = nil) + with_each_topic_approved_value(values) do |topic, value| + assert topic.invalid?, "#{value.inspect} not rejected as a number" + assert topic.errors[:approved].any?, "FAILED for #{value.inspect}" + assert_equal error, topic.errors[:approved].first if error + end end - end - def valid!(values) - with_each_topic_approved_value(values) do |topic, value| - assert topic.valid?, "#{value.inspect} not accepted as a number with validation error: #{topic.errors[:approved].first}" + def valid!(values) + with_each_topic_approved_value(values) do |topic, value| + assert topic.valid?, "#{value.inspect} not accepted as a number with validation error: #{topic.errors[:approved].first}" + end end - end - def with_each_topic_approved_value(values) - topic = Topic.new(title: "numeric test", content: "whatever") - values.each do |value| - topic.approved = value - yield topic, value + def with_each_topic_approved_value(values) + topic = Topic.new(title: "numeric test", content: "whatever") + values.each do |value| + topic.approved = value + yield topic, value + end end - end end diff --git a/activemodel/test/models/custom_reader.rb b/activemodel/test/models/custom_reader.rb index 2fbcf79c3d..dc26bb10ff 100644 --- a/activemodel/test/models/custom_reader.rb +++ b/activemodel/test/models/custom_reader.rb @@ -12,4 +12,4 @@ class CustomReader def read_attribute_for_validation(key) @data[key] end -end \ No newline at end of file +end diff --git a/activemodel/test/models/topic.rb b/activemodel/test/models/topic.rb index fed50bc361..287fee0523 100644 --- a/activemodel/test/models/topic.rb +++ b/activemodel/test/models/topic.rb @@ -38,7 +38,7 @@ class Topic end def my_word_tokenizer(str) - str.scan(/\w+/) + str.scan(/\w+/) end end diff --git a/activemodel/test/models/track_back.rb b/activemodel/test/models/track_back.rb index 768c96ecf0..357ee37d6d 100644 --- a/activemodel/test/models/track_back.rb +++ b/activemodel/test/models/track_back.rb @@ -8,4 +8,4 @@ class Post class NamedTrackBack extend ActiveModel::Naming end -end \ No newline at end of file +end diff --git a/activemodel/test/models/user.rb b/activemodel/test/models/user.rb index 1ec6001c48..6556b1a7d9 100644 --- a/activemodel/test/models/user.rb +++ b/activemodel/test/models/user.rb @@ -1,7 +1,7 @@ class User extend ActiveModel::Callbacks include ActiveModel::SecurePassword - + define_model_callbacks :create has_secure_password diff --git a/activerecord/examples/performance.rb b/activerecord/examples/performance.rb index cb9ee58f59..2098341763 100644 --- a/activerecord/examples/performance.rb +++ b/activerecord/examples/performance.rb @@ -120,10 +120,10 @@ Benchmark.ips(TIME) do |x| Exhibit.first.look end - x.report "Model.take" do + x.report "Model.take" do Exhibit.take end - + x.report("Model.all limit(100)") do Exhibit.look Exhibit.limit(100) end diff --git a/activerecord/lib/active_record/aggregations.rb b/activerecord/lib/active_record/aggregations.rb index 9f965052c5..55076c4314 100644 --- a/activerecord/lib/active_record/aggregations.rb +++ b/activerecord/lib/active_record/aggregations.rb @@ -179,104 +179,104 @@ module ActiveRecord # # Customer.where(balance: Money.new(20, "USD")) # - module ClassMethods - # Adds reader and writer methods for manipulating a value object: - # composed_of :address adds address and address=(new_address) methods. - # - # Options are: - # * :class_name - Specifies the class name of the association. Use it only if that name - # can't be inferred from the part id. So composed_of :address will by default be linked - # to the Address class, but if the real class name is +CompanyAddress+, you'll have to specify it - # with this option. - # * :mapping - Specifies the mapping of entity attributes to attributes of the value - # object. Each mapping is represented as an array where the first item is the name of the - # entity attribute and the second item is the name of the attribute in the value object. The - # order in which mappings are defined determines the order in which attributes are sent to the - # value class constructor. - # * :allow_nil - Specifies that the value object will not be instantiated when all mapped - # attributes are +nil+. Setting the value object to +nil+ has the effect of writing +nil+ to all - # mapped attributes. - # This defaults to +false+. - # * :constructor - A symbol specifying the name of the constructor method or a Proc that - # is called to initialize the value object. The constructor is passed all of the mapped attributes, - # in the order that they are defined in the :mapping option, as arguments and uses them - # to instantiate a :class_name object. - # The default is :new. - # * :converter - A symbol specifying the name of a class method of :class_name - # or a Proc that is called when a new value is assigned to the value object. The converter is - # passed the single value that is used in the assignment and is only called if the new value is - # not an instance of :class_name. If :allow_nil is set to true, the converter - # can return nil to skip the assignment. - # - # Option examples: - # composed_of :temperature, mapping: %w(reading celsius) - # composed_of :balance, class_name: "Money", mapping: %w(balance amount), - # converter: Proc.new { |balance| balance.to_money } - # composed_of :address, mapping: [ %w(address_street street), %w(address_city city) ] - # composed_of :gps_location - # composed_of :gps_location, allow_nil: true - # composed_of :ip_address, - # class_name: 'IPAddr', - # mapping: %w(ip to_i), - # constructor: Proc.new { |ip| IPAddr.new(ip, Socket::AF_INET) }, - # converter: Proc.new { |ip| ip.is_a?(Integer) ? IPAddr.new(ip, Socket::AF_INET) : IPAddr.new(ip.to_s) } - # - def composed_of(part_id, options = {}) - options.assert_valid_keys(:class_name, :mapping, :allow_nil, :constructor, :converter) + module ClassMethods + # Adds reader and writer methods for manipulating a value object: + # composed_of :address adds address and address=(new_address) methods. + # + # Options are: + # * :class_name - Specifies the class name of the association. Use it only if that name + # can't be inferred from the part id. So composed_of :address will by default be linked + # to the Address class, but if the real class name is +CompanyAddress+, you'll have to specify it + # with this option. + # * :mapping - Specifies the mapping of entity attributes to attributes of the value + # object. Each mapping is represented as an array where the first item is the name of the + # entity attribute and the second item is the name of the attribute in the value object. The + # order in which mappings are defined determines the order in which attributes are sent to the + # value class constructor. + # * :allow_nil - Specifies that the value object will not be instantiated when all mapped + # attributes are +nil+. Setting the value object to +nil+ has the effect of writing +nil+ to all + # mapped attributes. + # This defaults to +false+. + # * :constructor - A symbol specifying the name of the constructor method or a Proc that + # is called to initialize the value object. The constructor is passed all of the mapped attributes, + # in the order that they are defined in the :mapping option, as arguments and uses them + # to instantiate a :class_name object. + # The default is :new. + # * :converter - A symbol specifying the name of a class method of :class_name + # or a Proc that is called when a new value is assigned to the value object. The converter is + # passed the single value that is used in the assignment and is only called if the new value is + # not an instance of :class_name. If :allow_nil is set to true, the converter + # can return nil to skip the assignment. + # + # Option examples: + # composed_of :temperature, mapping: %w(reading celsius) + # composed_of :balance, class_name: "Money", mapping: %w(balance amount), + # converter: Proc.new { |balance| balance.to_money } + # composed_of :address, mapping: [ %w(address_street street), %w(address_city city) ] + # composed_of :gps_location + # composed_of :gps_location, allow_nil: true + # composed_of :ip_address, + # class_name: 'IPAddr', + # mapping: %w(ip to_i), + # constructor: Proc.new { |ip| IPAddr.new(ip, Socket::AF_INET) }, + # converter: Proc.new { |ip| ip.is_a?(Integer) ? IPAddr.new(ip, Socket::AF_INET) : IPAddr.new(ip.to_s) } + # + def composed_of(part_id, options = {}) + options.assert_valid_keys(:class_name, :mapping, :allow_nil, :constructor, :converter) - name = part_id.id2name - class_name = options[:class_name] || name.camelize - mapping = options[:mapping] || [ name, name ] - mapping = [ mapping ] unless mapping.first.is_a?(Array) - allow_nil = options[:allow_nil] || false - constructor = options[:constructor] || :new - converter = options[:converter] + name = part_id.id2name + class_name = options[:class_name] || name.camelize + mapping = options[:mapping] || [ name, name ] + mapping = [ mapping ] unless mapping.first.is_a?(Array) + allow_nil = options[:allow_nil] || false + constructor = options[:constructor] || :new + converter = options[:converter] - reader_method(name, class_name, mapping, allow_nil, constructor) - writer_method(name, class_name, mapping, allow_nil, converter) + reader_method(name, class_name, mapping, allow_nil, constructor) + writer_method(name, class_name, mapping, allow_nil, converter) - reflection = ActiveRecord::Reflection.create(:composed_of, part_id, nil, options, self) - Reflection.add_aggregate_reflection self, part_id, reflection - end + reflection = ActiveRecord::Reflection.create(:composed_of, part_id, nil, options, self) + Reflection.add_aggregate_reflection self, part_id, reflection + end - 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)} - object = constructor.respond_to?(:call) ? - constructor.call(*attrs) : - class_name.constantize.send(constructor, *attrs) - @aggregation_cache[name] = object + 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)} + object = constructor.respond_to?(:call) ? + constructor.call(*attrs) : + class_name.constantize.send(constructor, *attrs) + @aggregation_cache[name] = object + end + @aggregation_cache[name] end - @aggregation_cache[name] end - end - def writer_method(name, class_name, mapping, allow_nil, converter) - define_method("#{name}=") do |part| - klass = class_name.constantize + def writer_method(name, class_name, mapping, allow_nil, converter) + define_method("#{name}=") do |part| + klass = class_name.constantize - unless part.is_a?(klass) || converter.nil? || part.nil? - part = converter.respond_to?(:call) ? converter.call(part) : klass.send(converter, part) - end + unless part.is_a?(klass) || converter.nil? || part.nil? + part = converter.respond_to?(:call) ? converter.call(part) : klass.send(converter, part) + end - hash_from_multiparameter_assignment = part.is_a?(Hash) && - part.each_key.all? { |k| k.is_a?(Integer) } - if hash_from_multiparameter_assignment - raise ArgumentError unless part.size == part.each_key.max - part = klass.new(*part.sort.map(&:last)) - end + hash_from_multiparameter_assignment = part.is_a?(Hash) && + part.each_key.all? { |k| k.is_a?(Integer) } + if hash_from_multiparameter_assignment + raise ArgumentError unless part.size == part.each_key.max + part = klass.new(*part.sort.map(&:last)) + end - if part.nil? && allow_nil - mapping.each { |key, _| self[key] = nil } - @aggregation_cache[name] = nil - else - mapping.each { |key, value| self[key] = part.send(value) } - @aggregation_cache[name] = part.freeze + if part.nil? && allow_nil + mapping.each { |key, _| self[key] = nil } + @aggregation_cache[name] = nil + else + mapping.each { |key, value| self[key] = part.send(value) } + @aggregation_cache[name] = part.freeze + end end end - end - end + end end end diff --git a/activerecord/lib/active_record/association_relation.rb b/activerecord/lib/active_record/association_relation.rb index c18e88e4cf..2da2d968b9 100644 --- a/activerecord/lib/active_record/association_relation.rb +++ b/activerecord/lib/active_record/association_relation.rb @@ -28,8 +28,8 @@ module ActiveRecord private - def exec_queries - super.each { |r| @association.set_inverse_instance r } - end + def exec_queries + super.each { |r| @association.set_inverse_instance r } + end end end diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index d1d71391e6..659e512ce2 100644 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -1150,684 +1150,684 @@ module ActiveRecord # # All of the association macros can be specialized through options. This makes cases # more complex than the simple and guessable ones possible. - module ClassMethods - # Specifies a one-to-many association. The following methods for retrieval and query of - # collections of associated objects will be added: - # - # +collection+ is a placeholder for the symbol passed as the +name+ argument, so - # has_many :clients would add among others clients.empty?. - # - # [collection(force_reload = false)] - # Returns an array of all the associated objects. - # An empty array is returned if none are found. - # [collection<<(object, ...)] - # Adds one or more objects to the collection by setting their foreign keys to the collection's primary key. - # Note that this operation instantly fires update SQL without waiting for the save or update call on the - # parent object, unless the parent object is a new record. - # This will also run validations and callbacks of associated object(s). - # [collection.delete(object, ...)] - # Removes one or more objects from the collection by setting their foreign keys to +NULL+. - # Objects will be in addition destroyed if they're associated with dependent: :destroy, - # and deleted if they're associated with dependent: :delete_all. - # - # If the :through option is used, then the join records are deleted (rather than - # nullified) by default, but you can specify dependent: :destroy or - # dependent: :nullify to override this. - # [collection.destroy(object, ...)] - # Removes one or more objects from the collection by running destroy on - # each record, regardless of any dependent option, ensuring callbacks are run. - # - # If the :through option is used, then the join records are destroyed - # instead, not the objects themselves. - # [collection=objects] - # Replaces the collections content by deleting and adding objects as appropriate. If the :through - # option is true callbacks in the join models are triggered except destroy callbacks, since deletion is - # direct by default. You can specify dependent: :destroy or - # dependent: :nullify to override this. - # [collection_singular_ids] - # Returns an array of the associated objects' ids - # [collection_singular_ids=ids] - # Replace the collection with the objects identified by the primary keys in +ids+. This - # method loads the models and calls collection=. See above. - # [collection.clear] - # Removes every object from the collection. This destroys the associated objects if they - # are associated with dependent: :destroy, deletes them directly from the - # database if dependent: :delete_all, otherwise sets their foreign keys to +NULL+. - # If the :through option is true no destroy callbacks are invoked on the join models. - # Join models are directly deleted. - # [collection.empty?] - # Returns +true+ if there are no associated objects. - # [collection.size] - # Returns the number of associated objects. - # [collection.find(...)] - # Finds an associated object according to the same rules as ActiveRecord::FinderMethods#find. - # [collection.exists?(...)] - # Checks whether an associated object with the given conditions exists. - # Uses the same rules as ActiveRecord::FinderMethods#exists?. - # [collection.build(attributes = {}, ...)] - # Returns one or more new objects of the collection type that have been instantiated - # with +attributes+ and linked to this object through a foreign key, but have not yet - # been saved. - # [collection.create(attributes = {})] - # Returns a new object of the collection type that has been instantiated - # with +attributes+, linked to this object through a foreign key, and that has already - # been saved (if it passed the validation). *Note*: This only works if the base model - # already exists in the DB, not if it is a new (unsaved) record! - # [collection.create!(attributes = {})] - # Does the same as collection.create, but raises ActiveRecord::RecordInvalid - # if the record is invalid. - # - # === Example - # - # A Firm class declares has_many :clients, which will add: - # * Firm#clients (similar to Client.where(firm_id: id)) - # * Firm#clients<< - # * Firm#clients.delete - # * Firm#clients.destroy - # * Firm#clients= - # * Firm#client_ids - # * Firm#client_ids= - # * Firm#clients.clear - # * Firm#clients.empty? (similar to firm.clients.size == 0) - # * Firm#clients.size (similar to Client.count "firm_id = #{id}") - # * Firm#clients.find (similar to Client.where(firm_id: id).find(id)) - # * Firm#clients.exists?(name: 'ACME') (similar to Client.exists?(name: 'ACME', firm_id: firm.id)) - # * Firm#clients.build (similar to Client.new("firm_id" => id)) - # * Firm#clients.create (similar to c = Client.new("firm_id" => id); c.save; c) - # * Firm#clients.create! (similar to c = Client.new("firm_id" => id); c.save!) - # The declaration can also include an +options+ hash to specialize the behavior of the association. - # - # === Scopes - # - # You can pass a second argument +scope+ as a callable (i.e. proc or - # lambda) to retrieve a specific set of records or customize the generated - # query when you access the associated collection. - # - # Scope examples: - # has_many :comments, -> { where(author_id: 1) } - # has_many :employees, -> { joins(:address) } - # has_many :posts, ->(post) { where("max_post_length > ?", post.length) } - # - # === Extensions - # - # The +extension+ argument allows you to pass a block into a has_many - # association. This is useful for adding new finders, creators and other - # factory-type methods to be used as part of the association. - # - # Extension examples: - # has_many :employees do - # def find_or_create_by_name(name) - # first_name, last_name = name.split(" ", 2) - # find_or_create_by(first_name: first_name, last_name: last_name) - # end - # end - # - # === Options - # [:class_name] - # Specify the class name of the association. Use it only if that name can't be inferred - # from the association name. So has_many :products will by default be linked - # to the +Product+ class, but if the real class name is +SpecialProduct+, you'll have to - # specify it with this option. - # [:foreign_key] - # Specify the foreign key used for the association. By default this is guessed to be the name - # of this class in lower-case and "_id" suffixed. So a Person class that makes a #has_many - # association will use "person_id" as the default :foreign_key. - # [:foreign_type] - # Specify the column used to store the associated object's type, if this is a polymorphic - # association. By default this is guessed to be the name of the polymorphic association - # specified on "as" option with a "_type" suffix. So a class that defines a - # has_many :tags, as: :taggable association will use "taggable_type" as the - # default :foreign_type. - # [:primary_key] - # Specify the name of the column to use as the primary key for the association. By default this is +id+. - # [:dependent] - # Controls what happens to the associated objects when - # their owner is destroyed. Note that these are implemented as - # callbacks, and Rails executes callbacks in order. Therefore, other - # similar callbacks may affect the :dependent behavior, and the - # :dependent behavior may affect other callbacks. - # - # * :destroy causes all the associated objects to also be destroyed. - # * :delete_all causes all the associated objects to be deleted directly from the database (so callbacks will not be executed). - # * :nullify causes the foreign keys to be set to +NULL+. Callbacks are not executed. - # * :restrict_with_exception causes an exception to be raised if there are any associated records. - # * :restrict_with_error causes an error to be added to the owner if there are any associated objects. - # - # If using with the :through option, the association on the join model must be - # a #belongs_to, and the records which get deleted are the join records, rather than - # the associated records. - # [:counter_cache] - # This option can be used to configure a custom named :counter_cache. You only need this option, - # when you customized the name of your :counter_cache on the #belongs_to association. - # [:as] - # Specifies a polymorphic interface (See #belongs_to). - # [:through] - # Specifies an association through which to perform the query. This can be any other type - # of association, including other :through associations. Options for :class_name, - # :primary_key and :foreign_key are ignored, as the association uses the - # source reflection. - # - # If the association on the join model is a #belongs_to, the collection can be modified - # and the records on the :through model will be automatically created and removed - # as appropriate. Otherwise, the collection is read-only, so you should manipulate the - # :through association directly. - # - # If you are going to modify the association (rather than just read from it), then it is - # a good idea to set the :inverse_of option on the source association on the - # join model. This allows associated records to be built which will automatically create - # the appropriate join model records when they are saved. (See the 'Association Join Models' - # section above.) - # [:source] - # Specifies the source association name used by #has_many :through queries. - # Only use it if the name cannot be inferred from the association. - # has_many :subscribers, through: :subscriptions will look for either :subscribers or - # :subscriber on Subscription, unless a :source is given. - # [:source_type] - # Specifies type of the source association used by #has_many :through queries where the source - # association is a polymorphic #belongs_to. - # [:validate] - # When set to +true+, validates new objects added to association when saving the parent object. +true+ by default. - # If you want to ensure associated objects are revalidated on every update, use +validates_associated+. - # [:autosave] - # If true, always save the associated objects or destroy them if marked for destruction, - # when saving the parent object. If false, never save or destroy the associated objects. - # By default, only save associated objects that are new records. This option is implemented as a - # +before_save+ callback. Because callbacks are run in the order they are defined, associated objects - # may need to be explicitly saved in any user-defined +before_save+ callbacks. - # - # Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for sets - # :autosave to true. - # [:inverse_of] - # Specifies the name of the #belongs_to association on the associated object - # that is the inverse of this #has_many association. Does not work in combination - # with :through or :as options. - # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail. - # [:extend] - # Specifies a module or array of modules that will be extended into the association object returned. - # Useful for defining methods on associations, especially when they should be shared between multiple - # association objects. - # - # Option examples: - # has_many :comments, -> { order("posted_on") } - # has_many :comments, -> { includes(:author) } - # has_many :people, -> { where(deleted: false).order("name") }, class_name: "Person" - # has_many :tracks, -> { order("position") }, dependent: :destroy - # has_many :comments, dependent: :nullify - # has_many :tags, as: :taggable - # has_many :reports, -> { readonly } - # has_many :subscribers, through: :subscriptions, source: :user - def has_many(name, scope = nil, options = {}, &extension) - reflection = Builder::HasMany.build(self, name, scope, options, &extension) - Reflection.add_reflection self, name, reflection - end - - # Specifies a one-to-one association with another class. This method should only be used - # if the other class contains the foreign key. If the current class contains the foreign key, - # then you should use #belongs_to instead. See also ActiveRecord::Associations::ClassMethods's overview - # on when to use #has_one and when to use #belongs_to. - # - # The following methods for retrieval and query of a single associated object will be added: - # - # +association+ is a placeholder for the symbol passed as the +name+ argument, so - # has_one :manager would add among others manager.nil?. - # - # [association(force_reload = false)] - # Returns the associated object. +nil+ is returned if none is found. - # [association=(associate)] - # Assigns the associate object, extracts the primary key, sets it as the foreign key, - # and saves the associate object. To avoid database inconsistencies, permanently deletes an existing - # associated object when assigning a new one, even if the new one isn't saved to database. - # [build_association(attributes = {})] - # Returns a new object of the associated type that has been instantiated - # with +attributes+ and linked to this object through a foreign key, but has not - # yet been saved. - # [create_association(attributes = {})] - # Returns a new object of the associated type that has been instantiated - # with +attributes+, linked to this object through a foreign key, and that - # has already been saved (if it passed the validation). - # [create_association!(attributes = {})] - # Does the same as create_association, but raises ActiveRecord::RecordInvalid - # if the record is invalid. - # - # === Example - # - # An Account class declares has_one :beneficiary, which will add: - # * Account#beneficiary (similar to Beneficiary.where(account_id: id).first) - # * Account#beneficiary=(beneficiary) (similar to beneficiary.account_id = account.id; beneficiary.save) - # * Account#build_beneficiary (similar to Beneficiary.new("account_id" => id)) - # * Account#create_beneficiary (similar to b = Beneficiary.new("account_id" => id); b.save; b) - # * Account#create_beneficiary! (similar to b = Beneficiary.new("account_id" => id); b.save!; b) - # - # === Scopes - # - # You can pass a second argument +scope+ as a callable (i.e. proc or - # lambda) to retrieve a specific record or customize the generated query - # when you access the associated object. - # - # Scope examples: - # has_one :author, -> { where(comment_id: 1) } - # has_one :employer, -> { joins(:company) } - # has_one :dob, ->(dob) { where("Date.new(2000, 01, 01) > ?", dob) } - # - # === Options - # - # The declaration can also include an +options+ hash to specialize the behavior of the association. - # - # Options are: - # [:class_name] - # Specify the class name of the association. Use it only if that name can't be inferred - # from the association name. So has_one :manager will by default be linked to the Manager class, but - # if the real class name is Person, you'll have to specify it with this option. - # [:dependent] - # Controls what happens to the associated object when - # its owner is destroyed: - # - # * :destroy causes the associated object to also be destroyed - # * :delete causes the associated object to be deleted directly from the database (so callbacks will not execute) - # * :nullify causes the foreign key to be set to +NULL+. Callbacks are not executed. - # * :restrict_with_exception causes an exception to be raised if there is an associated record - # * :restrict_with_error causes an error to be added to the owner if there is an associated object - # - # Note that :dependent option is ignored when using :through option. - # [:foreign_key] - # Specify the foreign key used for the association. By default this is guessed to be the name - # of this class in lower-case and "_id" suffixed. So a Person class that makes a #has_one association - # will use "person_id" as the default :foreign_key. - # [:foreign_type] - # Specify the column used to store the associated object's type, if this is a polymorphic - # association. By default this is guessed to be the name of the polymorphic association - # specified on "as" option with a "_type" suffix. So a class that defines a - # has_one :tag, as: :taggable association will use "taggable_type" as the - # default :foreign_type. - # [:primary_key] - # Specify the method that returns the primary key used for the association. By default this is +id+. - # [:as] - # Specifies a polymorphic interface (See #belongs_to). - # [:through] - # Specifies a Join Model through which to perform the query. Options for :class_name, - # :primary_key, and :foreign_key are ignored, as the association uses the - # source reflection. You can only use a :through query through a #has_one - # or #belongs_to association on the join model. - # [:source] - # Specifies the source association name used by #has_one :through queries. - # Only use it if the name cannot be inferred from the association. - # has_one :favorite, through: :favorites will look for a - # :favorite on Favorite, unless a :source is given. - # [:source_type] - # Specifies type of the source association used by #has_one :through queries where the source - # association is a polymorphic #belongs_to. - # [:validate] - # When set to +true+, validates new objects added to association when saving the parent object. +false+ by default. - # If you want to ensure associated objects are revalidated on every update, use +validates_associated+. - # [:autosave] - # If true, always save the associated object or destroy it if marked for destruction, - # when saving the parent object. If false, never save or destroy the associated object. - # By default, only save the associated object if it's a new record. - # - # Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for sets - # :autosave to true. - # [:inverse_of] - # Specifies the name of the #belongs_to association on the associated object - # that is the inverse of this #has_one association. Does not work in combination - # with :through or :as options. - # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail. - # [:required] - # When set to +true+, the association will also have its presence validated. - # This will validate the association itself, not the id. You can use - # +:inverse_of+ to avoid an extra query during validation. - # - # Option examples: - # has_one :credit_card, dependent: :destroy # destroys the associated credit card - # has_one :credit_card, dependent: :nullify # updates the associated records foreign - # # key value to NULL rather than destroying it - # has_one :last_comment, -> { order('posted_on') }, class_name: "Comment" - # has_one :project_manager, -> { where(role: 'project_manager') }, class_name: "Person" - # has_one :attachment, as: :attachable - # has_one :boss, -> { readonly } - # has_one :club, through: :membership - # has_one :primary_address, -> { where(primary: true) }, through: :addressables, source: :addressable - # has_one :credit_card, required: true - def has_one(name, scope = nil, options = {}) - reflection = Builder::HasOne.build(self, name, scope, options) - Reflection.add_reflection self, name, reflection - end + module ClassMethods + # Specifies a one-to-many association. The following methods for retrieval and query of + # collections of associated objects will be added: + # + # +collection+ is a placeholder for the symbol passed as the +name+ argument, so + # has_many :clients would add among others clients.empty?. + # + # [collection(force_reload = false)] + # Returns an array of all the associated objects. + # An empty array is returned if none are found. + # [collection<<(object, ...)] + # Adds one or more objects to the collection by setting their foreign keys to the collection's primary key. + # Note that this operation instantly fires update SQL without waiting for the save or update call on the + # parent object, unless the parent object is a new record. + # This will also run validations and callbacks of associated object(s). + # [collection.delete(object, ...)] + # Removes one or more objects from the collection by setting their foreign keys to +NULL+. + # Objects will be in addition destroyed if they're associated with dependent: :destroy, + # and deleted if they're associated with dependent: :delete_all. + # + # If the :through option is used, then the join records are deleted (rather than + # nullified) by default, but you can specify dependent: :destroy or + # dependent: :nullify to override this. + # [collection.destroy(object, ...)] + # Removes one or more objects from the collection by running destroy on + # each record, regardless of any dependent option, ensuring callbacks are run. + # + # If the :through option is used, then the join records are destroyed + # instead, not the objects themselves. + # [collection=objects] + # Replaces the collections content by deleting and adding objects as appropriate. If the :through + # option is true callbacks in the join models are triggered except destroy callbacks, since deletion is + # direct by default. You can specify dependent: :destroy or + # dependent: :nullify to override this. + # [collection_singular_ids] + # Returns an array of the associated objects' ids + # [collection_singular_ids=ids] + # Replace the collection with the objects identified by the primary keys in +ids+. This + # method loads the models and calls collection=. See above. + # [collection.clear] + # Removes every object from the collection. This destroys the associated objects if they + # are associated with dependent: :destroy, deletes them directly from the + # database if dependent: :delete_all, otherwise sets their foreign keys to +NULL+. + # If the :through option is true no destroy callbacks are invoked on the join models. + # Join models are directly deleted. + # [collection.empty?] + # Returns +true+ if there are no associated objects. + # [collection.size] + # Returns the number of associated objects. + # [collection.find(...)] + # Finds an associated object according to the same rules as ActiveRecord::FinderMethods#find. + # [collection.exists?(...)] + # Checks whether an associated object with the given conditions exists. + # Uses the same rules as ActiveRecord::FinderMethods#exists?. + # [collection.build(attributes = {}, ...)] + # Returns one or more new objects of the collection type that have been instantiated + # with +attributes+ and linked to this object through a foreign key, but have not yet + # been saved. + # [collection.create(attributes = {})] + # Returns a new object of the collection type that has been instantiated + # with +attributes+, linked to this object through a foreign key, and that has already + # been saved (if it passed the validation). *Note*: This only works if the base model + # already exists in the DB, not if it is a new (unsaved) record! + # [collection.create!(attributes = {})] + # Does the same as collection.create, but raises ActiveRecord::RecordInvalid + # if the record is invalid. + # + # === Example + # + # A Firm class declares has_many :clients, which will add: + # * Firm#clients (similar to Client.where(firm_id: id)) + # * Firm#clients<< + # * Firm#clients.delete + # * Firm#clients.destroy + # * Firm#clients= + # * Firm#client_ids + # * Firm#client_ids= + # * Firm#clients.clear + # * Firm#clients.empty? (similar to firm.clients.size == 0) + # * Firm#clients.size (similar to Client.count "firm_id = #{id}") + # * Firm#clients.find (similar to Client.where(firm_id: id).find(id)) + # * Firm#clients.exists?(name: 'ACME') (similar to Client.exists?(name: 'ACME', firm_id: firm.id)) + # * Firm#clients.build (similar to Client.new("firm_id" => id)) + # * Firm#clients.create (similar to c = Client.new("firm_id" => id); c.save; c) + # * Firm#clients.create! (similar to c = Client.new("firm_id" => id); c.save!) + # The declaration can also include an +options+ hash to specialize the behavior of the association. + # + # === Scopes + # + # You can pass a second argument +scope+ as a callable (i.e. proc or + # lambda) to retrieve a specific set of records or customize the generated + # query when you access the associated collection. + # + # Scope examples: + # has_many :comments, -> { where(author_id: 1) } + # has_many :employees, -> { joins(:address) } + # has_many :posts, ->(post) { where("max_post_length > ?", post.length) } + # + # === Extensions + # + # The +extension+ argument allows you to pass a block into a has_many + # association. This is useful for adding new finders, creators and other + # factory-type methods to be used as part of the association. + # + # Extension examples: + # has_many :employees do + # def find_or_create_by_name(name) + # first_name, last_name = name.split(" ", 2) + # find_or_create_by(first_name: first_name, last_name: last_name) + # end + # end + # + # === Options + # [:class_name] + # Specify the class name of the association. Use it only if that name can't be inferred + # from the association name. So has_many :products will by default be linked + # to the +Product+ class, but if the real class name is +SpecialProduct+, you'll have to + # specify it with this option. + # [:foreign_key] + # Specify the foreign key used for the association. By default this is guessed to be the name + # of this class in lower-case and "_id" suffixed. So a Person class that makes a #has_many + # association will use "person_id" as the default :foreign_key. + # [:foreign_type] + # Specify the column used to store the associated object's type, if this is a polymorphic + # association. By default this is guessed to be the name of the polymorphic association + # specified on "as" option with a "_type" suffix. So a class that defines a + # has_many :tags, as: :taggable association will use "taggable_type" as the + # default :foreign_type. + # [:primary_key] + # Specify the name of the column to use as the primary key for the association. By default this is +id+. + # [:dependent] + # Controls what happens to the associated objects when + # their owner is destroyed. Note that these are implemented as + # callbacks, and Rails executes callbacks in order. Therefore, other + # similar callbacks may affect the :dependent behavior, and the + # :dependent behavior may affect other callbacks. + # + # * :destroy causes all the associated objects to also be destroyed. + # * :delete_all causes all the associated objects to be deleted directly from the database (so callbacks will not be executed). + # * :nullify causes the foreign keys to be set to +NULL+. Callbacks are not executed. + # * :restrict_with_exception causes an exception to be raised if there are any associated records. + # * :restrict_with_error causes an error to be added to the owner if there are any associated objects. + # + # If using with the :through option, the association on the join model must be + # a #belongs_to, and the records which get deleted are the join records, rather than + # the associated records. + # [:counter_cache] + # This option can be used to configure a custom named :counter_cache. You only need this option, + # when you customized the name of your :counter_cache on the #belongs_to association. + # [:as] + # Specifies a polymorphic interface (See #belongs_to). + # [:through] + # Specifies an association through which to perform the query. This can be any other type + # of association, including other :through associations. Options for :class_name, + # :primary_key and :foreign_key are ignored, as the association uses the + # source reflection. + # + # If the association on the join model is a #belongs_to, the collection can be modified + # and the records on the :through model will be automatically created and removed + # as appropriate. Otherwise, the collection is read-only, so you should manipulate the + # :through association directly. + # + # If you are going to modify the association (rather than just read from it), then it is + # a good idea to set the :inverse_of option on the source association on the + # join model. This allows associated records to be built which will automatically create + # the appropriate join model records when they are saved. (See the 'Association Join Models' + # section above.) + # [:source] + # Specifies the source association name used by #has_many :through queries. + # Only use it if the name cannot be inferred from the association. + # has_many :subscribers, through: :subscriptions will look for either :subscribers or + # :subscriber on Subscription, unless a :source is given. + # [:source_type] + # Specifies type of the source association used by #has_many :through queries where the source + # association is a polymorphic #belongs_to. + # [:validate] + # When set to +true+, validates new objects added to association when saving the parent object. +true+ by default. + # If you want to ensure associated objects are revalidated on every update, use +validates_associated+. + # [:autosave] + # If true, always save the associated objects or destroy them if marked for destruction, + # when saving the parent object. If false, never save or destroy the associated objects. + # By default, only save associated objects that are new records. This option is implemented as a + # +before_save+ callback. Because callbacks are run in the order they are defined, associated objects + # may need to be explicitly saved in any user-defined +before_save+ callbacks. + # + # Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for sets + # :autosave to true. + # [:inverse_of] + # Specifies the name of the #belongs_to association on the associated object + # that is the inverse of this #has_many association. Does not work in combination + # with :through or :as options. + # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail. + # [:extend] + # Specifies a module or array of modules that will be extended into the association object returned. + # Useful for defining methods on associations, especially when they should be shared between multiple + # association objects. + # + # Option examples: + # has_many :comments, -> { order("posted_on") } + # has_many :comments, -> { includes(:author) } + # has_many :people, -> { where(deleted: false).order("name") }, class_name: "Person" + # has_many :tracks, -> { order("position") }, dependent: :destroy + # has_many :comments, dependent: :nullify + # has_many :tags, as: :taggable + # has_many :reports, -> { readonly } + # has_many :subscribers, through: :subscriptions, source: :user + def has_many(name, scope = nil, options = {}, &extension) + reflection = Builder::HasMany.build(self, name, scope, options, &extension) + Reflection.add_reflection self, name, reflection + end - # Specifies a one-to-one association with another class. This method should only be used - # if this class contains the foreign key. If the other class contains the foreign key, - # then you should use #has_one instead. See also ActiveRecord::Associations::ClassMethods's overview - # on when to use #has_one and when to use #belongs_to. - # - # Methods will be added for retrieval and query for a single associated object, for which - # this object holds an id: - # - # +association+ is a placeholder for the symbol passed as the +name+ argument, so - # belongs_to :author would add among others author.nil?. - # - # [association(force_reload = false)] - # Returns the associated object. +nil+ is returned if none is found. - # [association=(associate)] - # Assigns the associate object, extracts the primary key, and sets it as the foreign key. - # [build_association(attributes = {})] - # Returns a new object of the associated type that has been instantiated - # with +attributes+ and linked to this object through a foreign key, but has not yet been saved. - # [create_association(attributes = {})] - # Returns a new object of the associated type that has been instantiated - # with +attributes+, linked to this object through a foreign key, and that - # has already been saved (if it passed the validation). - # [create_association!(attributes = {})] - # Does the same as create_association, but raises ActiveRecord::RecordInvalid - # if the record is invalid. - # - # === Example - # - # A Post class declares belongs_to :author, which will add: - # * Post#author (similar to Author.find(author_id)) - # * Post#author=(author) (similar to post.author_id = author.id) - # * Post#build_author (similar to post.author = Author.new) - # * Post#create_author (similar to post.author = Author.new; post.author.save; post.author) - # * Post#create_author! (similar to post.author = Author.new; post.author.save!; post.author) - # The declaration can also include an +options+ hash to specialize the behavior of the association. - # - # === Scopes - # - # You can pass a second argument +scope+ as a callable (i.e. proc or - # lambda) to retrieve a specific record or customize the generated query - # when you access the associated object. - # - # Scope examples: - # belongs_to :firm, -> { where(id: 2) } - # belongs_to :user, -> { joins(:friends) } - # belongs_to :level, ->(level) { where("game_level > ?", level.current) } - # - # === Options - # - # [:class_name] - # Specify the class name of the association. Use it only if that name can't be inferred - # from the association name. So belongs_to :author will by default be linked to the Author class, but - # if the real class name is Person, you'll have to specify it with this option. - # [:foreign_key] - # Specify the foreign key used for the association. By default this is guessed to be the name - # of the association with an "_id" suffix. So a class that defines a belongs_to :person - # association will use "person_id" as the default :foreign_key. Similarly, - # belongs_to :favorite_person, class_name: "Person" will use a foreign key - # of "favorite_person_id". - # [:foreign_type] - # Specify the column used to store the associated object's type, if this is a polymorphic - # association. By default this is guessed to be the name of the association with a "_type" - # suffix. So a class that defines a belongs_to :taggable, polymorphic: true - # association will use "taggable_type" as the default :foreign_type. - # [:primary_key] - # Specify the method that returns the primary key of associated object used for the association. - # By default this is id. - # [:dependent] - # If set to :destroy, the associated object is destroyed when this object is. If set to - # :delete, the associated object is deleted *without* calling its destroy method. - # This option should not be specified when #belongs_to is used in conjunction with - # a #has_many relationship on another class because of the potential to leave - # orphaned records behind. - # [:counter_cache] - # Caches the number of belonging objects on the associate class through the use of CounterCache::ClassMethods#increment_counter - # and CounterCache::ClassMethods#decrement_counter. The counter cache is incremented when an object of this - # class is created and decremented when it's destroyed. This requires that a column - # named #{table_name}_count (such as +comments_count+ for a belonging Comment class) - # is used on the associate class (such as a Post class) - that is the migration for - # #{table_name}_count is created on the associate class (such that Post.comments_count will - # return the count cached, see note below). You can also specify a custom counter - # cache column by providing a column name instead of a +true+/+false+ value to this - # option (e.g., counter_cache: :my_custom_counter.) - # Note: Specifying a counter cache will add it to that model's list of readonly attributes - # using +attr_readonly+. - # [:polymorphic] - # Specify this association is a polymorphic association by passing +true+. - # Note: If you've enabled the counter cache, then you may want to add the counter cache attribute - # to the +attr_readonly+ list in the associated classes (e.g. class Post; attr_readonly :comments_count; end). - # [:validate] - # When set to +true+, validates new objects added to association when saving the parent object. +false+ by default. - # If you want to ensure associated objects are revalidated on every update, use +validates_associated+. - # [:autosave] - # If true, always save the associated object or destroy it if marked for destruction, when - # saving the parent object. - # If false, never save or destroy the associated object. - # By default, only save the associated object if it's a new record. - # - # Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for - # sets :autosave to true. - # [:touch] - # If true, the associated object will be touched (the updated_at/on attributes set to current time) - # when this record is either saved or destroyed. If you specify a symbol, that attribute - # will be updated with the current time in addition to the updated_at/on attribute. - # Please note that with touching no validation is performed and only the +after_touch+, - # +after_commit+ and +after_rollback+ callbacks are executed. - # [:inverse_of] - # Specifies the name of the #has_one or #has_many association on the associated - # object that is the inverse of this #belongs_to association. Does not work in - # combination with the :polymorphic options. - # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail. - # [:optional] - # When set to +true+, the association will not have its presence validated. - # [:required] - # When set to +true+, the association will also have its presence validated. - # This will validate the association itself, not the id. You can use - # +:inverse_of+ to avoid an extra query during validation. - # NOTE: required is set to true by default and is deprecated. If - # you don't want to have association presence validated, use optional: true. - # - # Option examples: - # belongs_to :firm, foreign_key: "client_of" - # belongs_to :person, primary_key: "name", foreign_key: "person_name" - # belongs_to :author, class_name: "Person", foreign_key: "author_id" - # belongs_to :valid_coupon, ->(o) { where "discounts > ?", o.payments_count }, - # class_name: "Coupon", foreign_key: "coupon_id" - # belongs_to :attachable, polymorphic: true - # belongs_to :project, -> { readonly } - # belongs_to :post, counter_cache: true - # belongs_to :comment, touch: true - # belongs_to :company, touch: :employees_last_updated_at - # belongs_to :user, optional: true - def belongs_to(name, scope = nil, options = {}) - reflection = Builder::BelongsTo.build(self, name, scope, options) - Reflection.add_reflection self, name, reflection - end + # Specifies a one-to-one association with another class. This method should only be used + # if the other class contains the foreign key. If the current class contains the foreign key, + # then you should use #belongs_to instead. See also ActiveRecord::Associations::ClassMethods's overview + # on when to use #has_one and when to use #belongs_to. + # + # The following methods for retrieval and query of a single associated object will be added: + # + # +association+ is a placeholder for the symbol passed as the +name+ argument, so + # has_one :manager would add among others manager.nil?. + # + # [association(force_reload = false)] + # Returns the associated object. +nil+ is returned if none is found. + # [association=(associate)] + # Assigns the associate object, extracts the primary key, sets it as the foreign key, + # and saves the associate object. To avoid database inconsistencies, permanently deletes an existing + # associated object when assigning a new one, even if the new one isn't saved to database. + # [build_association(attributes = {})] + # Returns a new object of the associated type that has been instantiated + # with +attributes+ and linked to this object through a foreign key, but has not + # yet been saved. + # [create_association(attributes = {})] + # Returns a new object of the associated type that has been instantiated + # with +attributes+, linked to this object through a foreign key, and that + # has already been saved (if it passed the validation). + # [create_association!(attributes = {})] + # Does the same as create_association, but raises ActiveRecord::RecordInvalid + # if the record is invalid. + # + # === Example + # + # An Account class declares has_one :beneficiary, which will add: + # * Account#beneficiary (similar to Beneficiary.where(account_id: id).first) + # * Account#beneficiary=(beneficiary) (similar to beneficiary.account_id = account.id; beneficiary.save) + # * Account#build_beneficiary (similar to Beneficiary.new("account_id" => id)) + # * Account#create_beneficiary (similar to b = Beneficiary.new("account_id" => id); b.save; b) + # * Account#create_beneficiary! (similar to b = Beneficiary.new("account_id" => id); b.save!; b) + # + # === Scopes + # + # You can pass a second argument +scope+ as a callable (i.e. proc or + # lambda) to retrieve a specific record or customize the generated query + # when you access the associated object. + # + # Scope examples: + # has_one :author, -> { where(comment_id: 1) } + # has_one :employer, -> { joins(:company) } + # has_one :dob, ->(dob) { where("Date.new(2000, 01, 01) > ?", dob) } + # + # === Options + # + # The declaration can also include an +options+ hash to specialize the behavior of the association. + # + # Options are: + # [:class_name] + # Specify the class name of the association. Use it only if that name can't be inferred + # from the association name. So has_one :manager will by default be linked to the Manager class, but + # if the real class name is Person, you'll have to specify it with this option. + # [:dependent] + # Controls what happens to the associated object when + # its owner is destroyed: + # + # * :destroy causes the associated object to also be destroyed + # * :delete causes the associated object to be deleted directly from the database (so callbacks will not execute) + # * :nullify causes the foreign key to be set to +NULL+. Callbacks are not executed. + # * :restrict_with_exception causes an exception to be raised if there is an associated record + # * :restrict_with_error causes an error to be added to the owner if there is an associated object + # + # Note that :dependent option is ignored when using :through option. + # [:foreign_key] + # Specify the foreign key used for the association. By default this is guessed to be the name + # of this class in lower-case and "_id" suffixed. So a Person class that makes a #has_one association + # will use "person_id" as the default :foreign_key. + # [:foreign_type] + # Specify the column used to store the associated object's type, if this is a polymorphic + # association. By default this is guessed to be the name of the polymorphic association + # specified on "as" option with a "_type" suffix. So a class that defines a + # has_one :tag, as: :taggable association will use "taggable_type" as the + # default :foreign_type. + # [:primary_key] + # Specify the method that returns the primary key used for the association. By default this is +id+. + # [:as] + # Specifies a polymorphic interface (See #belongs_to). + # [:through] + # Specifies a Join Model through which to perform the query. Options for :class_name, + # :primary_key, and :foreign_key are ignored, as the association uses the + # source reflection. You can only use a :through query through a #has_one + # or #belongs_to association on the join model. + # [:source] + # Specifies the source association name used by #has_one :through queries. + # Only use it if the name cannot be inferred from the association. + # has_one :favorite, through: :favorites will look for a + # :favorite on Favorite, unless a :source is given. + # [:source_type] + # Specifies type of the source association used by #has_one :through queries where the source + # association is a polymorphic #belongs_to. + # [:validate] + # When set to +true+, validates new objects added to association when saving the parent object. +false+ by default. + # If you want to ensure associated objects are revalidated on every update, use +validates_associated+. + # [:autosave] + # If true, always save the associated object or destroy it if marked for destruction, + # when saving the parent object. If false, never save or destroy the associated object. + # By default, only save the associated object if it's a new record. + # + # Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for sets + # :autosave to true. + # [:inverse_of] + # Specifies the name of the #belongs_to association on the associated object + # that is the inverse of this #has_one association. Does not work in combination + # with :through or :as options. + # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail. + # [:required] + # When set to +true+, the association will also have its presence validated. + # This will validate the association itself, not the id. You can use + # +:inverse_of+ to avoid an extra query during validation. + # + # Option examples: + # has_one :credit_card, dependent: :destroy # destroys the associated credit card + # has_one :credit_card, dependent: :nullify # updates the associated records foreign + # # key value to NULL rather than destroying it + # has_one :last_comment, -> { order('posted_on') }, class_name: "Comment" + # has_one :project_manager, -> { where(role: 'project_manager') }, class_name: "Person" + # has_one :attachment, as: :attachable + # has_one :boss, -> { readonly } + # has_one :club, through: :membership + # has_one :primary_address, -> { where(primary: true) }, through: :addressables, source: :addressable + # has_one :credit_card, required: true + def has_one(name, scope = nil, options = {}) + reflection = Builder::HasOne.build(self, name, scope, options) + Reflection.add_reflection self, name, reflection + end - # Specifies a many-to-many relationship with another class. This associates two classes via an - # intermediate join table. Unless the join table is explicitly specified as an option, it is - # guessed using the lexical order of the class names. So a join between Developer and Project - # will give the default join table name of "developers_projects" because "D" precedes "P" alphabetically. - # Note that this precedence is calculated using the < operator for String. This - # means that if the strings are of different lengths, and the strings are equal when compared - # up to the shortest length, then the longer string is considered of higher - # lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" - # to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", - # but it in fact generates a join table name of "paper_boxes_papers". Be aware of this caveat, and use the - # custom :join_table option if you need to. - # If your tables share a common prefix, it will only appear once at the beginning. For example, - # the tables "catalog_categories" and "catalog_products" generate a join table name of "catalog_categories_products". - # - # The join table should not have a primary key or a model associated with it. You must manually generate the - # join table with a migration such as this: - # - # class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration[5.0] - # def change - # create_join_table :developers, :projects - # end - # end - # - # It's also a good idea to add indexes to each of those columns to speed up the joins process. - # However, in MySQL it is advised to add a compound index for both of the columns as MySQL only - # uses one index per table during the lookup. - # - # Adds the following methods for retrieval and query: - # - # +collection+ is a placeholder for the symbol passed as the +name+ argument, so - # has_and_belongs_to_many :categories would add among others categories.empty?. - # - # [collection(force_reload = false)] - # Returns an array of all the associated objects. - # An empty array is returned if none are found. - # [collection<<(object, ...)] - # Adds one or more objects to the collection by creating associations in the join table - # (collection.push and collection.concat are aliases to this method). - # Note that this operation instantly fires update SQL without waiting for the save or update call on the - # parent object, unless the parent object is a new record. - # [collection.delete(object, ...)] - # Removes one or more objects from the collection by removing their associations from the join table. - # This does not destroy the objects. - # [collection.destroy(object, ...)] - # Removes one or more objects from the collection by running destroy on each association in the join table, overriding any dependent option. - # This does not destroy the objects. - # [collection=objects] - # Replaces the collection's content by deleting and adding objects as appropriate. - # [collection_singular_ids] - # Returns an array of the associated objects' ids. - # [collection_singular_ids=ids] - # Replace the collection by the objects identified by the primary keys in +ids+. - # [collection.clear] - # Removes every object from the collection. This does not destroy the objects. - # [collection.empty?] - # Returns +true+ if there are no associated objects. - # [collection.size] - # Returns the number of associated objects. - # [collection.find(id)] - # Finds an associated object responding to the +id+ and that - # meets the condition that it has to be associated with this object. - # Uses the same rules as ActiveRecord::FinderMethods#find. - # [collection.exists?(...)] - # Checks whether an associated object with the given conditions exists. - # Uses the same rules as ActiveRecord::FinderMethods#exists?. - # [collection.build(attributes = {})] - # Returns a new object of the collection type that has been instantiated - # with +attributes+ and linked to this object through the join table, but has not yet been saved. - # [collection.create(attributes = {})] - # Returns a new object of the collection type that has been instantiated - # with +attributes+, linked to this object through the join table, and that has already been - # saved (if it passed the validation). - # - # === Example - # - # A Developer class declares has_and_belongs_to_many :projects, which will add: - # * Developer#projects - # * Developer#projects<< - # * Developer#projects.delete - # * Developer#projects.destroy - # * Developer#projects= - # * Developer#project_ids - # * Developer#project_ids= - # * Developer#projects.clear - # * Developer#projects.empty? - # * Developer#projects.size - # * Developer#projects.find(id) - # * Developer#projects.exists?(...) - # * Developer#projects.build (similar to Project.new("developer_id" => id)) - # * Developer#projects.create (similar to c = Project.new("developer_id" => id); c.save; c) - # The declaration may include an +options+ hash to specialize the behavior of the association. - # - # === Scopes - # - # You can pass a second argument +scope+ as a callable (i.e. proc or - # lambda) to retrieve a specific set of records or customize the generated - # query when you access the associated collection. - # - # Scope examples: - # has_and_belongs_to_many :projects, -> { includes(:milestones, :manager) } - # has_and_belongs_to_many :categories, ->(category) { - # where("default_category = ?", category.name) - # } - # - # === Extensions - # - # The +extension+ argument allows you to pass a block into a - # has_and_belongs_to_many association. This is useful for adding new - # finders, creators and other factory-type methods to be used as part of - # the association. - # - # Extension examples: - # has_and_belongs_to_many :contractors do - # def find_or_create_by_name(name) - # first_name, last_name = name.split(" ", 2) - # find_or_create_by(first_name: first_name, last_name: last_name) - # end - # end - # - # === Options - # - # [:class_name] - # Specify the class name of the association. Use it only if that name can't be inferred - # from the association name. So has_and_belongs_to_many :projects will by default be linked to the - # Project class, but if the real class name is SuperProject, you'll have to specify it with this option. - # [:join_table] - # Specify the name of the join table if the default based on lexical order isn't what you want. - # WARNING: If you're overwriting the table name of either class, the +table_name+ method - # MUST be declared underneath any #has_and_belongs_to_many declaration in order to work. - # [:foreign_key] - # Specify the foreign key used for the association. By default this is guessed to be the name - # of this class in lower-case and "_id" suffixed. So a Person class that makes - # a #has_and_belongs_to_many association to Project will use "person_id" as the - # default :foreign_key. - # [:association_foreign_key] - # Specify the foreign key used for the association on the receiving side of the association. - # By default this is guessed to be the name of the associated class in lower-case and "_id" suffixed. - # So if a Person class makes a #has_and_belongs_to_many association to Project, - # the association will use "project_id" as the default :association_foreign_key. - # [:validate] - # When set to +true+, validates new objects added to association when saving the parent object. +true+ by default. - # If you want to ensure associated objects are revalidated on every update, use +validates_associated+. - # [:autosave] - # If true, always save the associated objects or destroy them if marked for destruction, when - # saving the parent object. - # If false, never save or destroy the associated objects. - # By default, only save associated objects that are new records. - # - # Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for sets - # :autosave to true. - # - # Option examples: - # has_and_belongs_to_many :projects - # has_and_belongs_to_many :projects, -> { includes(:milestones, :manager) } - # has_and_belongs_to_many :nations, class_name: "Country" - # has_and_belongs_to_many :categories, join_table: "prods_cats" - # has_and_belongs_to_many :categories, -> { readonly } - def has_and_belongs_to_many(name, scope = nil, options = {}, &extension) - if scope.is_a?(Hash) - options = scope - scope = nil + # Specifies a one-to-one association with another class. This method should only be used + # if this class contains the foreign key. If the other class contains the foreign key, + # then you should use #has_one instead. See also ActiveRecord::Associations::ClassMethods's overview + # on when to use #has_one and when to use #belongs_to. + # + # Methods will be added for retrieval and query for a single associated object, for which + # this object holds an id: + # + # +association+ is a placeholder for the symbol passed as the +name+ argument, so + # belongs_to :author would add among others author.nil?. + # + # [association(force_reload = false)] + # Returns the associated object. +nil+ is returned if none is found. + # [association=(associate)] + # Assigns the associate object, extracts the primary key, and sets it as the foreign key. + # [build_association(attributes = {})] + # Returns a new object of the associated type that has been instantiated + # with +attributes+ and linked to this object through a foreign key, but has not yet been saved. + # [create_association(attributes = {})] + # Returns a new object of the associated type that has been instantiated + # with +attributes+, linked to this object through a foreign key, and that + # has already been saved (if it passed the validation). + # [create_association!(attributes = {})] + # Does the same as create_association, but raises ActiveRecord::RecordInvalid + # if the record is invalid. + # + # === Example + # + # A Post class declares belongs_to :author, which will add: + # * Post#author (similar to Author.find(author_id)) + # * Post#author=(author) (similar to post.author_id = author.id) + # * Post#build_author (similar to post.author = Author.new) + # * Post#create_author (similar to post.author = Author.new; post.author.save; post.author) + # * Post#create_author! (similar to post.author = Author.new; post.author.save!; post.author) + # The declaration can also include an +options+ hash to specialize the behavior of the association. + # + # === Scopes + # + # You can pass a second argument +scope+ as a callable (i.e. proc or + # lambda) to retrieve a specific record or customize the generated query + # when you access the associated object. + # + # Scope examples: + # belongs_to :firm, -> { where(id: 2) } + # belongs_to :user, -> { joins(:friends) } + # belongs_to :level, ->(level) { where("game_level > ?", level.current) } + # + # === Options + # + # [:class_name] + # Specify the class name of the association. Use it only if that name can't be inferred + # from the association name. So belongs_to :author will by default be linked to the Author class, but + # if the real class name is Person, you'll have to specify it with this option. + # [:foreign_key] + # Specify the foreign key used for the association. By default this is guessed to be the name + # of the association with an "_id" suffix. So a class that defines a belongs_to :person + # association will use "person_id" as the default :foreign_key. Similarly, + # belongs_to :favorite_person, class_name: "Person" will use a foreign key + # of "favorite_person_id". + # [:foreign_type] + # Specify the column used to store the associated object's type, if this is a polymorphic + # association. By default this is guessed to be the name of the association with a "_type" + # suffix. So a class that defines a belongs_to :taggable, polymorphic: true + # association will use "taggable_type" as the default :foreign_type. + # [:primary_key] + # Specify the method that returns the primary key of associated object used for the association. + # By default this is id. + # [:dependent] + # If set to :destroy, the associated object is destroyed when this object is. If set to + # :delete, the associated object is deleted *without* calling its destroy method. + # This option should not be specified when #belongs_to is used in conjunction with + # a #has_many relationship on another class because of the potential to leave + # orphaned records behind. + # [:counter_cache] + # Caches the number of belonging objects on the associate class through the use of CounterCache::ClassMethods#increment_counter + # and CounterCache::ClassMethods#decrement_counter. The counter cache is incremented when an object of this + # class is created and decremented when it's destroyed. This requires that a column + # named #{table_name}_count (such as +comments_count+ for a belonging Comment class) + # is used on the associate class (such as a Post class) - that is the migration for + # #{table_name}_count is created on the associate class (such that Post.comments_count will + # return the count cached, see note below). You can also specify a custom counter + # cache column by providing a column name instead of a +true+/+false+ value to this + # option (e.g., counter_cache: :my_custom_counter.) + # Note: Specifying a counter cache will add it to that model's list of readonly attributes + # using +attr_readonly+. + # [:polymorphic] + # Specify this association is a polymorphic association by passing +true+. + # Note: If you've enabled the counter cache, then you may want to add the counter cache attribute + # to the +attr_readonly+ list in the associated classes (e.g. class Post; attr_readonly :comments_count; end). + # [:validate] + # When set to +true+, validates new objects added to association when saving the parent object. +false+ by default. + # If you want to ensure associated objects are revalidated on every update, use +validates_associated+. + # [:autosave] + # If true, always save the associated object or destroy it if marked for destruction, when + # saving the parent object. + # If false, never save or destroy the associated object. + # By default, only save the associated object if it's a new record. + # + # Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for + # sets :autosave to true. + # [:touch] + # If true, the associated object will be touched (the updated_at/on attributes set to current time) + # when this record is either saved or destroyed. If you specify a symbol, that attribute + # will be updated with the current time in addition to the updated_at/on attribute. + # Please note that with touching no validation is performed and only the +after_touch+, + # +after_commit+ and +after_rollback+ callbacks are executed. + # [:inverse_of] + # Specifies the name of the #has_one or #has_many association on the associated + # object that is the inverse of this #belongs_to association. Does not work in + # combination with the :polymorphic options. + # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail. + # [:optional] + # When set to +true+, the association will not have its presence validated. + # [:required] + # When set to +true+, the association will also have its presence validated. + # This will validate the association itself, not the id. You can use + # +:inverse_of+ to avoid an extra query during validation. + # NOTE: required is set to true by default and is deprecated. If + # you don't want to have association presence validated, use optional: true. + # + # Option examples: + # belongs_to :firm, foreign_key: "client_of" + # belongs_to :person, primary_key: "name", foreign_key: "person_name" + # belongs_to :author, class_name: "Person", foreign_key: "author_id" + # belongs_to :valid_coupon, ->(o) { where "discounts > ?", o.payments_count }, + # class_name: "Coupon", foreign_key: "coupon_id" + # belongs_to :attachable, polymorphic: true + # belongs_to :project, -> { readonly } + # belongs_to :post, counter_cache: true + # belongs_to :comment, touch: true + # belongs_to :company, touch: :employees_last_updated_at + # belongs_to :user, optional: true + def belongs_to(name, scope = nil, options = {}) + reflection = Builder::BelongsTo.build(self, name, scope, options) + Reflection.add_reflection self, name, reflection end - habtm_reflection = ActiveRecord::Reflection::HasAndBelongsToManyReflection.new(name, scope, options, self) + # Specifies a many-to-many relationship with another class. This associates two classes via an + # intermediate join table. Unless the join table is explicitly specified as an option, it is + # guessed using the lexical order of the class names. So a join between Developer and Project + # will give the default join table name of "developers_projects" because "D" precedes "P" alphabetically. + # Note that this precedence is calculated using the < operator for String. This + # means that if the strings are of different lengths, and the strings are equal when compared + # up to the shortest length, then the longer string is considered of higher + # lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" + # to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", + # but it in fact generates a join table name of "paper_boxes_papers". Be aware of this caveat, and use the + # custom :join_table option if you need to. + # If your tables share a common prefix, it will only appear once at the beginning. For example, + # the tables "catalog_categories" and "catalog_products" generate a join table name of "catalog_categories_products". + # + # The join table should not have a primary key or a model associated with it. You must manually generate the + # join table with a migration such as this: + # + # class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration[5.0] + # def change + # create_join_table :developers, :projects + # end + # end + # + # It's also a good idea to add indexes to each of those columns to speed up the joins process. + # However, in MySQL it is advised to add a compound index for both of the columns as MySQL only + # uses one index per table during the lookup. + # + # Adds the following methods for retrieval and query: + # + # +collection+ is a placeholder for the symbol passed as the +name+ argument, so + # has_and_belongs_to_many :categories would add among others categories.empty?. + # + # [collection(force_reload = false)] + # Returns an array of all the associated objects. + # An empty array is returned if none are found. + # [collection<<(object, ...)] + # Adds one or more objects to the collection by creating associations in the join table + # (collection.push and collection.concat are aliases to this method). + # Note that this operation instantly fires update SQL without waiting for the save or update call on the + # parent object, unless the parent object is a new record. + # [collection.delete(object, ...)] + # Removes one or more objects from the collection by removing their associations from the join table. + # This does not destroy the objects. + # [collection.destroy(object, ...)] + # Removes one or more objects from the collection by running destroy on each association in the join table, overriding any dependent option. + # This does not destroy the objects. + # [collection=objects] + # Replaces the collection's content by deleting and adding objects as appropriate. + # [collection_singular_ids] + # Returns an array of the associated objects' ids. + # [collection_singular_ids=ids] + # Replace the collection by the objects identified by the primary keys in +ids+. + # [collection.clear] + # Removes every object from the collection. This does not destroy the objects. + # [collection.empty?] + # Returns +true+ if there are no associated objects. + # [collection.size] + # Returns the number of associated objects. + # [collection.find(id)] + # Finds an associated object responding to the +id+ and that + # meets the condition that it has to be associated with this object. + # Uses the same rules as ActiveRecord::FinderMethods#find. + # [collection.exists?(...)] + # Checks whether an associated object with the given conditions exists. + # Uses the same rules as ActiveRecord::FinderMethods#exists?. + # [collection.build(attributes = {})] + # Returns a new object of the collection type that has been instantiated + # with +attributes+ and linked to this object through the join table, but has not yet been saved. + # [collection.create(attributes = {})] + # Returns a new object of the collection type that has been instantiated + # with +attributes+, linked to this object through the join table, and that has already been + # saved (if it passed the validation). + # + # === Example + # + # A Developer class declares has_and_belongs_to_many :projects, which will add: + # * Developer#projects + # * Developer#projects<< + # * Developer#projects.delete + # * Developer#projects.destroy + # * Developer#projects= + # * Developer#project_ids + # * Developer#project_ids= + # * Developer#projects.clear + # * Developer#projects.empty? + # * Developer#projects.size + # * Developer#projects.find(id) + # * Developer#projects.exists?(...) + # * Developer#projects.build (similar to Project.new("developer_id" => id)) + # * Developer#projects.create (similar to c = Project.new("developer_id" => id); c.save; c) + # The declaration may include an +options+ hash to specialize the behavior of the association. + # + # === Scopes + # + # You can pass a second argument +scope+ as a callable (i.e. proc or + # lambda) to retrieve a specific set of records or customize the generated + # query when you access the associated collection. + # + # Scope examples: + # has_and_belongs_to_many :projects, -> { includes(:milestones, :manager) } + # has_and_belongs_to_many :categories, ->(category) { + # where("default_category = ?", category.name) + # } + # + # === Extensions + # + # The +extension+ argument allows you to pass a block into a + # has_and_belongs_to_many association. This is useful for adding new + # finders, creators and other factory-type methods to be used as part of + # the association. + # + # Extension examples: + # has_and_belongs_to_many :contractors do + # def find_or_create_by_name(name) + # first_name, last_name = name.split(" ", 2) + # find_or_create_by(first_name: first_name, last_name: last_name) + # end + # end + # + # === Options + # + # [:class_name] + # Specify the class name of the association. Use it only if that name can't be inferred + # from the association name. So has_and_belongs_to_many :projects will by default be linked to the + # Project class, but if the real class name is SuperProject, you'll have to specify it with this option. + # [:join_table] + # Specify the name of the join table if the default based on lexical order isn't what you want. + # WARNING: If you're overwriting the table name of either class, the +table_name+ method + # MUST be declared underneath any #has_and_belongs_to_many declaration in order to work. + # [:foreign_key] + # Specify the foreign key used for the association. By default this is guessed to be the name + # of this class in lower-case and "_id" suffixed. So a Person class that makes + # a #has_and_belongs_to_many association to Project will use "person_id" as the + # default :foreign_key. + # [:association_foreign_key] + # Specify the foreign key used for the association on the receiving side of the association. + # By default this is guessed to be the name of the associated class in lower-case and "_id" suffixed. + # So if a Person class makes a #has_and_belongs_to_many association to Project, + # the association will use "project_id" as the default :association_foreign_key. + # [:validate] + # When set to +true+, validates new objects added to association when saving the parent object. +true+ by default. + # If you want to ensure associated objects are revalidated on every update, use +validates_associated+. + # [:autosave] + # If true, always save the associated objects or destroy them if marked for destruction, when + # saving the parent object. + # If false, never save or destroy the associated objects. + # By default, only save associated objects that are new records. + # + # Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for sets + # :autosave to true. + # + # Option examples: + # has_and_belongs_to_many :projects + # has_and_belongs_to_many :projects, -> { includes(:milestones, :manager) } + # has_and_belongs_to_many :nations, class_name: "Country" + # has_and_belongs_to_many :categories, join_table: "prods_cats" + # has_and_belongs_to_many :categories, -> { readonly } + def has_and_belongs_to_many(name, scope = nil, options = {}, &extension) + if scope.is_a?(Hash) + options = scope + scope = nil + end + + habtm_reflection = ActiveRecord::Reflection::HasAndBelongsToManyReflection.new(name, scope, options, self) - builder = Builder::HasAndBelongsToMany.new name, self, options + builder = Builder::HasAndBelongsToMany.new name, self, options - join_model = builder.through_model + join_model = builder.through_model - const_set join_model.name, join_model - private_constant join_model.name + const_set join_model.name, join_model + private_constant join_model.name - middle_reflection = builder.middle_reflection join_model + middle_reflection = builder.middle_reflection join_model - Builder::HasMany.define_callbacks self, middle_reflection - Reflection.add_reflection self, middle_reflection.name, middle_reflection - middle_reflection.parent_reflection = habtm_reflection + Builder::HasMany.define_callbacks self, middle_reflection + Reflection.add_reflection self, middle_reflection.name, middle_reflection + middle_reflection.parent_reflection = habtm_reflection - include Module.new { - class_eval <<-RUBY, __FILE__, __LINE__ + 1 + include Module.new { + class_eval <<-RUBY, __FILE__, __LINE__ + 1 def destroy_associations association(:#{middle_reflection.name}).delete_all(:delete_all) association(:#{name}).reset super end RUBY - } + } - hm_options = {} - hm_options[:through] = middle_reflection.name - hm_options[:source] = join_model.right_reflection.name + hm_options = {} + hm_options[:through] = middle_reflection.name + hm_options[:source] = join_model.right_reflection.name - [:before_add, :after_add, :before_remove, :after_remove, :autosave, :validate, :join_table, :class_name, :extend].each do |k| - hm_options[k] = options[k] if options.key? k - end + [:before_add, :after_add, :before_remove, :after_remove, :autosave, :validate, :join_table, :class_name, :extend].each do |k| + hm_options[k] = options[k] if options.key? k + end - has_many name, scope, hm_options, &extension - self._reflections[name.to_s].parent_reflection = habtm_reflection + has_many name, scope, hm_options, &extension + self._reflections[name.to_s].parent_reflection = habtm_reflection + end end - end end end diff --git a/activerecord/lib/active_record/associations/association_scope.rb b/activerecord/lib/active_record/associations/association_scope.rb index 15844de0bc..12f8c1ccd4 100644 --- a/activerecord/lib/active_record/associations/association_scope.rb +++ b/activerecord/lib/active_record/associations/association_scope.rb @@ -51,115 +51,115 @@ module ActiveRecord protected - attr_reader :value_transformation + attr_reader :value_transformation private - def join(table, constraint) - table.create_join(table, table.create_on(constraint), join_type) - end + def join(table, constraint) + table.create_join(table, table.create_on(constraint), join_type) + end + + def last_chain_scope(scope, table, reflection, owner, association_klass) + join_keys = reflection.join_keys(association_klass) + key = join_keys.key + foreign_key = join_keys.foreign_key - def last_chain_scope(scope, table, reflection, owner, association_klass) - join_keys = reflection.join_keys(association_klass) - key = join_keys.key - foreign_key = join_keys.foreign_key + value = transform_value(owner[foreign_key]) + scope = scope.where(table.name => { key => value }) - value = transform_value(owner[foreign_key]) - scope = scope.where(table.name => { key => value }) + if reflection.type + polymorphic_type = transform_value(owner.class.base_class.name) + scope = scope.where(table.name => { reflection.type => polymorphic_type }) + end - if reflection.type - polymorphic_type = transform_value(owner.class.base_class.name) - scope = scope.where(table.name => { reflection.type => polymorphic_type }) + scope end - scope - end + def transform_value(value) + value_transformation.call(value) + end - def transform_value(value) - value_transformation.call(value) - end + def next_chain_scope(scope, table, reflection, association_klass, foreign_table, next_reflection) + join_keys = reflection.join_keys(association_klass) + key = join_keys.key + foreign_key = join_keys.foreign_key - def next_chain_scope(scope, table, reflection, association_klass, foreign_table, next_reflection) - join_keys = reflection.join_keys(association_klass) - key = join_keys.key - foreign_key = join_keys.foreign_key + constraint = table[key].eq(foreign_table[foreign_key]) - constraint = table[key].eq(foreign_table[foreign_key]) + if reflection.type + value = transform_value(next_reflection.klass.base_class.name) + scope = scope.where(table.name => { reflection.type => value }) + end - if reflection.type - value = transform_value(next_reflection.klass.base_class.name) - scope = scope.where(table.name => { reflection.type => value }) + scope = scope.joins(join(foreign_table, constraint)) end - scope = scope.joins(join(foreign_table, constraint)) - end + class ReflectionProxy < SimpleDelegator # :nodoc: + attr_accessor :next + attr_reader :alias_name - class ReflectionProxy < SimpleDelegator # :nodoc: - attr_accessor :next - attr_reader :alias_name + def initialize(reflection, alias_name) + super(reflection) + @alias_name = alias_name + end - def initialize(reflection, alias_name) - super(reflection) - @alias_name = alias_name + def all_includes; nil; end end - def all_includes; nil; end - end - - def get_chain(reflection, association, tracker) - name = reflection.name - runtime_reflection = Reflection::RuntimeReflection.new(reflection, association) - previous_reflection = runtime_reflection - reflection.chain.drop(1).each do |refl| - alias_name = tracker.aliased_table_for(refl.table_name, refl.alias_candidate(name)) - proxy = ReflectionProxy.new(refl, alias_name) - previous_reflection.next = proxy - previous_reflection = proxy + def get_chain(reflection, association, tracker) + name = reflection.name + runtime_reflection = Reflection::RuntimeReflection.new(reflection, association) + previous_reflection = runtime_reflection + reflection.chain.drop(1).each do |refl| + alias_name = tracker.aliased_table_for(refl.table_name, refl.alias_candidate(name)) + proxy = ReflectionProxy.new(refl, alias_name) + previous_reflection.next = proxy + previous_reflection = proxy + end + [runtime_reflection, previous_reflection] end - [runtime_reflection, previous_reflection] - end - def add_constraints(scope, owner, association_klass, refl, chain_head, chain_tail) - owner_reflection = chain_tail - table = owner_reflection.alias_name - scope = last_chain_scope(scope, table, owner_reflection, owner, association_klass) + def add_constraints(scope, owner, association_klass, refl, chain_head, chain_tail) + owner_reflection = chain_tail + table = owner_reflection.alias_name + scope = last_chain_scope(scope, table, owner_reflection, owner, association_klass) - reflection = chain_head - while reflection - table = reflection.alias_name + reflection = chain_head + while reflection + table = reflection.alias_name - unless reflection == chain_tail - next_reflection = reflection.next - foreign_table = next_reflection.alias_name - scope = next_chain_scope(scope, table, reflection, association_klass, foreign_table, next_reflection) - end + unless reflection == chain_tail + next_reflection = reflection.next + foreign_table = next_reflection.alias_name + scope = next_chain_scope(scope, table, reflection, association_klass, foreign_table, next_reflection) + end - # Exclude the scope of the association itself, because that - # was already merged in the #scope method. - reflection.constraints.each do |scope_chain_item| - item = eval_scope(reflection.klass, scope_chain_item, owner) + # Exclude the scope of the association itself, because that + # was already merged in the #scope method. + reflection.constraints.each do |scope_chain_item| + item = eval_scope(reflection.klass, scope_chain_item, owner) - if scope_chain_item == refl.scope - scope.merge! item.except(:where, :includes) - end + if scope_chain_item == refl.scope + scope.merge! item.except(:where, :includes) + end + + reflection.all_includes do + scope.includes! item.includes_values + end - reflection.all_includes do - scope.includes! item.includes_values + scope.unscope!(*item.unscope_values) + scope.where_clause += item.where_clause + scope.order_values |= item.order_values end - scope.unscope!(*item.unscope_values) - scope.where_clause += item.where_clause - scope.order_values |= item.order_values + reflection = reflection.next end - reflection = reflection.next + scope end - scope - end - - def eval_scope(klass, scope, owner) - klass.unscoped.instance_exec(owner, &scope) - end + def eval_scope(klass, scope, owner) + klass.unscoped.instance_exec(owner, &scope) + end end end end diff --git a/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb b/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb index 33c8d4b8d6..047292b2bd 100644 --- a/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb +++ b/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb @@ -16,9 +16,9 @@ module ActiveRecord::Associations::Builder # :nodoc: private - def klass - @lhs_class.send(:compute_type, @rhs_class_name) - end + def klass + @lhs_class.send(:compute_type, @rhs_class_name) + end end def self.build(lhs_class, name, options) @@ -105,29 +105,29 @@ module ActiveRecord::Associations::Builder # :nodoc: private - def middle_options(join_model) - middle_options = {} - middle_options[:class_name] = "#{lhs_model.name}::#{join_model.name}" - middle_options[:source] = join_model.left_reflection.name - if options.key? :foreign_key - middle_options[:foreign_key] = options[:foreign_key] + def middle_options(join_model) + middle_options = {} + middle_options[:class_name] = "#{lhs_model.name}::#{join_model.name}" + middle_options[:source] = join_model.left_reflection.name + if options.key? :foreign_key + middle_options[:foreign_key] = options[:foreign_key] + end + middle_options end - middle_options - end - def belongs_to_options(options) - rhs_options = {} + def belongs_to_options(options) + rhs_options = {} - if options.key? :class_name - rhs_options[:foreign_key] = options[:class_name].to_s.foreign_key - rhs_options[:class_name] = options[:class_name] - end + if options.key? :class_name + rhs_options[:foreign_key] = options[:class_name].to_s.foreign_key + rhs_options[:class_name] = options[:class_name] + end - if options.key? :association_foreign_key - rhs_options[:foreign_key] = options[:association_foreign_key] - end + if options.key? :association_foreign_key + rhs_options[:foreign_key] = options[:association_foreign_key] + end - rhs_options - end + rhs_options + end end end diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index c8805d107b..7d106015d7 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -221,7 +221,7 @@ module ActiveRecord end dependent = if dependent - dependent + dependent elsif options[:dependent] == :destroy :delete_all else diff --git a/activerecord/lib/active_record/associations/join_dependency.rb b/activerecord/lib/active_record/associations/join_dependency.rb index 0f9ad77405..3946d5baa4 100644 --- a/activerecord/lib/active_record/associations/join_dependency.rb +++ b/activerecord/lib/active_record/associations/join_dependency.rb @@ -167,134 +167,134 @@ module ActiveRecord private - def make_constraints(parent, child, tables, join_type) - chain = child.reflection.chain - foreign_table = parent.table - foreign_klass = parent.base_klass - child.join_constraints(foreign_table, foreign_klass, child, join_type, tables, child.reflection.scope_chain, chain) - end - - def make_outer_joins(parent, child) - tables = table_aliases_for(parent, child) - join_type = Arel::Nodes::OuterJoin - info = make_constraints parent, child, tables, join_type - - [info] + child.children.flat_map { |c| make_outer_joins(child, c) } - end + def make_constraints(parent, child, tables, join_type) + chain = child.reflection.chain + foreign_table = parent.table + foreign_klass = parent.base_klass + child.join_constraints(foreign_table, foreign_klass, child, join_type, tables, child.reflection.scope_chain, chain) + end - def make_left_outer_joins(parent, child) - tables = child.tables - join_type = Arel::Nodes::OuterJoin - info = make_constraints parent, child, tables, join_type + def make_outer_joins(parent, child) + tables = table_aliases_for(parent, child) + join_type = Arel::Nodes::OuterJoin + info = make_constraints parent, child, tables, join_type - [info] + child.children.flat_map { |c| make_left_outer_joins(child, c) } - end + [info] + child.children.flat_map { |c| make_outer_joins(child, c) } + end - def make_inner_joins(parent, child) - tables = child.tables - join_type = Arel::Nodes::InnerJoin - info = make_constraints parent, child, tables, join_type + def make_left_outer_joins(parent, child) + tables = child.tables + join_type = Arel::Nodes::OuterJoin + info = make_constraints parent, child, tables, join_type - [info] + child.children.flat_map { |c| make_inner_joins(child, c) } - end + [info] + child.children.flat_map { |c| make_left_outer_joins(child, c) } + end - def table_aliases_for(parent, node) - node.reflection.chain.map { |reflection| - alias_tracker.aliased_table_for( - reflection.table_name, - table_alias_for(reflection, parent, reflection != node.reflection) - ) - } - end + def make_inner_joins(parent, child) + tables = child.tables + join_type = Arel::Nodes::InnerJoin + info = make_constraints parent, child, tables, join_type - def construct_tables!(parent, node) - node.tables = table_aliases_for(parent, node) - node.children.each { |child| construct_tables! node, child } - end + [info] + child.children.flat_map { |c| make_inner_joins(child, c) } + end - def table_alias_for(reflection, parent, join) - name = "#{reflection.plural_name}_#{parent.table_name}" - name << "_join" if join - name - end + def table_aliases_for(parent, node) + node.reflection.chain.map { |reflection| + alias_tracker.aliased_table_for( + reflection.table_name, + table_alias_for(reflection, parent, reflection != node.reflection) + ) + } + end - def walk(left, right) - intersection, missing = right.children.map { |node1| - [left.children.find { |node2| node1.match? node2 }, node1] - }.partition(&:first) + def construct_tables!(parent, node) + node.tables = table_aliases_for(parent, node) + node.children.each { |child| construct_tables! node, child } + end - ojs = missing.flat_map { |_,n| make_outer_joins left, n } - intersection.flat_map { |l,r| walk l, r }.concat ojs - end + def table_alias_for(reflection, parent, join) + name = "#{reflection.plural_name}_#{parent.table_name}" + name << "_join" if join + name + end - def find_reflection(klass, name) - klass._reflect_on_association(name) or - raise ConfigurationError, "Can't join '#{ klass.name }' to association named '#{ name }'; perhaps you misspelled it?" - end + def walk(left, right) + intersection, missing = right.children.map { |node1| + [left.children.find { |node2| node1.match? node2 }, node1] + }.partition(&:first) - def build(associations, base_klass) - associations.map do |name, right| - reflection = find_reflection base_klass, name - reflection.check_validity! - reflection.check_eager_loadable! + ojs = missing.flat_map { |_,n| make_outer_joins left, n } + intersection.flat_map { |l,r| walk l, r }.concat ojs + end - if reflection.polymorphic? - next unless @eager_loading - raise EagerLoadPolymorphicError.new(reflection) - end + def find_reflection(klass, name) + klass._reflect_on_association(name) or + raise ConfigurationError, "Can't join '#{ klass.name }' to association named '#{ name }'; perhaps you misspelled it?" + end - JoinAssociation.new reflection, build(right, reflection.klass) - end.compact - end + def build(associations, base_klass) + associations.map do |name, right| + reflection = find_reflection base_klass, name + reflection.check_validity! + reflection.check_eager_loadable! - def construct(ar_parent, parent, row, rs, seen, model_cache, aliases) - return if ar_parent.nil? + if reflection.polymorphic? + next unless @eager_loading + raise EagerLoadPolymorphicError.new(reflection) + end - parent.children.each do |node| - if node.reflection.collection? - other = ar_parent.association(node.reflection.name) - other.loaded! - elsif ar_parent.association_cached?(node.reflection.name) - model = ar_parent.association(node.reflection.name).target - construct(model, node, row, rs, seen, model_cache, aliases) - next - end + JoinAssociation.new reflection, build(right, reflection.klass) + end.compact + end - key = aliases.column_alias(node, node.primary_key) - id = row[key] - if id.nil? - nil_association = ar_parent.association(node.reflection.name) - nil_association.loaded! - next + def construct(ar_parent, parent, row, rs, seen, model_cache, aliases) + return if ar_parent.nil? + + parent.children.each do |node| + if node.reflection.collection? + other = ar_parent.association(node.reflection.name) + other.loaded! + elsif ar_parent.association_cached?(node.reflection.name) + model = ar_parent.association(node.reflection.name).target + construct(model, node, row, rs, seen, model_cache, aliases) + next + end + + key = aliases.column_alias(node, node.primary_key) + id = row[key] + if id.nil? + nil_association = ar_parent.association(node.reflection.name) + nil_association.loaded! + next + end + + model = seen[ar_parent.object_id][node.base_klass][id] + + if model + construct(model, node, row, rs, seen, model_cache, aliases) + else + model = construct_model(ar_parent, node, row, model_cache, id, aliases) + model.readonly! + seen[ar_parent.object_id][node.base_klass][id] = model + construct(model, node, row, rs, seen, model_cache, aliases) + end end + end - model = seen[ar_parent.object_id][node.base_klass][id] + def construct_model(record, node, row, model_cache, id, aliases) + model = model_cache[node][id] ||= node.instantiate(row, + aliases.column_aliases(node)) + other = record.association(node.reflection.name) - if model - construct(model, node, row, rs, seen, model_cache, aliases) + if node.reflection.collection? + other.target.push(model) else - model = construct_model(ar_parent, node, row, model_cache, id, aliases) - model.readonly! - seen[ar_parent.object_id][node.base_klass][id] = model - construct(model, node, row, rs, seen, model_cache, aliases) + other.target = model end - end - end - def construct_model(record, node, row, model_cache, id, aliases) - model = model_cache[node][id] ||= node.instantiate(row, - aliases.column_aliases(node)) - other = record.association(node.reflection.name) - - if node.reflection.collection? - other.target.push(model) - else - other.target = model + other.set_inverse_instance(model) + model end - - other.set_inverse_instance(model) - model - end end end end diff --git a/activerecord/lib/active_record/associations/preloader.rb b/activerecord/lib/active_record/associations/preloader.rb index 320d9dc952..a81860e40f 100644 --- a/activerecord/lib/active_record/associations/preloader.rb +++ b/activerecord/lib/active_record/associations/preloader.rb @@ -107,30 +107,30 @@ module ActiveRecord private # Loads all the given data into +records+ for the +association+. - def preloaders_on(association, records, scope) - case association - when Hash - preloaders_for_hash(association, records, scope) - when Symbol - preloaders_for_one(association, records, scope) - when String - preloaders_for_one(association.to_sym, records, scope) - else - raise ArgumentError, "#{association.inspect} was not recognized for preload" + def preloaders_on(association, records, scope) + case association + when Hash + preloaders_for_hash(association, records, scope) + when Symbol + preloaders_for_one(association, records, scope) + when String + preloaders_for_one(association.to_sym, records, scope) + else + raise ArgumentError, "#{association.inspect} was not recognized for preload" + end end - end - def preloaders_for_hash(association, records, scope) - association.flat_map { |parent, child| - loaders = preloaders_for_one parent, records, scope + def preloaders_for_hash(association, records, scope) + association.flat_map { |parent, child| + loaders = preloaders_for_one parent, records, scope - recs = loaders.flat_map(&:preloaded_records).uniq - loaders.concat Array.wrap(child).flat_map { |assoc| - preloaders_on assoc, recs, scope + recs = loaders.flat_map(&:preloaded_records).uniq + loaders.concat Array.wrap(child).flat_map { |assoc| + preloaders_on assoc, recs, scope + } + loaders } - loaders - } - end + end # Loads all the given data into +records+ for a singular +association+. # @@ -144,70 +144,70 @@ module ActiveRecord # Additionally, polymorphic belongs_to associations can have multiple associated # classes, depending on the polymorphic_type field. So we group by the classes as # well. - def preloaders_for_one(association, records, scope) - grouped_records(association, records).flat_map do |reflection, klasses| - klasses.map do |rhs_klass, rs| - loader = preloader_for(reflection, rs, rhs_klass).new(rhs_klass, rs, reflection, scope) - loader.run self - loader + def preloaders_for_one(association, records, scope) + grouped_records(association, records).flat_map do |reflection, klasses| + klasses.map do |rhs_klass, rs| + loader = preloader_for(reflection, rs, rhs_klass).new(rhs_klass, rs, reflection, scope) + loader.run self + loader + end end end - end - def grouped_records(association, records) - h = {} - records.each do |record| - next unless record - assoc = record.association(association) - klasses = h[assoc.reflection] ||= {} - (klasses[assoc.klass] ||= []) << record + def grouped_records(association, records) + h = {} + records.each do |record| + next unless record + assoc = record.association(association) + klasses = h[assoc.reflection] ||= {} + (klasses[assoc.klass] ||= []) << record + end + h end - h - end - class AlreadyLoaded # :nodoc: - attr_reader :owners, :reflection + class AlreadyLoaded # :nodoc: + attr_reader :owners, :reflection - def initialize(klass, owners, reflection, preload_scope) - @owners = owners - @reflection = reflection - end + def initialize(klass, owners, reflection, preload_scope) + @owners = owners + @reflection = reflection + end - def run(preloader); end + def run(preloader); end - def preloaded_records - owners.flat_map { |owner| owner.association(reflection.name).target } + def preloaded_records + owners.flat_map { |owner| owner.association(reflection.name).target } + end end - end - class NullPreloader # :nodoc: - def self.new(klass, owners, reflection, preload_scope); self; end - def self.run(preloader); end - def self.preloaded_records; []; end - def self.owners; []; end - end + class NullPreloader # :nodoc: + def self.new(klass, owners, reflection, preload_scope); self; end + def self.run(preloader); end + def self.preloaded_records; []; end + def self.owners; []; end + end # Returns a class containing the logic needed to load preload the data # and attach it to a relation. For example +Preloader::Association+ or # +Preloader::HasManyThrough+. The class returned implements a `run` method # that accepts a preloader. - def preloader_for(reflection, owners, rhs_klass) - return NullPreloader unless rhs_klass + def preloader_for(reflection, owners, rhs_klass) + return NullPreloader unless rhs_klass - if owners.first.association(reflection.name).loaded? - return AlreadyLoaded - end - reflection.check_preloadable! - - case reflection.macro - when :has_many - reflection.options[:through] ? HasManyThrough : HasMany - when :has_one - reflection.options[:through] ? HasOneThrough : HasOne - when :belongs_to - BelongsTo + if owners.first.association(reflection.name).loaded? + return AlreadyLoaded + end + reflection.check_preloadable! + + case reflection.macro + when :has_many + reflection.options[:through] ? HasManyThrough : HasMany + when :has_one + reflection.options[:through] ? HasOneThrough : HasOne + when :belongs_to + BelongsTo + end end - end end end end diff --git a/activerecord/lib/active_record/associations/preloader/association.rb b/activerecord/lib/active_record/associations/preloader/association.rb index 3032bc786e..a8afa48865 100644 --- a/activerecord/lib/active_record/associations/preloader/association.rb +++ b/activerecord/lib/active_record/associations/preloader/association.rb @@ -61,99 +61,99 @@ module ActiveRecord private - def associated_records_by_owner(preloader) - records = load_records - owners.each_with_object({}) do |owner, result| - result[owner] = records[convert_key(owner[owner_key_name])] || [] + def associated_records_by_owner(preloader) + records = load_records + owners.each_with_object({}) do |owner, result| + result[owner] = records[convert_key(owner[owner_key_name])] || [] + end end - end - def owner_keys - unless defined?(@owner_keys) - @owner_keys = owners.map do |owner| - owner[owner_key_name] + def owner_keys + unless defined?(@owner_keys) + @owner_keys = owners.map do |owner| + owner[owner_key_name] + end + @owner_keys.uniq! + @owner_keys.compact! end - @owner_keys.uniq! - @owner_keys.compact! + @owner_keys end - @owner_keys - end - def key_conversion_required? - @key_conversion_required ||= association_key_type != owner_key_type - end + def key_conversion_required? + @key_conversion_required ||= association_key_type != owner_key_type + end - def convert_key(key) - if key_conversion_required? - key.to_s - else - key + def convert_key(key) + if key_conversion_required? + key.to_s + else + key + end end - end - def association_key_type - @klass.type_for_attribute(association_key_name.to_s).type - end + def association_key_type + @klass.type_for_attribute(association_key_name.to_s).type + end - def owner_key_type - @model.type_for_attribute(owner_key_name.to_s).type - end + def owner_key_type + @model.type_for_attribute(owner_key_name.to_s).type + end - def load_records - return {} if owner_keys.empty? - # Some databases impose a limit on the number of ids in a list (in Oracle it's 1000) - # Make several smaller queries if necessary or make one query if the adapter supports it - slices = owner_keys.each_slice(klass.connection.in_clause_length || owner_keys.size) - @preloaded_records = slices.flat_map do |slice| - records_for(slice) + def load_records + return {} if owner_keys.empty? + # Some databases impose a limit on the number of ids in a list (in Oracle it's 1000) + # Make several smaller queries if necessary or make one query if the adapter supports it + slices = owner_keys.each_slice(klass.connection.in_clause_length || owner_keys.size) + @preloaded_records = slices.flat_map do |slice| + records_for(slice) + end + @preloaded_records.group_by do |record| + convert_key(record[association_key_name]) + end end - @preloaded_records.group_by do |record| - convert_key(record[association_key_name]) + + def reflection_scope + @reflection_scope ||= reflection.scope ? klass.unscoped.instance_exec(nil, &reflection.scope) : klass.unscoped end - end - def reflection_scope - @reflection_scope ||= reflection.scope ? klass.unscoped.instance_exec(nil, &reflection.scope) : klass.unscoped - end + def build_scope + scope = klass.unscoped - def build_scope - scope = klass.unscoped + values = reflection_scope.values + preload_values = preload_scope.values - values = reflection_scope.values - preload_values = preload_scope.values + scope.where_clause = reflection_scope.where_clause + preload_scope.where_clause + scope.references_values = Array(values[:references]) + Array(preload_values[:references]) - scope.where_clause = reflection_scope.where_clause + preload_scope.where_clause - scope.references_values = Array(values[:references]) + Array(preload_values[:references]) + if preload_values[:select] || values[:select] + scope._select!(preload_values[:select] || values[:select]) + end + scope.includes! preload_values[:includes] || values[:includes] + if preload_scope.joins_values.any? + scope.joins!(preload_scope.joins_values) + else + scope.joins!(reflection_scope.joins_values) + end - if preload_values[:select] || values[:select] - scope._select!(preload_values[:select] || values[:select]) - end - scope.includes! preload_values[:includes] || values[:includes] - if preload_scope.joins_values.any? - scope.joins!(preload_scope.joins_values) - else - scope.joins!(reflection_scope.joins_values) - end + if order_values = preload_values[:order] || values[:order] + scope.order!(order_values) + end - if order_values = preload_values[:order] || values[:order] - scope.order!(order_values) - end + if preload_values[:reordering] || values[:reordering] + scope.reordering_value = true + end - if preload_values[:reordering] || values[:reordering] - scope.reordering_value = true - end + if preload_values[:readonly] || values[:readonly] + scope.readonly! + end - if preload_values[:readonly] || values[:readonly] - scope.readonly! - end + if options[:as] + scope.where!(klass.table_name => { reflection.type => model.base_class.sti_name }) + end - if options[:as] - scope.where!(klass.table_name => { reflection.type => model.base_class.sti_name }) + scope.unscope_values = Array(values[:unscope]) + Array(preload_values[:unscope]) + klass.default_scoped.merge(scope) end - - scope.unscope_values = Array(values[:unscope]) + Array(preload_values[:unscope]) - klass.default_scoped.merge(scope) - end end end end diff --git a/activerecord/lib/active_record/associations/preloader/collection_association.rb b/activerecord/lib/active_record/associations/preloader/collection_association.rb index 9939280fa4..24b8e01029 100644 --- a/activerecord/lib/active_record/associations/preloader/collection_association.rb +++ b/activerecord/lib/active_record/associations/preloader/collection_association.rb @@ -4,14 +4,14 @@ module ActiveRecord class CollectionAssociation < Association #:nodoc: private - def preload(preloader) - associated_records_by_owner(preloader).each do |owner, records| - association = owner.association(reflection.name) - association.loaded! - association.target.concat(records) - records.each { |record| association.set_inverse_instance(record) } + def preload(preloader) + associated_records_by_owner(preloader).each do |owner, records| + association = owner.association(reflection.name) + association.loaded! + association.target.concat(records) + records.each { |record| association.set_inverse_instance(record) } + end end - end end end end diff --git a/activerecord/lib/active_record/associations/preloader/singular_association.rb b/activerecord/lib/active_record/associations/preloader/singular_association.rb index f60647a81e..9f8d98c5a5 100644 --- a/activerecord/lib/active_record/associations/preloader/singular_association.rb +++ b/activerecord/lib/active_record/associations/preloader/singular_association.rb @@ -5,15 +5,15 @@ module ActiveRecord private - def preload(preloader) - associated_records_by_owner(preloader).each do |owner, associated_records| - record = associated_records.first + def preload(preloader) + associated_records_by_owner(preloader).each do |owner, associated_records| + record = associated_records.first - association = owner.association(reflection.name) - association.target = record - association.set_inverse_instance(record) if record + association = owner.association(reflection.name) + association.target = record + association.set_inverse_instance(record) if record + end end - end end end diff --git a/activerecord/lib/active_record/associations/preloader/through_association.rb b/activerecord/lib/active_record/associations/preloader/through_association.rb index b0203909ce..f53c30f80e 100644 --- a/activerecord/lib/active_record/associations/preloader/through_association.rb +++ b/activerecord/lib/active_record/associations/preloader/through_association.rb @@ -61,48 +61,48 @@ module ActiveRecord private - def id_to_index_map(ids) - id_map = {} - ids.each_with_index { |id, index| id_map[id] = index } - id_map - end + def id_to_index_map(ids) + id_map = {} + ids.each_with_index { |id, index| id_map[id] = index } + id_map + end - def reset_association(owners, association_name) - should_reset = (through_scope != through_reflection.klass.unscoped) || - (reflection.options[:source_type] && through_reflection.collection?) + def reset_association(owners, association_name) + should_reset = (through_scope != through_reflection.klass.unscoped) || + (reflection.options[:source_type] && through_reflection.collection?) - # Don't cache the association - we would only be caching a subset - if should_reset - owners.each { |owner| - owner.association(association_name).reset - } + # Don't cache the association - we would only be caching a subset + if should_reset + owners.each { |owner| + owner.association(association_name).reset + } + end end - end - def through_scope - scope = through_reflection.klass.unscoped + def through_scope + scope = through_reflection.klass.unscoped - if options[:source_type] - scope.where! reflection.foreign_type => options[:source_type] - else - unless reflection_scope.where_clause.empty? - scope.includes_values = Array(reflection_scope.values[:includes] || options[:source]) - scope.where_clause = reflection_scope.where_clause - end + if options[:source_type] + scope.where! reflection.foreign_type => options[:source_type] + else + unless reflection_scope.where_clause.empty? + scope.includes_values = Array(reflection_scope.values[:includes] || options[:source]) + scope.where_clause = reflection_scope.where_clause + end - scope.references! reflection_scope.values[:references] - if scope.eager_loading? && order_values = reflection_scope.values[:order] - scope = scope.order(order_values) + scope.references! reflection_scope.values[:references] + if scope.eager_loading? && order_values = reflection_scope.values[:order] + scope = scope.order(order_values) + end end - end - scope - end + scope + end - def target_records_from_association(association) - association.loaded? ? association.target : association.reader - end + def target_records_from_association(association) + association.loaded? ? association.target : association.reader + end end end end diff --git a/activerecord/lib/active_record/attribute.rb b/activerecord/lib/active_record/attribute.rb index 2f41e9e45b..95b3adae5f 100644 --- a/activerecord/lib/active_record/attribute.rb +++ b/activerecord/lib/active_record/attribute.rb @@ -130,108 +130,108 @@ module ActiveRecord protected - attr_reader :original_attribute - alias_method :assigned?, :original_attribute + attr_reader :original_attribute + alias_method :assigned?, :original_attribute - def initialize_dup(other) - if defined?(@value) && @value.duplicable? - @value = @value.dup + def initialize_dup(other) + if defined?(@value) && @value.duplicable? + @value = @value.dup + end end - end - - def changed_from_assignment? - assigned? && type.changed?(original_value, value, value_before_type_cast) - end - def original_value_for_database - if assigned? - original_attribute.original_value_for_database - else - _original_value_for_database + def changed_from_assignment? + assigned? && type.changed?(original_value, value, value_before_type_cast) end - end - - def _original_value_for_database - type.serialize(original_value) - end - class FromDatabase < Attribute # :nodoc: - def type_cast(value) - type.deserialize(value) + def original_value_for_database + if assigned? + original_attribute.original_value_for_database + else + _original_value_for_database + end end def _original_value_for_database - value_before_type_cast + type.serialize(original_value) end - end - class FromUser < Attribute # :nodoc: - def type_cast(value) - type.cast(value) - end + class FromDatabase < Attribute # :nodoc: + def type_cast(value) + type.deserialize(value) + end - def came_from_user? - true + def _original_value_for_database + value_before_type_cast + end end - end - class WithCastValue < Attribute # :nodoc: - def type_cast(value) - value - end + class FromUser < Attribute # :nodoc: + def type_cast(value) + type.cast(value) + end - def changed_in_place? - false + def came_from_user? + true + end end - end - class Null < Attribute # :nodoc: - def initialize(name) - super(name, nil, Type::Value.new) - end + class WithCastValue < Attribute # :nodoc: + def type_cast(value) + value + end - def type_cast(*) - nil + def changed_in_place? + false + end end - def with_type(type) - self.class.with_cast_value(name, nil, type) - end + class Null < Attribute # :nodoc: + def initialize(name) + super(name, nil, Type::Value.new) + end - def with_value_from_database(value) - raise ActiveModel::MissingAttributeError, "can't write unknown attribute `#{name}`" - end - alias_method :with_value_from_user, :with_value_from_database - end + def type_cast(*) + nil + end - class Uninitialized < Attribute # :nodoc: - UNINITIALIZED_ORIGINAL_VALUE = Object.new + def with_type(type) + self.class.with_cast_value(name, nil, type) + end - def initialize(name, type) - super(name, nil, type) + def with_value_from_database(value) + raise ActiveModel::MissingAttributeError, "can't write unknown attribute `#{name}`" + end + alias_method :with_value_from_user, :with_value_from_database end - def value - if block_given? - yield name + class Uninitialized < Attribute # :nodoc: + UNINITIALIZED_ORIGINAL_VALUE = Object.new + + def initialize(name, type) + super(name, nil, type) end - end - def original_value - UNINITIALIZED_ORIGINAL_VALUE - end + def value + if block_given? + yield name + end + end - def value_for_database - end + def original_value + UNINITIALIZED_ORIGINAL_VALUE + end - def initialized? - false - end + def value_for_database + end + + def initialized? + false + end - def with_type(type) - self.class.new(name, type) + def with_type(type) + self.class.new(name, type) + end end - end - private_constant :FromDatabase, :FromUser, :Null, :Uninitialized, :WithCastValue + private_constant :FromDatabase, :FromUser, :Null, :Uninitialized, :WithCastValue end end diff --git a/activerecord/lib/active_record/attribute/user_provided_default.rb b/activerecord/lib/active_record/attribute/user_provided_default.rb index 32b9c289bb..a4e2c2ec85 100644 --- a/activerecord/lib/active_record/attribute/user_provided_default.rb +++ b/activerecord/lib/active_record/attribute/user_provided_default.rb @@ -22,7 +22,7 @@ module ActiveRecord protected - attr_reader :user_provided_value + attr_reader :user_provided_value end end end diff --git a/activerecord/lib/active_record/attribute_assignment.rb b/activerecord/lib/active_record/attribute_assignment.rb index 1cccb0852e..f3ce52fdfe 100644 --- a/activerecord/lib/active_record/attribute_assignment.rb +++ b/activerecord/lib/active_record/attribute_assignment.rb @@ -12,27 +12,27 @@ module ActiveRecord private - def _assign_attributes(attributes) # :nodoc: - multi_parameter_attributes = {} - nested_parameter_attributes = {} + def _assign_attributes(attributes) # :nodoc: + multi_parameter_attributes = {} + nested_parameter_attributes = {} - attributes.each do |k, v| - if k.include?("(") - multi_parameter_attributes[k] = attributes.delete(k) - elsif v.is_a?(Hash) - nested_parameter_attributes[k] = attributes.delete(k) + attributes.each do |k, v| + if k.include?("(") + multi_parameter_attributes[k] = attributes.delete(k) + elsif v.is_a?(Hash) + nested_parameter_attributes[k] = attributes.delete(k) + end end - end - super(attributes) + super(attributes) - assign_nested_parameter_attributes(nested_parameter_attributes) unless nested_parameter_attributes.empty? - assign_multiparameter_attributes(multi_parameter_attributes) unless multi_parameter_attributes.empty? - end + assign_nested_parameter_attributes(nested_parameter_attributes) unless nested_parameter_attributes.empty? + assign_multiparameter_attributes(multi_parameter_attributes) unless multi_parameter_attributes.empty? + end # Assign any deferred nested attributes after the base attributes have been set. - def assign_nested_parameter_attributes(pairs) - pairs.each { |k, v| _assign_attribute(k, v) } - end + def assign_nested_parameter_attributes(pairs) + pairs.each { |k, v| _assign_attribute(k, v) } + end # Instantiates objects for all attribute classes that needs more than one constructor parameter. This is done # by calling new on the column type or aggregation type (through composed_of) object with these parameters. @@ -40,52 +40,52 @@ module ActiveRecord # written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the # parentheses to have the parameters typecasted before they're used in the constructor. Use i for Integer and # f for Float. If all the values for a given attribute are empty, the attribute will be set to +nil+. - def assign_multiparameter_attributes(pairs) - execute_callstack_for_multiparameter_attributes( - extract_callstack_for_multiparameter_attributes(pairs) - ) - end + def assign_multiparameter_attributes(pairs) + execute_callstack_for_multiparameter_attributes( + extract_callstack_for_multiparameter_attributes(pairs) + ) + end - def execute_callstack_for_multiparameter_attributes(callstack) - errors = [] - callstack.each do |name, values_with_empty_parameters| - begin - if values_with_empty_parameters.each_value.all?(&:nil?) - values = nil - else - values = values_with_empty_parameters + def execute_callstack_for_multiparameter_attributes(callstack) + errors = [] + callstack.each do |name, values_with_empty_parameters| + begin + if values_with_empty_parameters.each_value.all?(&:nil?) + values = nil + else + values = values_with_empty_parameters + end + send("#{name}=", values) + rescue => ex + errors << AttributeAssignmentError.new("error on assignment #{values_with_empty_parameters.values.inspect} to #{name} (#{ex.message})", ex, name) end - send("#{name}=", values) - rescue => ex - errors << AttributeAssignmentError.new("error on assignment #{values_with_empty_parameters.values.inspect} to #{name} (#{ex.message})", ex, name) + end + unless errors.empty? + error_descriptions = errors.map(&:message).join(",") + raise MultiparameterAssignmentErrors.new(errors), "#{errors.size} error(s) on assignment of multiparameter attributes [#{error_descriptions}]" end end - unless errors.empty? - error_descriptions = errors.map(&:message).join(",") - raise MultiparameterAssignmentErrors.new(errors), "#{errors.size} error(s) on assignment of multiparameter attributes [#{error_descriptions}]" - end - end - def extract_callstack_for_multiparameter_attributes(pairs) - attributes = {} + def extract_callstack_for_multiparameter_attributes(pairs) + attributes = {} - pairs.each do |(multiparameter_name, value)| - attribute_name = multiparameter_name.split("(").first - attributes[attribute_name] ||= {} + pairs.each do |(multiparameter_name, value)| + attribute_name = multiparameter_name.split("(").first + attributes[attribute_name] ||= {} - parameter_value = value.empty? ? nil : type_cast_attribute_value(multiparameter_name, value) - attributes[attribute_name][find_parameter_position(multiparameter_name)] ||= parameter_value - end + parameter_value = value.empty? ? nil : type_cast_attribute_value(multiparameter_name, value) + attributes[attribute_name][find_parameter_position(multiparameter_name)] ||= parameter_value + end - attributes - end + attributes + end - def type_cast_attribute_value(multiparameter_name, value) - multiparameter_name =~ /\([0-9]*([if])\)/ ? value.send("to_" + $1) : value - end + def type_cast_attribute_value(multiparameter_name, value) + multiparameter_name =~ /\([0-9]*([if])\)/ ? value.send("to_" + $1) : value + end - def find_parameter_position(multiparameter_name) - multiparameter_name.scan(/\(([0-9]*).*\)/).first.first.to_i - end + def find_parameter_position(multiparameter_name) + multiparameter_name.scan(/\(([0-9]*).*\)/).first.first.to_i + end end end diff --git a/activerecord/lib/active_record/attribute_decorators.rb b/activerecord/lib/active_record/attribute_decorators.rb index 7d0ae32411..340dfe11cf 100644 --- a/activerecord/lib/active_record/attribute_decorators.rb +++ b/activerecord/lib/active_record/attribute_decorators.rb @@ -24,13 +24,13 @@ module ActiveRecord private - def load_schema! - super - attribute_types.each do |name, type| - decorated_type = attribute_type_decorations.apply(name, type) - define_attribute(name, decorated_type) + def load_schema! + super + attribute_types.each do |name, type| + decorated_type = attribute_type_decorations.apply(name, type) + define_attribute(name, decorated_type) + end end - end end class TypeDecorator # :nodoc: @@ -53,15 +53,15 @@ module ActiveRecord private - def decorators_for(name, type) - matching(name, type).map(&:last) - end + def decorators_for(name, type) + matching(name, type).map(&:last) + end - def matching(name, type) - @decorations.values.select do |(matcher, _)| - matcher.call(name, type) + def matching(name, type) + @decorations.values.select do |(matcher, _)| + matcher.call(name, type) + end end - end end end end diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb index 12699bb30b..367e7fba84 100644 --- a/activerecord/lib/active_record/attribute_methods.rb +++ b/activerecord/lib/active_record/attribute_methods.rb @@ -161,7 +161,7 @@ module ActiveRecord # # => ["id", "created_at", "updated_at", "name", "age"] def attribute_names @attribute_names ||= if !abstract_class? && table_exists? - attribute_types.keys + attribute_types.keys else [] end @@ -394,65 +394,65 @@ module ActiveRecord protected - def clone_attribute_value(reader_method, attribute_name) # :nodoc: - value = send(reader_method, attribute_name) - value.duplicable? ? value.clone : value - rescue TypeError, NoMethodError - value - end + def clone_attribute_value(reader_method, attribute_name) # :nodoc: + value = send(reader_method, attribute_name) + value.duplicable? ? value.clone : value + rescue TypeError, NoMethodError + value + end - def arel_attributes_with_values_for_create(attribute_names) # :nodoc: - arel_attributes_with_values(attributes_for_create(attribute_names)) - end + def arel_attributes_with_values_for_create(attribute_names) # :nodoc: + arel_attributes_with_values(attributes_for_create(attribute_names)) + end - def arel_attributes_with_values_for_update(attribute_names) # :nodoc: - arel_attributes_with_values(attributes_for_update(attribute_names)) - end + def arel_attributes_with_values_for_update(attribute_names) # :nodoc: + arel_attributes_with_values(attributes_for_update(attribute_names)) + end - def attribute_method?(attr_name) # :nodoc: - # We check defined? because Syck calls respond_to? before actually calling initialize. - defined?(@attributes) && @attributes.key?(attr_name) - end + def attribute_method?(attr_name) # :nodoc: + # We check defined? because Syck calls respond_to? before actually calling initialize. + defined?(@attributes) && @attributes.key?(attr_name) + end private # Returns a Hash of the Arel::Attributes and attribute values that have been # typecasted for use in an Arel insert/update method. - def arel_attributes_with_values(attribute_names) - attrs = {} - arel_table = self.class.arel_table + def arel_attributes_with_values(attribute_names) + attrs = {} + arel_table = self.class.arel_table - attribute_names.each do |name| - attrs[arel_table[name]] = typecasted_attribute_value(name) + attribute_names.each do |name| + attrs[arel_table[name]] = typecasted_attribute_value(name) + end + attrs end - attrs - end # Filters the primary keys and readonly attributes from the attribute names. - def attributes_for_update(attribute_names) - attribute_names.reject do |name| - readonly_attribute?(name) + def attributes_for_update(attribute_names) + attribute_names.reject do |name| + readonly_attribute?(name) + end end - end # Filters out the primary keys, from the attribute names, when the primary # key is to be generated (e.g. the id attribute has no value). - def attributes_for_create(attribute_names) - attribute_names.reject do |name| - pk_attribute?(name) && id.nil? + def attributes_for_create(attribute_names) + attribute_names.reject do |name| + pk_attribute?(name) && id.nil? + end end - end - def readonly_attribute?(name) - self.class.readonly_attributes.include?(name) - end + def readonly_attribute?(name) + self.class.readonly_attributes.include?(name) + end - def pk_attribute?(name) - name == self.class.primary_key - end + def pk_attribute?(name) + name == self.class.primary_key + end - def typecasted_attribute_value(name) - _read_attribute(name) - end + def typecasted_attribute_value(name) + _read_attribute(name) + end end end diff --git a/activerecord/lib/active_record/attribute_methods/before_type_cast.rb b/activerecord/lib/active_record/attribute_methods/before_type_cast.rb index 1db6776688..92f124078c 100644 --- a/activerecord/lib/active_record/attribute_methods/before_type_cast.rb +++ b/activerecord/lib/active_record/attribute_methods/before_type_cast.rb @@ -64,13 +64,13 @@ module ActiveRecord private # Handle *_before_type_cast for method_missing. - def attribute_before_type_cast(attribute_name) - read_attribute_before_type_cast(attribute_name) - end + def attribute_before_type_cast(attribute_name) + read_attribute_before_type_cast(attribute_name) + end - def attribute_came_from_user?(attribute_name) - @attributes[attribute_name].came_from_user? - end + def attribute_came_from_user?(attribute_name) + @attributes[attribute_name].came_from_user? + end end end end diff --git a/activerecord/lib/active_record/attribute_methods/dirty.rb b/activerecord/lib/active_record/attribute_methods/dirty.rb index 50d7e1df7a..c9638bf70b 100644 --- a/activerecord/lib/active_record/attribute_methods/dirty.rb +++ b/activerecord/lib/active_record/attribute_methods/dirty.rb @@ -100,52 +100,52 @@ module ActiveRecord private - def mutation_tracker - unless defined?(@mutation_tracker) - @mutation_tracker = nil + def mutation_tracker + unless defined?(@mutation_tracker) + @mutation_tracker = nil + end + @mutation_tracker ||= AttributeMutationTracker.new(@attributes) end - @mutation_tracker ||= AttributeMutationTracker.new(@attributes) - end - def changes_include?(attr_name) - super || mutation_tracker.changed?(attr_name) - end + def changes_include?(attr_name) + super || mutation_tracker.changed?(attr_name) + end - def clear_attribute_change(attr_name) - mutation_tracker.forget_change(attr_name) - end + def clear_attribute_change(attr_name) + mutation_tracker.forget_change(attr_name) + end - def _update_record(*) - partial_writes? ? super(keys_for_partial_write) : super - end + def _update_record(*) + partial_writes? ? super(keys_for_partial_write) : super + end - def _create_record(*) - partial_writes? ? super(keys_for_partial_write) : super - end + def _create_record(*) + partial_writes? ? super(keys_for_partial_write) : super + end - def keys_for_partial_write - changed & self.class.column_names - end + def keys_for_partial_write + changed & self.class.column_names + end - def store_original_attributes - @attributes = @attributes.map(&:forgetting_assignment) - @mutation_tracker = nil - end + def store_original_attributes + @attributes = @attributes.map(&:forgetting_assignment) + @mutation_tracker = nil + end - def previous_mutation_tracker - @previous_mutation_tracker ||= NullMutationTracker.instance - end + def previous_mutation_tracker + @previous_mutation_tracker ||= NullMutationTracker.instance + end - def cache_changed_attributes - @cached_changed_attributes = changed_attributes - yield - ensure - clear_changed_attributes_cache - end + def cache_changed_attributes + @cached_changed_attributes = changed_attributes + yield + ensure + clear_changed_attributes_cache + end - def clear_changed_attributes_cache - remove_instance_variable(:@cached_changed_attributes) if defined?(@cached_changed_attributes) - end + def clear_changed_attributes_cache + remove_instance_variable(:@cached_changed_attributes) if defined?(@cached_changed_attributes) + end end end end diff --git a/activerecord/lib/active_record/attribute_methods/primary_key.rb b/activerecord/lib/active_record/attribute_methods/primary_key.rb index 162a564a49..9e99ed8ac1 100644 --- a/activerecord/lib/active_record/attribute_methods/primary_key.rb +++ b/activerecord/lib/active_record/attribute_methods/primary_key.rb @@ -47,95 +47,95 @@ module ActiveRecord protected - def attribute_method?(attr_name) - attr_name == "id" || super - end + def attribute_method?(attr_name) + attr_name == "id" || super + end - module ClassMethods - def define_method_attribute(attr_name) - super + module ClassMethods + def define_method_attribute(attr_name) + super - if attr_name == primary_key && attr_name != "id" - generated_attribute_methods.send(:alias_method, :id, primary_key) + if attr_name == primary_key && attr_name != "id" + generated_attribute_methods.send(:alias_method, :id, primary_key) + end end - end - ID_ATTRIBUTE_METHODS = %w(id id= id? id_before_type_cast id_was).to_set + ID_ATTRIBUTE_METHODS = %w(id id= id? id_before_type_cast id_was).to_set - def dangerous_attribute_method?(method_name) - super && !ID_ATTRIBUTE_METHODS.include?(method_name) - end + def dangerous_attribute_method?(method_name) + super && !ID_ATTRIBUTE_METHODS.include?(method_name) + end - # Defines the primary key field -- can be overridden in subclasses. - # Overwriting will negate any effect of the +primary_key_prefix_type+ - # setting, though. - def primary_key - @primary_key = reset_primary_key unless defined? @primary_key - @primary_key - end + # Defines the primary key field -- can be overridden in subclasses. + # Overwriting will negate any effect of the +primary_key_prefix_type+ + # setting, though. + def primary_key + @primary_key = reset_primary_key unless defined? @primary_key + @primary_key + end - # Returns a quoted version of the primary key name, used to construct - # SQL statements. - def quoted_primary_key - @quoted_primary_key ||= connection.quote_column_name(primary_key) - end + # Returns a quoted version of the primary key name, used to construct + # SQL statements. + def quoted_primary_key + @quoted_primary_key ||= connection.quote_column_name(primary_key) + end - def reset_primary_key #:nodoc: - if self == base_class - self.primary_key = get_primary_key(base_class.name) - else - self.primary_key = base_class.primary_key + def reset_primary_key #:nodoc: + if self == base_class + self.primary_key = get_primary_key(base_class.name) + else + self.primary_key = base_class.primary_key + end end - end - def get_primary_key(base_name) #:nodoc: - if base_name && primary_key_prefix_type == :table_name - base_name.foreign_key(false) - elsif base_name && primary_key_prefix_type == :table_name_with_underscore - base_name.foreign_key - else - if ActiveRecord::Base != self && table_exists? - pk = connection.schema_cache.primary_keys(table_name) - suppress_composite_primary_key(pk) + def get_primary_key(base_name) #:nodoc: + if base_name && primary_key_prefix_type == :table_name + base_name.foreign_key(false) + elsif base_name && primary_key_prefix_type == :table_name_with_underscore + base_name.foreign_key else - "id" + if ActiveRecord::Base != self && table_exists? + pk = connection.schema_cache.primary_keys(table_name) + suppress_composite_primary_key(pk) + else + "id" + end end end - end - # Sets the name of the primary key column. - # - # class Project < ActiveRecord::Base - # self.primary_key = 'sysid' - # end - # - # You can also define the #primary_key method yourself: - # - # class Project < ActiveRecord::Base - # def self.primary_key - # 'foo_' + super - # end - # end - # - # Project.primary_key # => "foo_id" - def primary_key=(value) - @primary_key = value && value.to_s - @quoted_primary_key = nil - @attributes_builder = nil - end + # Sets the name of the primary key column. + # + # class Project < ActiveRecord::Base + # self.primary_key = 'sysid' + # end + # + # You can also define the #primary_key method yourself: + # + # class Project < ActiveRecord::Base + # def self.primary_key + # 'foo_' + super + # end + # end + # + # Project.primary_key # => "foo_id" + def primary_key=(value) + @primary_key = value && value.to_s + @quoted_primary_key = nil + @attributes_builder = nil + end - private + private - def suppress_composite_primary_key(pk) - return pk unless pk.is_a?(Array) + def suppress_composite_primary_key(pk) + return pk unless pk.is_a?(Array) - warn <<-WARNING.strip_heredoc + warn <<-WARNING.strip_heredoc WARNING: Active Record does not support composite primary key. #{table_name} has composite primary key. Composite primary key is ignored. WARNING + end end - end end end end diff --git a/activerecord/lib/active_record/attribute_methods/read.rb b/activerecord/lib/active_record/attribute_methods/read.rb index a7310130fe..95853501db 100644 --- a/activerecord/lib/active_record/attribute_methods/read.rb +++ b/activerecord/lib/active_record/attribute_methods/read.rb @@ -24,24 +24,24 @@ module ActiveRecord # to allocate an object on each call to the attribute method. # Making it frozen means that it doesn't get duped when used to # key the @attributes in read_attribute. - def define_method_attribute(name) - safe_name = name.unpack("h*".freeze).first - temp_method = "__temp__#{safe_name}" + def define_method_attribute(name) + safe_name = name.unpack("h*".freeze).first + temp_method = "__temp__#{safe_name}" - ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name + ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name - generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1 + generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1 def #{temp_method} name = ::ActiveRecord::AttributeMethods::AttrNames::ATTR_#{safe_name} _read_attribute(name) { |n| missing_attribute(n, caller) } end STR - generated_attribute_methods.module_eval do - alias_method name, temp_method - undef_method temp_method + generated_attribute_methods.module_eval do + alias_method name, temp_method + undef_method temp_method + end end - end end # Returns the value of the attribute identified by attr_name after diff --git a/activerecord/lib/active_record/attribute_methods/serialization.rb b/activerecord/lib/active_record/attribute_methods/serialization.rb index 65978aea2a..8fb29fb358 100644 --- a/activerecord/lib/active_record/attribute_methods/serialization.rb +++ b/activerecord/lib/active_record/attribute_methods/serialization.rb @@ -50,7 +50,7 @@ module ActiveRecord # to ensure special objects (e.g. Active Record models) are dumped correctly # using the #as_json hook. coder = if class_name_or_coder == ::JSON - Coders::JSON + Coders::JSON elsif [:load, :dump].all? { |x| class_name_or_coder.respond_to?(x) } class_name_or_coder else 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 d7b5f8b262..ff9fd206c0 100644 --- a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb +++ b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb @@ -26,31 +26,31 @@ module ActiveRecord private - def convert_time_to_time_zone(value) - return if value.nil? + def convert_time_to_time_zone(value) + return if value.nil? - if value.acts_like?(:time) - value.in_time_zone - elsif value.is_a?(::Float) - value - else - map_avoiding_infinite_recursion(value) { |v| convert_time_to_time_zone(v) } + if value.acts_like?(:time) + value.in_time_zone + elsif value.is_a?(::Float) + value + else + map_avoiding_infinite_recursion(value) { |v| convert_time_to_time_zone(v) } + end end - end - def set_time_zone_without_conversion(value) - ::Time.zone.local_to_utc(value).in_time_zone if value - end + def set_time_zone_without_conversion(value) + ::Time.zone.local_to_utc(value).in_time_zone if value + end - def map_avoiding_infinite_recursion(value) - map(value) do |v| - if value.equal?(v) - nil - else - yield(v) + def map_avoiding_infinite_recursion(value) + map(value) do |v| + if value.equal?(v) + nil + else + yield(v) + end end end - end end extend ActiveSupport::Concern @@ -69,31 +69,31 @@ module ActiveRecord module ClassMethods private - def inherited(subclass) - # We need to apply this decorator here, rather than on module inclusion. The closure - # created by the matcher would otherwise evaluate for `ActiveRecord::Base`, not the - # sub class being decorated. As such, changes to `time_zone_aware_attributes`, or - # `skip_time_zone_conversion_for_attributes` would not be picked up. - subclass.class_eval do - matcher = ->(name, type) { create_time_zone_conversion_attribute?(name, type) } - decorate_matching_attribute_types(matcher, :_time_zone_conversion) do |type| - TimeZoneConverter.new(type) + def inherited(subclass) + # We need to apply this decorator here, rather than on module inclusion. The closure + # created by the matcher would otherwise evaluate for `ActiveRecord::Base`, not the + # sub class being decorated. As such, changes to `time_zone_aware_attributes`, or + # `skip_time_zone_conversion_for_attributes` would not be picked up. + subclass.class_eval do + matcher = ->(name, type) { create_time_zone_conversion_attribute?(name, type) } + decorate_matching_attribute_types(matcher, :_time_zone_conversion) do |type| + TimeZoneConverter.new(type) + end end + super end - super - end - 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) - result = enabled_for_column && - time_zone_aware_types.include?(cast_type.type) - - if enabled_for_column && - !result && - cast_type.type == :time && - time_zone_aware_types.include?(:not_explicitly_configured) - ActiveSupport::Deprecation.warn(<<-MESSAGE.strip_heredoc) + 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) + result = enabled_for_column && + time_zone_aware_types.include?(cast_type.type) + + if enabled_for_column && + !result && + cast_type.type == :time && + time_zone_aware_types.include?(:not_explicitly_configured) + ActiveSupport::Deprecation.warn(<<-MESSAGE.strip_heredoc) Time columns will become time zone aware in Rails 5.1. This still causes `String`s to be parsed as if they were in `Time.zone`, and `Time`s to be converted to `Time.zone`. @@ -106,10 +106,10 @@ module ActiveRecord config.active_record.time_zone_aware_types = [:datetime, :time] MESSAGE - end + end - result - end + result + end end end end diff --git a/activerecord/lib/active_record/attribute_methods/write.rb b/activerecord/lib/active_record/attribute_methods/write.rb index e7f62197c3..5822414129 100644 --- a/activerecord/lib/active_record/attribute_methods/write.rb +++ b/activerecord/lib/active_record/attribute_methods/write.rb @@ -10,11 +10,11 @@ module ActiveRecord module ClassMethods protected - def define_method_attribute=(name) - safe_name = name.unpack("h*".freeze).first - ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name + def define_method_attribute=(name) + safe_name = name.unpack("h*".freeze).first + ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name - generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1 + generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1 def __temp__#{safe_name}=(value) name = ::ActiveRecord::AttributeMethods::AttrNames::ATTR_#{safe_name} write_attribute(name, value) @@ -22,7 +22,7 @@ module ActiveRecord alias_method #{(name + '=').inspect}, :__temp__#{safe_name}= undef_method :__temp__#{safe_name}= STR - end + end end # Updates the attribute identified by attr_name with the @@ -38,22 +38,22 @@ module ActiveRecord private # Handle *= for method_missing. - def attribute=(attribute_name, value) - write_attribute(attribute_name, value) - end + def attribute=(attribute_name, value) + write_attribute(attribute_name, value) + end - def write_attribute_with_type_cast(attr_name, value, should_type_cast) - attr_name = attr_name.to_s - attr_name = self.class.primary_key if attr_name == "id" && self.class.primary_key + def write_attribute_with_type_cast(attr_name, value, should_type_cast) + attr_name = attr_name.to_s + attr_name = self.class.primary_key if attr_name == "id" && self.class.primary_key - if should_type_cast - @attributes.write_from_user(attr_name, value) - else - @attributes.write_cast_value(attr_name, value) - end + if should_type_cast + @attributes.write_from_user(attr_name, value) + else + @attributes.write_cast_value(attr_name, value) + end - value - end + value + end end end end diff --git a/activerecord/lib/active_record/attribute_mutation_tracker.rb b/activerecord/lib/active_record/attribute_mutation_tracker.rb index 0133b4d0be..c257aef52f 100644 --- a/activerecord/lib/active_record/attribute_mutation_tracker.rb +++ b/activerecord/lib/active_record/attribute_mutation_tracker.rb @@ -36,13 +36,13 @@ module ActiveRecord protected - attr_reader :attributes + attr_reader :attributes private - def attr_names - attributes.keys - end + def attr_names + attributes.keys + end end class NullMutationTracker # :nodoc: diff --git a/activerecord/lib/active_record/attribute_set.rb b/activerecord/lib/active_record/attribute_set.rb index fd569d869a..5bde1f107c 100644 --- a/activerecord/lib/active_record/attribute_set.rb +++ b/activerecord/lib/active_record/attribute_set.rb @@ -100,12 +100,12 @@ module ActiveRecord protected - attr_reader :attributes + attr_reader :attributes private - def initialized_attributes - attributes.select { |_, attr| attr.initialized? } - end + def initialized_attributes + attributes.select { |_, attr| attr.initialized? } + end end end diff --git a/activerecord/lib/active_record/attribute_set/builder.rb b/activerecord/lib/active_record/attribute_set/builder.rb index b4d98ca3c0..661f996e1a 100644 --- a/activerecord/lib/active_record/attribute_set/builder.rb +++ b/activerecord/lib/active_record/attribute_set/builder.rb @@ -92,31 +92,31 @@ module ActiveRecord protected - attr_reader :types, :values, :additional_types, :delegate_hash, :default - - def materialize - unless @materialized - values.each_key { |key| self[key] } - types.each_key { |key| self[key] } - unless frozen? - @materialized = true + attr_reader :types, :values, :additional_types, :delegate_hash, :default + + def materialize + unless @materialized + values.each_key { |key| self[key] } + types.each_key { |key| self[key] } + unless frozen? + @materialized = true + end end + delegate_hash end - delegate_hash - end private - def assign_default_value(name) - type = additional_types.fetch(name, types[name]) - value_present = true - value = values.fetch(name) { value_present = false } + def assign_default_value(name) + type = additional_types.fetch(name, types[name]) + value_present = true + value = values.fetch(name) { value_present = false } - if value_present - delegate_hash[name] = Attribute.from_database(name, value, type) - elsif types.key?(name) - delegate_hash[name] = default.call(name) || Attribute.uninitialized(name, type) + if value_present + delegate_hash[name] = Attribute.from_database(name, value, type) + elsif types.key?(name) + delegate_hash[name] = default.call(name) || Attribute.uninitialized(name, type) + end end - end end end diff --git a/activerecord/lib/active_record/attribute_set/yaml_encoder.rb b/activerecord/lib/active_record/attribute_set/yaml_encoder.rb index 52ffe719f4..c86cfc4263 100644 --- a/activerecord/lib/active_record/attribute_set/yaml_encoder.rb +++ b/activerecord/lib/active_record/attribute_set/yaml_encoder.rb @@ -33,7 +33,7 @@ module ActiveRecord protected - attr_reader :default_types + attr_reader :default_types end end end diff --git a/activerecord/lib/active_record/attributes.rb b/activerecord/lib/active_record/attributes.rb index 880d9a2b84..4b92e5835f 100644 --- a/activerecord/lib/active_record/attributes.rb +++ b/activerecord/lib/active_record/attributes.rb @@ -242,24 +242,24 @@ module ActiveRecord private - NO_DEFAULT_PROVIDED = Object.new # :nodoc: - private_constant :NO_DEFAULT_PROVIDED + NO_DEFAULT_PROVIDED = Object.new # :nodoc: + private_constant :NO_DEFAULT_PROVIDED - def define_default_attribute(name, value, type, from_user:) - if value == NO_DEFAULT_PROVIDED - default_attribute = _default_attributes[name].with_type(type) - elsif from_user - default_attribute = Attribute::UserProvidedDefault.new( - name, - value, - type, - _default_attributes.fetch(name.to_s) { nil }, - ) - else - default_attribute = Attribute.from_database(name, value, type) + def define_default_attribute(name, value, type, from_user:) + if value == NO_DEFAULT_PROVIDED + default_attribute = _default_attributes[name].with_type(type) + elsif from_user + default_attribute = Attribute::UserProvidedDefault.new( + name, + value, + type, + _default_attributes.fetch(name.to_s) { nil }, + ) + else + default_attribute = Attribute.from_database(name, value, type) + end + _default_attributes[name] = default_attribute end - _default_attributes[name] = default_attribute - end end end end diff --git a/activerecord/lib/active_record/coders/yaml_column.rb b/activerecord/lib/active_record/coders/yaml_column.rb index 8b98d9ccd7..ee38172742 100644 --- a/activerecord/lib/active_record/coders/yaml_column.rb +++ b/activerecord/lib/active_record/coders/yaml_column.rb @@ -39,13 +39,13 @@ module ActiveRecord private - def check_arity_of_constructor - begin - load(nil) - rescue ArgumentError - raise ArgumentError, "Cannot serialize #{object_class}. Classes passed to `serialize` must have a 0 argument constructor." + def check_arity_of_constructor + begin + load(nil) + rescue ArgumentError + raise ArgumentError, "Cannot serialize #{object_class}. Classes passed to `serialize` must have a 0 argument constructor." + end end - end end end end 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 db798bc303..535d79b525 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb @@ -150,61 +150,61 @@ module ActiveRecord private - def internal_poll(timeout) - no_wait_poll || (timeout && wait_poll(timeout)) - end + def internal_poll(timeout) + no_wait_poll || (timeout && wait_poll(timeout)) + end - def synchronize(&block) - @lock.synchronize(&block) - end + def synchronize(&block) + @lock.synchronize(&block) + end # Test if the queue currently contains any elements. - def any? - !@queue.empty? - end + def any? + !@queue.empty? + end # A thread can remove an element from the queue without # waiting if and only if the number of currently available # connections is strictly greater than the number of waiting # threads. - def can_remove_no_wait? - @queue.size > @num_waiting - end + def can_remove_no_wait? + @queue.size > @num_waiting + end # Removes and returns the head of the queue if possible, or nil. - def remove - @queue.shift - end + def remove + @queue.shift + end # Remove and return the head the queue if the number of # available elements is strictly greater than the number of # threads currently waiting. Otherwise, return nil. - def no_wait_poll - remove if can_remove_no_wait? - end + def no_wait_poll + remove if can_remove_no_wait? + end # Waits on the queue up to +timeout+ seconds, then removes and # returns the head of the queue. - def wait_poll(timeout) - @num_waiting += 1 + def wait_poll(timeout) + @num_waiting += 1 - t0 = Time.now - elapsed = 0 - loop do - @cond.wait(timeout - elapsed) + t0 = Time.now + elapsed = 0 + loop do + @cond.wait(timeout - elapsed) - return remove if any? + return remove if any? - elapsed = Time.now - t0 - if elapsed >= timeout - msg = "could not obtain a connection from the pool within %0.3f seconds (waited %0.3f seconds); all pooled connections were in use" % - [timeout, elapsed] - raise ConnectionTimeoutError, msg + elapsed = Time.now - t0 + if elapsed >= timeout + msg = "could not obtain a connection from the pool within %0.3f seconds (waited %0.3f seconds); all pooled connections were in use" % + [timeout, elapsed] + raise ConnectionTimeoutError, msg + end end + ensure + @num_waiting -= 1 end - ensure - @num_waiting -= 1 - end end # Adds the ability to turn a basic fair FIFO queue into one @@ -274,11 +274,11 @@ module ActiveRecord include BiasableQueue private - def internal_poll(timeout) - conn = super - conn.lease if conn - conn - end + def internal_poll(timeout) + conn = super + conn.lease if conn + conn + end end # Every +frequency+ seconds, the reaper will call +reap+ on +pool+. @@ -584,111 +584,111 @@ module ActiveRecord private #-- # this is unfortunately not concurrent - def bulk_make_new_connections(num_new_conns_needed) - num_new_conns_needed.times do - # try_to_checkout_new_connection will not exceed pool's @size limit - if new_conn = try_to_checkout_new_connection - # make the new_conn available to the starving threads stuck @available Queue - checkin(new_conn) + def bulk_make_new_connections(num_new_conns_needed) + num_new_conns_needed.times do + # try_to_checkout_new_connection will not exceed pool's @size limit + if new_conn = try_to_checkout_new_connection + # make the new_conn available to the starving threads stuck @available Queue + checkin(new_conn) + end end end - end #-- # From the discussion on GitHub: # https://github.com/rails/rails/pull/14938#commitcomment-6601951 # This hook-in method allows for easier monkey-patching fixes needed by # JRuby users that use Fibers. - def connection_cache_key(thread) - thread - end + def connection_cache_key(thread) + thread + end # Take control of all existing connections so a "group" action such as # reload/disconnect can be performed safely. It is no longer enough to # wrap it in +synchronize+ because some pool's actions are allowed # to be performed outside of the main +synchronize+ block. - def with_exclusively_acquired_all_connections(raise_on_acquisition_timeout = true) - with_new_connections_blocked do - attempt_to_checkout_all_existing_connections(raise_on_acquisition_timeout) - yield + def with_exclusively_acquired_all_connections(raise_on_acquisition_timeout = true) + with_new_connections_blocked do + attempt_to_checkout_all_existing_connections(raise_on_acquisition_timeout) + yield + end end - end - 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} - end + 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} + end - newly_checked_out = [] - timeout_time = Time.now + (@checkout_timeout * 2) + newly_checked_out = [] + timeout_time = Time.now + (@checkout_timeout * 2) - @available.with_a_bias_for(Thread.current) do - loop do - synchronize do - return if collected_conns.size == @connections.size && @now_connecting == 0 - remaining_timeout = timeout_time - Time.now - remaining_timeout = 0 if remaining_timeout < 0 - conn = checkout_for_exclusive_access(remaining_timeout) - collected_conns << conn - newly_checked_out << conn + @available.with_a_bias_for(Thread.current) do + loop do + synchronize do + return if collected_conns.size == @connections.size && @now_connecting == 0 + remaining_timeout = timeout_time - Time.now + remaining_timeout = 0 if remaining_timeout < 0 + conn = checkout_for_exclusive_access(remaining_timeout) + collected_conns << conn + newly_checked_out << conn + end end end - end - rescue ExclusiveConnectionTimeoutError - # raise_on_acquisition_timeout == false means we are directed to ignore any - # timeouts and are expected to just give up: we've obtained as many connections - # as possible, note that in a case like that we don't return any of the - # +newly_checked_out+ connections. - - if raise_on_acquisition_timeout + rescue ExclusiveConnectionTimeoutError + # raise_on_acquisition_timeout == false means we are directed to ignore any + # timeouts and are expected to just give up: we've obtained as many connections + # as possible, note that in a case like that we don't return any of the + # +newly_checked_out+ connections. + + if raise_on_acquisition_timeout + release_newly_checked_out = true + raise + end + rescue Exception # if something else went wrong + # this can't be a "naked" rescue, because we have should return conns + # even for non-StandardErrors release_newly_checked_out = true raise + ensure + 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)} + end end - rescue Exception # if something else went wrong - # this can't be a "naked" rescue, because we have should return conns - # even for non-StandardErrors - release_newly_checked_out = true - raise - ensure - 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)} - end - end #-- # Must be called in a synchronize block. - def checkout_for_exclusive_access(checkout_timeout) - checkout(checkout_timeout) - rescue ConnectionTimeoutError - # this block can't be easily moved into attempt_to_checkout_all_existing_connections's - # rescue block, because doing so would put it outside of synchronize section, without - # being in a critical section thread_report might become inaccurate - msg = "could not obtain ownership of all database connections in #{checkout_timeout} seconds" - - thread_report = [] - @connections.each do |conn| - unless conn.owner == Thread.current - thread_report << "#{conn} is owned by #{conn.owner}" + def checkout_for_exclusive_access(checkout_timeout) + checkout(checkout_timeout) + rescue ConnectionTimeoutError + # this block can't be easily moved into attempt_to_checkout_all_existing_connections's + # rescue block, because doing so would put it outside of synchronize section, without + # being in a critical section thread_report might become inaccurate + msg = "could not obtain ownership of all database connections in #{checkout_timeout} seconds" + + thread_report = [] + @connections.each do |conn| + unless conn.owner == Thread.current + thread_report << "#{conn} is owned by #{conn.owner}" + end end - end - msg << " (#{thread_report.join(', ')})" if thread_report.any? + msg << " (#{thread_report.join(', ')})" if thread_report.any? - raise ExclusiveConnectionTimeoutError, msg - end + raise ExclusiveConnectionTimeoutError, msg + end - def with_new_connections_blocked - previous_value = nil - synchronize do - previous_value, @new_cons_enabled = @new_cons_enabled, false + def with_new_connections_blocked + previous_value = nil + synchronize do + previous_value, @new_cons_enabled = @new_cons_enabled, false + end + yield + ensure + synchronize { @new_cons_enabled = previous_value } end - yield - ensure - synchronize { @new_cons_enabled = previous_value } - end # Acquire a connection by one of 1) immediately removing one # from the queue of available connections, 2) creating a new @@ -701,86 +701,86 @@ module ActiveRecord #-- # Implementation detail: the connection returned by +acquire_connection+ # will already be "+connection.lease+ -ed" to the current thread. - def acquire_connection(checkout_timeout) - # NOTE: we rely on +@available.poll+ and +try_to_checkout_new_connection+ to - # +conn.lease+ the returned connection (and to do this in a +synchronized+ - # section). This is not the cleanest implementation, as ideally we would - # synchronize { conn.lease } in this method, but by leaving it to +@available.poll+ - # and +try_to_checkout_new_connection+ we can piggyback on +synchronize+ sections - # of the said methods and avoid an additional +synchronize+ overhead. - if conn = @available.poll || try_to_checkout_new_connection - conn - else - reap - @available.poll(checkout_timeout) + def acquire_connection(checkout_timeout) + # NOTE: we rely on +@available.poll+ and +try_to_checkout_new_connection+ to + # +conn.lease+ the returned connection (and to do this in a +synchronized+ + # section). This is not the cleanest implementation, as ideally we would + # synchronize { conn.lease } in this method, but by leaving it to +@available.poll+ + # and +try_to_checkout_new_connection+ we can piggyback on +synchronize+ sections + # of the said methods and avoid an additional +synchronize+ overhead. + if conn = @available.poll || try_to_checkout_new_connection + conn + else + reap + @available.poll(checkout_timeout) + end end - end #-- # if owner_thread param is omitted, this must be called in synchronize block - def remove_connection_from_thread_cache(conn, owner_thread = conn.owner) - @thread_cached_conns.delete_pair(connection_cache_key(owner_thread), conn) - end - alias_method :release, :remove_connection_from_thread_cache + def remove_connection_from_thread_cache(conn, owner_thread = conn.owner) + @thread_cached_conns.delete_pair(connection_cache_key(owner_thread), conn) + end + alias_method :release, :remove_connection_from_thread_cache - def new_connection - Base.send(spec.adapter_method, spec.config).tap do |conn| - conn.schema_cache = schema_cache.dup if schema_cache + def new_connection + Base.send(spec.adapter_method, spec.config).tap do |conn| + conn.schema_cache = schema_cache.dup if schema_cache + end end - end # If the pool is not at a +@size+ limit, establish new connection. Connecting # to the DB is done outside main synchronized section. #-- # Implementation constraint: a newly established connection returned by this # method must be in the +.leased+ state. - def try_to_checkout_new_connection - # first in synchronized section check if establishing new conns is allowed - # and increment @now_connecting, to prevent overstepping this pool's @size - # constraint - do_checkout = synchronize do - if @new_cons_enabled && (@connections.size + @now_connecting) < @size - @now_connecting += 1 - end - end - if do_checkout - begin - # if successfully incremented @now_connecting establish new connection - # outside of synchronized section - conn = checkout_new_connection - ensure - synchronize do - if conn - adopt_connection(conn) - # returned conn needs to be already leased - conn.lease + def try_to_checkout_new_connection + # first in synchronized section check if establishing new conns is allowed + # and increment @now_connecting, to prevent overstepping this pool's @size + # constraint + do_checkout = synchronize do + if @new_cons_enabled && (@connections.size + @now_connecting) < @size + @now_connecting += 1 + end + end + if do_checkout + begin + # if successfully incremented @now_connecting establish new connection + # outside of synchronized section + conn = checkout_new_connection + ensure + synchronize do + if conn + adopt_connection(conn) + # returned conn needs to be already leased + conn.lease + end + @now_connecting -= 1 end - @now_connecting -= 1 end end end - end - def adopt_connection(conn) - conn.pool = self - @connections << conn - end + def adopt_connection(conn) + conn.pool = self + @connections << conn + end - def checkout_new_connection - raise ConnectionNotEstablished unless @automatic_reconnect - new_connection - end + def checkout_new_connection + raise ConnectionNotEstablished unless @automatic_reconnect + new_connection + end - def checkout_and_verify(c) - c._run_checkout_callbacks do - c.verify! + def checkout_and_verify(c) + c._run_checkout_callbacks do + c.verify! + end + c + rescue + remove c + c.disconnect! + raise end - c - rescue - remove c - c.disconnect! - raise - end end # ConnectionHandler is a collection of ConnectionPool objects. It is used @@ -942,14 +942,14 @@ module ActiveRecord private - def owner_to_pool - @owner_to_pool[Process.pid] - end + def owner_to_pool + @owner_to_pool[Process.pid] + end - def pool_from_any_process_for(spec_name) - owner_to_pool = @owner_to_pool.values.find { |v| v[spec_name] } - owner_to_pool && owner_to_pool[spec_name] - end + def pool_from_any_process_for(spec_name) + owner_to_pool = @owner_to_pool.values.find { |v| v[spec_name] } + owner_to_pool && owner_to_pool[spec_name] + end end end end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb b/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb index 47f24df22f..10c60080d5 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb @@ -73,23 +73,23 @@ module ActiveRecord private - def cache_sql(sql, binds) - result = - if @query_cache[sql].key?(binds) - ActiveSupport::Notifications.instrument("sql.active_record", - sql: sql, binds: binds, name: "CACHE", connection_id: object_id) - @query_cache[sql][binds] - else - @query_cache[sql][binds] = yield - end - result.dup - end + def cache_sql(sql, binds) + result = + if @query_cache[sql].key?(binds) + ActiveSupport::Notifications.instrument("sql.active_record", + sql: sql, binds: binds, name: "CACHE", connection_id: object_id) + @query_cache[sql][binds] + else + @query_cache[sql][binds] = yield + end + result.dup + end # If arel is locked this is a SELECT ... FOR UPDATE or somesuch. Such # queries should not be cached. - def locked?(arel) - arel.respond_to?(:locked) && arel.locked - end + def locked?(arel) + arel.respond_to?(:locked) && arel.locked + end end end end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb index 20d009bbf8..bbd52b8a91 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb @@ -152,47 +152,47 @@ module ActiveRecord private - def type_casted_binds(binds) - binds.map { |attr| type_cast(attr.value_for_database) } - end - - def types_which_need_no_typecasting - [nil, Numeric, String] - end - - def _quote(value) - case value - when String, ActiveSupport::Multibyte::Chars, Type::Binary::Data - "'#{quote_string(value.to_s)}'" - when true then quoted_true - when false then quoted_false - when nil then "NULL" - # BigDecimals need to be put in a non-normalized form and quoted. - when BigDecimal then value.to_s("F") - when Numeric, ActiveSupport::Duration then value.to_s - when Type::Time::Value then "'#{quoted_time(value)}'" - when Date, Time then "'#{quoted_date(value)}'" - when Symbol then "'#{quote_string(value.to_s)}'" - when Class then "'#{value}'" - else raise TypeError, "can't quote #{value.class.name}" + def type_casted_binds(binds) + binds.map { |attr| type_cast(attr.value_for_database) } end - end - def _type_cast(value) - case value - when Symbol, ActiveSupport::Multibyte::Chars, Type::Binary::Data - value.to_s - when true then unquoted_true - when false then unquoted_false - # BigDecimals need to be put in a non-normalized form and quoted. - when BigDecimal then value.to_s("F") - when Type::Time::Value then quoted_time(value) - when Date, Time then quoted_date(value) - when *types_which_need_no_typecasting - value - else raise TypeError + def types_which_need_no_typecasting + [nil, Numeric, String] + end + + def _quote(value) + case value + when String, ActiveSupport::Multibyte::Chars, Type::Binary::Data + "'#{quote_string(value.to_s)}'" + when true then quoted_true + when false then quoted_false + when nil then "NULL" + # BigDecimals need to be put in a non-normalized form and quoted. + when BigDecimal then value.to_s("F") + when Numeric, ActiveSupport::Duration then value.to_s + when Type::Time::Value then "'#{quoted_time(value)}'" + when Date, Time then "'#{quoted_date(value)}'" + when Symbol then "'#{quote_string(value.to_s)}'" + when Class then "'#{value}'" + else raise TypeError, "can't quote #{value.class.name}" + end + end + + def _type_cast(value) + case value + when Symbol, ActiveSupport::Multibyte::Chars, Type::Binary::Data + value.to_s + when true then unquoted_true + when false then unquoted_false + # BigDecimals need to be put in a non-normalized form and quoted. + when BigDecimal then value.to_s("F") + when Type::Time::Value then quoted_time(value) + when Date, Time then quoted_date(value) + when *types_which_need_no_typecasting + value + else raise TypeError + end end - end end end 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 c1fc99ce1f..1d18a58eab 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb @@ -61,9 +61,9 @@ module ActiveRecord end private - def default_primary_key - "id" - end + def default_primary_key + "id" + end end class ReferenceDefinition # :nodoc: @@ -103,51 +103,51 @@ module ActiveRecord protected - attr_reader :name, :polymorphic, :index, :foreign_key, :type, :options + attr_reader :name, :polymorphic, :index, :foreign_key, :type, :options private - def as_options(value, default = {}) - if value.is_a?(Hash) - value - else - default + def as_options(value, default = {}) + if value.is_a?(Hash) + value + else + default + end end - end - def polymorphic_options - as_options(polymorphic, options) - end + def polymorphic_options + as_options(polymorphic, options) + end - def index_options - as_options(index) - end + def index_options + as_options(index) + end - def foreign_key_options - as_options(foreign_key).merge(column: column_name) - end + def foreign_key_options + as_options(foreign_key).merge(column: column_name) + end - def columns - result = [[column_name, type, options]] - if polymorphic - result.unshift(["#{name}_type", :string, polymorphic_options]) + def columns + result = [[column_name, type, options]] + if polymorphic + result.unshift(["#{name}_type", :string, polymorphic_options]) + end + result end - result - end - def column_name - "#{name}_id" - end + def column_name + "#{name}_id" + end - def column_names - columns.map(&:first) - end + def column_names + columns.map(&:first) + end - def foreign_table_name - foreign_key_options.fetch(:to_table) do - Base.pluralize_table_names ? name.to_s.pluralize : name + def foreign_table_name + foreign_key_options.fetch(:to_table) do + Base.pluralize_table_names ? name.to_s.pluralize : name + end end - end end module ColumnMethods @@ -383,13 +383,13 @@ module ActiveRecord end private - def create_column_definition(name, type) - ColumnDefinition.new name, type - end + def create_column_definition(name, type) + ColumnDefinition.new name, type + end - def aliased_types(name, fallback) - "timestamp" == name ? :datetime : fallback - end + def aliased_types(name, fallback) + "timestamp" == name ? :datetime : fallback + end end class AlterTable # :nodoc: diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb index 321e08c5ca..8bb7362c2e 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb @@ -58,48 +58,48 @@ module ActiveRecord private - def default_primary_key?(column) - schema_type(column) == :integer - end + def default_primary_key?(column) + schema_type(column) == :integer + end - def schema_type(column) - if column.bigint? - :bigint - else - column.type + def schema_type(column) + if column.bigint? + :bigint + else + column.type + end end - end - def schema_limit(column) - limit = column.limit unless column.bigint? - limit.inspect if limit && limit != native_database_types[column.type][:limit] - end + def schema_limit(column) + limit = column.limit unless column.bigint? + limit.inspect if limit && limit != native_database_types[column.type][:limit] + end - def schema_precision(column) - column.precision.inspect if column.precision - end + def schema_precision(column) + column.precision.inspect if column.precision + end - def schema_scale(column) - column.scale.inspect if column.scale - end + def schema_scale(column) + column.scale.inspect if column.scale + end - def schema_default(column) - type = lookup_cast_type_from_column(column) - default = type.deserialize(column.default) - if default.nil? - schema_expression(column) - else - type.type_cast_for_schema(default) + def schema_default(column) + type = lookup_cast_type_from_column(column) + default = type.deserialize(column.default) + if default.nil? + schema_expression(column) + else + type.type_cast_for_schema(default) + end end - end - def schema_expression(column) - "-> { #{column.default_function.inspect} }" if column.default_function - end + def schema_expression(column) + "-> { #{column.default_function.inspect} }" if column.default_function + end - def schema_collation(column) - column.collation.inspect if column.collation - end + def schema_collation(column) + column.collation.inspect if column.collation + end end end end 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 f2134fe035..d2ebc36fff 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb @@ -1245,49 +1245,49 @@ module ActiveRecord end private - def create_table_definition(*args) - TableDefinition.new(*args) - end - - def create_alter_table(name) - AlterTable.new create_table_definition(name) - end + def create_table_definition(*args) + TableDefinition.new(*args) + end - def index_name_options(column_names) # :nodoc: - if column_names.is_a?(String) - column_names = column_names.scan(/\w+/).join("_") + def create_alter_table(name) + AlterTable.new create_table_definition(name) end - { column: column_names } - end + def index_name_options(column_names) # :nodoc: + if column_names.is_a?(String) + column_names = column_names.scan(/\w+/).join("_") + end - def foreign_key_name(table_name, options) # :nodoc: - identifier = "#{table_name}_#{options.fetch(:column)}_fk" - hashed_identifier = Digest::SHA256.hexdigest(identifier).first(10) - options.fetch(:name) do - "fk_rails_#{hashed_identifier}" + { column: column_names } + end + + def foreign_key_name(table_name, options) # :nodoc: + identifier = "#{table_name}_#{options.fetch(:column)}_fk" + hashed_identifier = Digest::SHA256.hexdigest(identifier).first(10) + options.fetch(:name) do + "fk_rails_#{hashed_identifier}" + end end - end - def validate_index_length!(table_name, new_name, internal = false) # :nodoc: - max_index_length = internal ? index_name_length : allowed_index_name_length + def validate_index_length!(table_name, new_name, internal = false) # :nodoc: + max_index_length = internal ? index_name_length : allowed_index_name_length - if new_name.length > max_index_length - raise ArgumentError, "Index name '#{new_name}' on table '#{table_name}' is too long; the limit is #{allowed_index_name_length} characters" + if new_name.length > max_index_length + raise ArgumentError, "Index name '#{new_name}' on table '#{table_name}' is too long; the limit is #{allowed_index_name_length} characters" + end end - end - def extract_new_default_value(default_or_changes) - if default_or_changes.is_a?(Hash) && default_or_changes.has_key?(:from) && default_or_changes.has_key?(:to) - default_or_changes[:to] - else - default_or_changes + def extract_new_default_value(default_or_changes) + if default_or_changes.is_a?(Hash) && default_or_changes.has_key?(:from) && default_or_changes.has_key?(:to) + default_or_changes[:to] + else + default_or_changes + end end - end - def can_remove_index_by_name?(options) - options.is_a?(Hash) && options.key?(:name) && options.except(:name, :algorithm).empty? - end + def can_remove_index_by_name?(options) + options.is_a?(Hash) && options.key?(:name) && options.except(:name, :algorithm).empty? + end end end end diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb index 7ba3b5f43b..8a2a1fafb1 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb @@ -497,115 +497,115 @@ module ActiveRecord protected - def initialize_type_map(m) # :nodoc: - register_class_with_limit m, %r(boolean)i, Type::Boolean - register_class_with_limit m, %r(char)i, Type::String - register_class_with_limit m, %r(binary)i, Type::Binary - register_class_with_limit m, %r(text)i, Type::Text - register_class_with_precision m, %r(date)i, Type::Date - register_class_with_precision m, %r(time)i, Type::Time - register_class_with_precision m, %r(datetime)i, Type::DateTime - register_class_with_limit m, %r(float)i, Type::Float - register_class_with_limit m, %r(int)i, Type::Integer - - m.alias_type %r(blob)i, "binary" - m.alias_type %r(clob)i, "text" - m.alias_type %r(timestamp)i, "datetime" - m.alias_type %r(numeric)i, "decimal" - m.alias_type %r(number)i, "decimal" - m.alias_type %r(double)i, "float" - - m.register_type(%r(decimal)i) do |sql_type| - scale = extract_scale(sql_type) - precision = extract_precision(sql_type) - - if scale == 0 - # FIXME: Remove this class as well - Type::DecimalWithoutScale.new(precision: precision) - else - Type::Decimal.new(precision: precision, scale: scale) + def initialize_type_map(m) # :nodoc: + register_class_with_limit m, %r(boolean)i, Type::Boolean + register_class_with_limit m, %r(char)i, Type::String + register_class_with_limit m, %r(binary)i, Type::Binary + register_class_with_limit m, %r(text)i, Type::Text + register_class_with_precision m, %r(date)i, Type::Date + register_class_with_precision m, %r(time)i, Type::Time + register_class_with_precision m, %r(datetime)i, Type::DateTime + register_class_with_limit m, %r(float)i, Type::Float + register_class_with_limit m, %r(int)i, Type::Integer + + m.alias_type %r(blob)i, "binary" + m.alias_type %r(clob)i, "text" + m.alias_type %r(timestamp)i, "datetime" + m.alias_type %r(numeric)i, "decimal" + m.alias_type %r(number)i, "decimal" + m.alias_type %r(double)i, "float" + + m.register_type(%r(decimal)i) do |sql_type| + scale = extract_scale(sql_type) + precision = extract_precision(sql_type) + + if scale == 0 + # FIXME: Remove this class as well + Type::DecimalWithoutScale.new(precision: precision) + else + Type::Decimal.new(precision: precision, scale: scale) + end end end - end - - def reload_type_map # :nodoc: - type_map.clear - initialize_type_map(type_map) - end - def register_class_with_limit(mapping, key, klass) # :nodoc: - mapping.register_type(key) do |*args| - limit = extract_limit(args.last) - klass.new(limit: limit) + def reload_type_map # :nodoc: + type_map.clear + initialize_type_map(type_map) end - end - def register_class_with_precision(mapping, key, klass) # :nodoc: - mapping.register_type(key) do |*args| - precision = extract_precision(args.last) - klass.new(precision: precision) + def register_class_with_limit(mapping, key, klass) # :nodoc: + mapping.register_type(key) do |*args| + limit = extract_limit(args.last) + klass.new(limit: limit) + end end - end - def extract_scale(sql_type) # :nodoc: - case sql_type - when /\((\d+)\)/ then 0 - when /\((\d+)(,(\d+))\)/ then $3.to_i + def register_class_with_precision(mapping, key, klass) # :nodoc: + mapping.register_type(key) do |*args| + precision = extract_precision(args.last) + klass.new(precision: precision) + end end - end - def extract_precision(sql_type) # :nodoc: - $1.to_i if sql_type =~ /\((\d+)(,\d+)?\)/ - end + def extract_scale(sql_type) # :nodoc: + case sql_type + when /\((\d+)\)/ then 0 + when /\((\d+)(,(\d+))\)/ then $3.to_i + end + end - def extract_limit(sql_type) # :nodoc: - case sql_type - when /^bigint/i - 8 - when /\((.*)\)/ - $1.to_i + def extract_precision(sql_type) # :nodoc: + $1.to_i if sql_type =~ /\((\d+)(,\d+)?\)/ end - end - def translate_exception_class(e, sql) - begin - message = "#{e.class.name}: #{e.message}: #{sql}" - rescue Encoding::CompatibilityError - message = "#{e.class.name}: #{e.message.force_encoding sql.encoding}: #{sql}" + def extract_limit(sql_type) # :nodoc: + case sql_type + when /^bigint/i + 8 + when /\((.*)\)/ + $1.to_i + end end - exception = translate_exception(e, message) - exception.set_backtrace e.backtrace - exception - end + def translate_exception_class(e, sql) + begin + message = "#{e.class.name}: #{e.message}: #{sql}" + rescue Encoding::CompatibilityError + message = "#{e.class.name}: #{e.message.force_encoding sql.encoding}: #{sql}" + end - def log(sql, name = "SQL", binds = [], type_casted_binds = [], statement_name = nil) - @instrumenter.instrument( - "sql.active_record", - sql: sql, - name: name, - binds: binds, - type_casted_binds: type_casted_binds, - statement_name: statement_name, - connection_id: object_id) { yield } - rescue => e - raise translate_exception_class(e, sql) - end + exception = translate_exception(e, message) + exception.set_backtrace e.backtrace + exception + end - def translate_exception(exception, message) - # override in derived class - ActiveRecord::StatementInvalid.new(message) - end + def log(sql, name = "SQL", binds = [], type_casted_binds = [], statement_name = nil) + @instrumenter.instrument( + "sql.active_record", + sql: sql, + name: name, + binds: binds, + type_casted_binds: type_casted_binds, + statement_name: statement_name, + connection_id: object_id) { yield } + rescue => e + raise translate_exception_class(e, sql) + end - def without_prepared_statement?(binds) - !prepared_statements || binds.empty? - end + def translate_exception(exception, message) + # override in derived class + ActiveRecord::StatementInvalid.new(message) + end - def column_for(table_name, column_name) # :nodoc: - column_name = column_name.to_s - columns(table_name).detect { |c| c.name == column_name } || - raise(ActiveRecordError, "No such column: #{table_name}.#{column_name}") - end + def without_prepared_statement?(binds) + !prepared_statements || binds.empty? + end + + def column_for(table_name, column_name) # :nodoc: + column_name = column_name.to_s + columns(table_name).detect { |c| c.name == column_name } || + raise(ActiveRecordError, "No such column: #{table_name}.#{column_name}") + end end end end 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 8ac8996d21..bea8d8dda6 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb @@ -651,340 +651,340 @@ module ActiveRecord protected - def initialize_type_map(m) # :nodoc: - super - - register_class_with_limit m, %r(char)i, MysqlString - - m.register_type %r(tinytext)i, Type::Text.new(limit: 2**8 - 1) - m.register_type %r(tinyblob)i, Type::Binary.new(limit: 2**8 - 1) - m.register_type %r(text)i, Type::Text.new(limit: 2**16 - 1) - m.register_type %r(blob)i, Type::Binary.new(limit: 2**16 - 1) - m.register_type %r(mediumtext)i, Type::Text.new(limit: 2**24 - 1) - m.register_type %r(mediumblob)i, Type::Binary.new(limit: 2**24 - 1) - m.register_type %r(longtext)i, Type::Text.new(limit: 2**32 - 1) - m.register_type %r(longblob)i, Type::Binary.new(limit: 2**32 - 1) - m.register_type %r(^float)i, Type::Float.new(limit: 24) - m.register_type %r(^double)i, Type::Float.new(limit: 53) - m.register_type %r(^json)i, MysqlJson.new - - register_integer_type m, %r(^bigint)i, limit: 8 - register_integer_type m, %r(^int)i, limit: 4 - register_integer_type m, %r(^mediumint)i, limit: 3 - register_integer_type m, %r(^smallint)i, limit: 2 - register_integer_type m, %r(^tinyint)i, limit: 1 - - m.register_type %r(^tinyint\(1\))i, Type::Boolean.new if emulate_booleans - m.alias_type %r(year)i, "integer" - m.alias_type %r(bit)i, "binary" - - m.register_type(%r(enum)i) do |sql_type| - limit = sql_type[/^enum\((.+)\)/i, 1] - .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 - MysqlString.new(limit: limit) - end - end - - def register_integer_type(mapping, key, options) # :nodoc: - mapping.register_type(key) do |sql_type| - if /\bunsigned\z/ === sql_type - Type::UnsignedInteger.new(options) - else - Type::Integer.new(options) + def initialize_type_map(m) # :nodoc: + super + + register_class_with_limit m, %r(char)i, MysqlString + + m.register_type %r(tinytext)i, Type::Text.new(limit: 2**8 - 1) + m.register_type %r(tinyblob)i, Type::Binary.new(limit: 2**8 - 1) + m.register_type %r(text)i, Type::Text.new(limit: 2**16 - 1) + m.register_type %r(blob)i, Type::Binary.new(limit: 2**16 - 1) + m.register_type %r(mediumtext)i, Type::Text.new(limit: 2**24 - 1) + m.register_type %r(mediumblob)i, Type::Binary.new(limit: 2**24 - 1) + m.register_type %r(longtext)i, Type::Text.new(limit: 2**32 - 1) + m.register_type %r(longblob)i, Type::Binary.new(limit: 2**32 - 1) + m.register_type %r(^float)i, Type::Float.new(limit: 24) + m.register_type %r(^double)i, Type::Float.new(limit: 53) + m.register_type %r(^json)i, MysqlJson.new + + register_integer_type m, %r(^bigint)i, limit: 8 + register_integer_type m, %r(^int)i, limit: 4 + register_integer_type m, %r(^mediumint)i, limit: 3 + register_integer_type m, %r(^smallint)i, limit: 2 + register_integer_type m, %r(^tinyint)i, limit: 1 + + m.register_type %r(^tinyint\(1\))i, Type::Boolean.new if emulate_booleans + m.alias_type %r(year)i, "integer" + m.alias_type %r(bit)i, "binary" + + m.register_type(%r(enum)i) do |sql_type| + limit = sql_type[/^enum\((.+)\)/i, 1] + .split(",").map{|enum| enum.strip.length - 2}.max + MysqlString.new(limit: limit) end - end - end - def extract_precision(sql_type) - if /time/ === sql_type - super || 0 - else - super + m.register_type(%r(^set)i) do |sql_type| + limit = sql_type[/^set\((.+)\)/i, 1] + .split(",").map{|set| set.strip.length - 1}.sum - 1 + MysqlString.new(limit: limit) + end end - end - def fetch_type_metadata(sql_type, extra = "") - MySQL::TypeMetadata.new(super(sql_type), extra: extra, strict: strict_mode?) - end + def register_integer_type(mapping, key, options) # :nodoc: + mapping.register_type(key) do |sql_type| + if /\bunsigned\z/ === sql_type + Type::UnsignedInteger.new(options) + else + Type::Integer.new(options) + end + end + end - def add_index_length(option_strings, column_names, options = {}) - if options.is_a?(Hash) && length = options[:length] - case length - when Hash - column_names.each {|name| option_strings[name] += "(#{length[name]})" if length.has_key?(name) && length[name].present?} - when Integer - column_names.each {|name| option_strings[name] += "(#{length})"} + def extract_precision(sql_type) + if /time/ === sql_type + super || 0 + else + super end end - return option_strings - end + def fetch_type_metadata(sql_type, extra = "") + MySQL::TypeMetadata.new(super(sql_type), extra: extra, strict: strict_mode?) + end - def quoted_columns_for_index(column_names, options = {}) - option_strings = Hash[column_names.map {|name| [name, ""]}] + def add_index_length(option_strings, column_names, options = {}) + if options.is_a?(Hash) && length = options[:length] + case length + when Hash + column_names.each {|name| option_strings[name] += "(#{length[name]})" if length.has_key?(name) && length[name].present?} + when Integer + column_names.each {|name| option_strings[name] += "(#{length})"} + end + end - # add index length - option_strings = add_index_length(option_strings, column_names, options) + return option_strings + end - # add index sort order - option_strings = add_index_sort_order(option_strings, column_names, options) + def quoted_columns_for_index(column_names, options = {}) + option_strings = Hash[column_names.map {|name| [name, ""]}] - column_names.map {|name| quote_column_name(name) + option_strings[name]} - end + # 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]} + end # 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 - ER_LOCK_DEADLOCK = 1213 - - def translate_exception(exception, message) - case error_number(exception) - when ER_DUP_ENTRY - RecordNotUnique.new(message) - when ER_NO_REFERENCED_ROW_2 - InvalidForeignKey.new(message) - when ER_DATA_TOO_LONG - ValueTooLong.new(message) - when ER_LOCK_DEADLOCK - Deadlocked.new(message) - else - super + ER_DUP_ENTRY = 1062 + ER_NO_REFERENCED_ROW_2 = 1452 + ER_DATA_TOO_LONG = 1406 + ER_LOCK_DEADLOCK = 1213 + + def translate_exception(exception, message) + case error_number(exception) + when ER_DUP_ENTRY + RecordNotUnique.new(message) + when ER_NO_REFERENCED_ROW_2 + InvalidForeignKey.new(message) + when ER_DATA_TOO_LONG + ValueTooLong.new(message) + when ER_LOCK_DEADLOCK + Deadlocked.new(message) + else + super + end end - end - def add_column_sql(table_name, column_name, type, options = {}) - td = create_table_definition(table_name) - cd = td.new_column_definition(column_name, type, options) - schema_creation.accept(AddColumnDefinition.new(cd)) - end + def add_column_sql(table_name, column_name, type, options = {}) + td = create_table_definition(table_name) + cd = td.new_column_definition(column_name, type, options) + schema_creation.accept(AddColumnDefinition.new(cd)) + end - def change_column_sql(table_name, column_name, type, options = {}) - column = column_for(table_name, column_name) + def change_column_sql(table_name, column_name, type, options = {}) + column = column_for(table_name, column_name) - unless options_include_default?(options) - options[:default] = column.default - end + unless options_include_default?(options) + options[:default] = column.default + end - unless options.has_key?(:null) - options[:null] = column.null - end + unless options.has_key?(:null) + options[:null] = column.null + end - td = create_table_definition(table_name) - cd = td.new_column_definition(column.name, type, options) - schema_creation.accept(ChangeColumnDefinition.new(cd, column.name)) - end + td = create_table_definition(table_name) + cd = td.new_column_definition(column.name, type, options) + schema_creation.accept(ChangeColumnDefinition.new(cd, column.name)) + end - def rename_column_sql(table_name, column_name, new_column_name) - column = column_for(table_name, column_name) - options = { - default: column.default, - null: column.null, - auto_increment: column.auto_increment? - } + def rename_column_sql(table_name, column_name, new_column_name) + column = column_for(table_name, column_name) + options = { + default: column.default, + null: column.null, + auto_increment: column.auto_increment? + } - current_type = select_one("SHOW COLUMNS FROM #{quote_table_name(table_name)} LIKE '#{column_name}'", "SCHEMA")["Type"] - td = create_table_definition(table_name) - cd = td.new_column_definition(new_column_name, current_type, options) - schema_creation.accept(ChangeColumnDefinition.new(cd, column.name)) - end + current_type = select_one("SHOW COLUMNS FROM #{quote_table_name(table_name)} LIKE '#{column_name}'", "SCHEMA")["Type"] + td = create_table_definition(table_name) + cd = td.new_column_definition(new_column_name, current_type, options) + schema_creation.accept(ChangeColumnDefinition.new(cd, column.name)) + end - def remove_column_sql(table_name, column_name, type = nil, options = {}) - "DROP #{quote_column_name(column_name)}" - end + def remove_column_sql(table_name, column_name, type = nil, options = {}) + "DROP #{quote_column_name(column_name)}" + end - def remove_columns_sql(table_name, *column_names) - column_names.map {|column_name| remove_column_sql(table_name, column_name) } - end + def remove_columns_sql(table_name, *column_names) + column_names.map {|column_name| remove_column_sql(table_name, column_name) } + end - def add_index_sql(table_name, column_name, options = {}) - index_name, index_type, index_columns, _, index_algorithm, index_using = add_index_options(table_name, column_name, options) - index_algorithm[0, 0] = ", " if index_algorithm.present? - "ADD #{index_type} INDEX #{quote_column_name(index_name)} #{index_using} (#{index_columns})#{index_algorithm}" - end + def add_index_sql(table_name, column_name, options = {}) + index_name, index_type, index_columns, _, index_algorithm, index_using = add_index_options(table_name, column_name, options) + index_algorithm[0, 0] = ", " if index_algorithm.present? + "ADD #{index_type} INDEX #{quote_column_name(index_name)} #{index_using} (#{index_columns})#{index_algorithm}" + end - def remove_index_sql(table_name, options = {}) - index_name = index_name_for_remove(table_name, options) - "DROP INDEX #{index_name}" - end + def remove_index_sql(table_name, options = {}) + index_name = index_name_for_remove(table_name, options) + "DROP INDEX #{index_name}" + end - def add_timestamps_sql(table_name, options = {}) - [add_column_sql(table_name, :created_at, :datetime, options), add_column_sql(table_name, :updated_at, :datetime, options)] - end + def add_timestamps_sql(table_name, options = {}) + [add_column_sql(table_name, :created_at, :datetime, options), add_column_sql(table_name, :updated_at, :datetime, options)] + end - def remove_timestamps_sql(table_name, options = {}) - [remove_column_sql(table_name, :updated_at), remove_column_sql(table_name, :created_at)] - end + def remove_timestamps_sql(table_name, options = {}) + [remove_column_sql(table_name, :updated_at), remove_column_sql(table_name, :created_at)] + end private # MySQL is too stupid to create a temporary table for use subquery, so we have # to give it some prompting in the form of a subsubquery. Ugh! - def subquery_for(key, select) - subsubselect = select.clone - subsubselect.projections = [key] + def subquery_for(key, select) + subsubselect = select.clone + subsubselect.projections = [key] - # Materialize subquery by adding distinct - # to work with MySQL 5.7.6 which sets optimizer_switch='derived_merge=on' - subsubselect.distinct unless select.limit || select.offset || select.orders.any? + # Materialize subquery by adding distinct + # to work with MySQL 5.7.6 which sets optimizer_switch='derived_merge=on' + subsubselect.distinct unless select.limit || select.offset || select.orders.any? - subselect = Arel::SelectManager.new(select.engine) - subselect.project Arel.sql(key.name) - subselect.from subsubselect.as("__active_record_temp") - end + subselect = Arel::SelectManager.new(select.engine) + subselect.project Arel.sql(key.name) + subselect.from subsubselect.as("__active_record_temp") + end - def supports_rename_index? - mariadb? ? false : version >= "5.7.6" - end + def supports_rename_index? + mariadb? ? false : version >= "5.7.6" + end - def configure_connection - variables = @config.fetch(:variables, {}).stringify_keys + def configure_connection + variables = @config.fetch(:variables, {}).stringify_keys - # By default, MySQL 'where id is null' selects the last inserted id; Turn this off. - variables["sql_auto_is_null"] = 0 + # By default, MySQL 'where id is null' selects the last inserted id; Turn this off. + variables["sql_auto_is_null"] = 0 - # Increase timeout so the server doesn't disconnect us. - wait_timeout = @config[:wait_timeout] - wait_timeout = 2147483 unless wait_timeout.is_a?(Integer) - variables["wait_timeout"] = self.class.type_cast_config_to_integer(wait_timeout) + # Increase timeout so the server doesn't disconnect us. + wait_timeout = @config[:wait_timeout] + wait_timeout = 2147483 unless wait_timeout.is_a?(Integer) + variables["wait_timeout"] = self.class.type_cast_config_to_integer(wait_timeout) - defaults = [":default", :default].to_set + defaults = [":default", :default].to_set - # Make MySQL reject illegal values rather than truncating or blanking them, see - # http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_strict_all_tables - # If the user has provided another value for sql_mode, don't replace it. - if sql_mode = variables.delete("sql_mode") - sql_mode = quote(sql_mode) - elsif !defaults.include?(strict_mode?) - if strict_mode? - sql_mode = "CONCAT(@@sql_mode, ',STRICT_ALL_TABLES')" - else - sql_mode = "REPLACE(@@sql_mode, 'STRICT_TRANS_TABLES', '')" - sql_mode = "REPLACE(#{sql_mode}, 'STRICT_ALL_TABLES', '')" - sql_mode = "REPLACE(#{sql_mode}, 'TRADITIONAL', '')" + # Make MySQL reject illegal values rather than truncating or blanking them, see + # http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_strict_all_tables + # If the user has provided another value for sql_mode, don't replace it. + if sql_mode = variables.delete("sql_mode") + sql_mode = quote(sql_mode) + elsif !defaults.include?(strict_mode?) + if strict_mode? + sql_mode = "CONCAT(@@sql_mode, ',STRICT_ALL_TABLES')" + else + sql_mode = "REPLACE(@@sql_mode, 'STRICT_TRANS_TABLES', '')" + sql_mode = "REPLACE(#{sql_mode}, 'STRICT_ALL_TABLES', '')" + sql_mode = "REPLACE(#{sql_mode}, 'TRADITIONAL', '')" + end + sql_mode = "CONCAT(#{sql_mode}, ',NO_AUTO_VALUE_ON_ZERO')" end - sql_mode = "CONCAT(#{sql_mode}, ',NO_AUTO_VALUE_ON_ZERO')" - end - sql_mode_assignment = "@@SESSION.sql_mode = #{sql_mode}, " if sql_mode - - # NAMES does not have an equals sign, see - # http://dev.mysql.com/doc/refman/5.7/en/set-statement.html#id944430 - # (trailing comma because variable_assignments will always have content) - if @config[:encoding] - encoding = "NAMES #{@config[:encoding]}" - encoding << " COLLATE #{@config[:collation]}" if @config[:collation] - encoding << ", " - end - - # Gather up all of the SET variables... - variable_assignments = variables.map do |k, v| - if defaults.include?(v) - "@@SESSION.#{k} = DEFAULT" # Sets the value to the global or compile default - elsif !v.nil? - "@@SESSION.#{k} = #{quote(v)}" + sql_mode_assignment = "@@SESSION.sql_mode = #{sql_mode}, " if sql_mode + + # NAMES does not have an equals sign, see + # http://dev.mysql.com/doc/refman/5.7/en/set-statement.html#id944430 + # (trailing comma because variable_assignments will always have content) + if @config[:encoding] + encoding = "NAMES #{@config[:encoding]}" + encoding << " COLLATE #{@config[:collation]}" if @config[:collation] + encoding << ", " end - # or else nil; compact to clear nils out - end.compact.join(", ") - # ...and send them all in one query - @connection.query "SET #{encoding} #{sql_mode_assignment} #{variable_assignments}" - end + # Gather up all of the SET variables... + variable_assignments = variables.map do |k, v| + if defaults.include?(v) + "@@SESSION.#{k} = DEFAULT" # Sets the value to the global or compile default + elsif !v.nil? + "@@SESSION.#{k} = #{quote(v)}" + end + # or else nil; compact to clear nils out + end.compact.join(", ") - def column_definitions(table_name) # :nodoc: - execute_and_free("SHOW FULL FIELDS FROM #{quote_table_name(table_name)}", "SCHEMA") do |result| - each_hash(result) + # ...and send them all in one query + @connection.query "SET #{encoding} #{sql_mode_assignment} #{variable_assignments}" end - end - def extract_foreign_key_action(specifier) # :nodoc: - case specifier - when "CASCADE"; :cascade - when "SET NULL"; :nullify + def column_definitions(table_name) # :nodoc: + execute_and_free("SHOW FULL FIELDS FROM #{quote_table_name(table_name)}", "SCHEMA") do |result| + each_hash(result) + end end - end - - def create_table_info(table_name) # :nodoc: - select_one("SHOW CREATE TABLE #{quote_table_name(table_name)}")["Create Table"] - end - def create_table_definition(*args) # :nodoc: - MySQL::TableDefinition.new(*args) - end + def extract_foreign_key_action(specifier) # :nodoc: + case specifier + when "CASCADE"; :cascade + when "SET NULL"; :nullify + end + end - def extract_schema_qualified_name(string) # :nodoc: - schema, name = string.to_s.scan(/[^`.\s]+|`[^`]*`/) - schema, name = @config[:database], schema unless name - [schema, name] - end + def create_table_info(table_name) # :nodoc: + select_one("SHOW CREATE TABLE #{quote_table_name(table_name)}")["Create Table"] + end - def integer_to_sql(limit) # :nodoc: - case limit - when 1; "tinyint" - when 2; "smallint" - when 3; "mediumint" - when nil, 4; "int" - when 5..8; "bigint" - else raise(ActiveRecordError, "No integer type has byte size #{limit}") + def create_table_definition(*args) # :nodoc: + MySQL::TableDefinition.new(*args) end - end - def text_to_sql(limit) # :nodoc: - case limit - when 0..0xff; "tinytext" - when nil, 0x100..0xffff; "text" - when 0x10000..0xffffff; "mediumtext" - when 0x1000000..0xffffffff; "longtext" - else raise(ActiveRecordError, "No text type has byte length #{limit}") + def extract_schema_qualified_name(string) # :nodoc: + schema, name = string.to_s.scan(/[^`.\s]+|`[^`]*`/) + schema, name = @config[:database], schema unless name + [schema, name] end - end - def binary_to_sql(limit) # :nodoc: - case limit - when 0..0xff; "tinyblob" - when nil, 0x100..0xffff; "blob" - when 0x10000..0xffffff; "mediumblob" - when 0x1000000..0xffffffff; "longblob" - else raise(ActiveRecordError, "No binary type has byte length #{limit}") + def integer_to_sql(limit) # :nodoc: + case limit + when 1; "tinyint" + when 2; "smallint" + when 3; "mediumint" + when nil, 4; "int" + when 5..8; "bigint" + else raise(ActiveRecordError, "No integer type has byte size #{limit}") + end end - end - class MysqlJson < Type::Internal::AbstractJson # :nodoc: - def changed_in_place?(raw_old_value, new_value) - # Normalization is required because MySQL JSON data format includes - # the space between the elements. - super(serialize(deserialize(raw_old_value)), new_value) + def text_to_sql(limit) # :nodoc: + case limit + when 0..0xff; "tinytext" + when nil, 0x100..0xffff; "text" + when 0x10000..0xffffff; "mediumtext" + when 0x1000000..0xffffffff; "longtext" + else raise(ActiveRecordError, "No text type has byte length #{limit}") + end end - end - class MysqlString < Type::String # :nodoc: - def serialize(value) - case value - when true then MySQL::Quoting::QUOTED_TRUE - when false then MySQL::Quoting::QUOTED_FALSE - else super + def binary_to_sql(limit) # :nodoc: + case limit + when 0..0xff; "tinyblob" + when nil, 0x100..0xffff; "blob" + when 0x10000..0xffffff; "mediumblob" + when 0x1000000..0xffffffff; "longblob" + else raise(ActiveRecordError, "No binary type has byte length #{limit}") end end - private + class MysqlJson < Type::Internal::AbstractJson # :nodoc: + def changed_in_place?(raw_old_value, new_value) + # Normalization is required because MySQL JSON data format includes + # the space between the elements. + super(serialize(deserialize(raw_old_value)), new_value) + end + end - def cast_value(value) - case value - when true then MySQL::Quoting::QUOTED_TRUE - when false then MySQL::Quoting::QUOTED_FALSE - else super + class MysqlString < Type::String # :nodoc: + def serialize(value) + case value + when true then MySQL::Quoting::QUOTED_TRUE + when false then MySQL::Quoting::QUOTED_FALSE + else super + end end + + private + + def cast_value(value) + case value + when true then MySQL::Quoting::QUOTED_TRUE + when false then MySQL::Quoting::QUOTED_FALSE + else super + end + end end - end - ActiveRecord::Type.register(:json, MysqlJson, adapter: :mysql2) - ActiveRecord::Type.register(:string, MysqlString, adapter: :mysql2) - ActiveRecord::Type.register(:unsigned_integer, Type::UnsignedInteger, adapter: :mysql2) + ActiveRecord::Type.register(:json, MysqlJson, adapter: :mysql2) + ActiveRecord::Type.register(:string, MysqlString, adapter: :mysql2) + ActiveRecord::Type.register(:unsigned_integer, Type::UnsignedInteger, adapter: :mysql2) end end end diff --git a/activerecord/lib/active_record/connection_adapters/column.rb b/activerecord/lib/active_record/connection_adapters/column.rb index 28f0c8686a..1808173592 100644 --- a/activerecord/lib/active_record/connection_adapters/column.rb +++ b/activerecord/lib/active_record/connection_adapters/column.rb @@ -52,9 +52,9 @@ module ActiveRecord protected - def attributes_for_hash - [self.class, name, default, sql_type_metadata, null, table_name, default_function, collation] - end + def attributes_for_hash + [self.class, name, default, sql_type_metadata, null, table_name, default_function, collation] + end end class NullColumn < Column diff --git a/activerecord/lib/active_record/connection_adapters/connection_specification.rb b/activerecord/lib/active_record/connection_adapters/connection_specification.rb index 996075e08a..c0c7ce46b2 100644 --- a/activerecord/lib/active_record/connection_adapters/connection_specification.rb +++ b/activerecord/lib/active_record/connection_adapters/connection_specification.rb @@ -56,13 +56,13 @@ module ActiveRecord private - def uri - @uri - end + def uri + @uri + end - def uri_parser - @uri_parser ||= URI::Parser.new - end + def uri_parser + @uri_parser ||= URI::Parser.new + end # Converts the query parameters of the URI into a hash. # @@ -73,39 +73,39 @@ module ActiveRecord # # "localhost" # # => {} - def query_hash - Hash[(@query || "").split("&").map { |pair| pair.split("=") }] - end + def query_hash + Hash[(@query || "").split("&").map { |pair| pair.split("=") }] + end - def raw_config - if uri.opaque - query_hash.merge( "adapter" => @adapter, - "database" => uri.opaque) - else - query_hash.merge( "adapter" => @adapter, - "username" => uri.user, - "password" => uri.password, - "port" => uri.port, - "database" => database_from_path, - "host" => uri.hostname) + def raw_config + if uri.opaque + query_hash.merge( "adapter" => @adapter, + "database" => uri.opaque) + else + query_hash.merge( "adapter" => @adapter, + "username" => uri.user, + "password" => uri.password, + "port" => uri.port, + "database" => database_from_path, + "host" => uri.hostname) + end end - end # Returns name of the database. - def database_from_path - if @adapter == "sqlite3" - # 'sqlite3:/foo' is absolute, because that makes sense. The - # corresponding relative version, 'sqlite3:foo', is handled - # elsewhere, as an "opaque". + def database_from_path + if @adapter == "sqlite3" + # 'sqlite3:/foo' is absolute, because that makes sense. The + # corresponding relative version, 'sqlite3:foo', is handled + # elsewhere, as an "opaque". - uri.path - else - # Only SQLite uses a filename as the "database" name; for - # anything else, a leading slash would be silly. + uri.path + else + # Only SQLite uses a filename as the "database" name; for + # anything else, a leading slash would be silly. - uri.path.sub(%r{^/}, "") + uri.path.sub(%r{^/}, "") + end end - end end ## @@ -211,16 +211,16 @@ module ActiveRecord # Resolver.new({}).resolve_connection("postgresql://localhost/foo") # # => { "host" => "localhost", "database" => "foo", "adapter" => "postgresql" } # - def resolve_connection(spec) - case spec - when Symbol - resolve_symbol_connection spec - when String - resolve_url_connection spec - when Hash - resolve_hash_connection spec + def resolve_connection(spec) + case spec + when Symbol + resolve_symbol_connection spec + when String + resolve_url_connection spec + when Hash + resolve_hash_connection spec + end end - end # Takes the environment such as +:production+ or +:development+. # This requires that the @configurations was initialized with a key that @@ -229,34 +229,34 @@ module ActiveRecord # Resolver.new("production" => {}).resolve_symbol_connection(:production) # # => {} # - def resolve_symbol_connection(spec) - if config = configurations[spec.to_s] - resolve_connection(config).merge("name" => spec.to_s) - else - raise(AdapterNotSpecified, "'#{spec}' database is not configured. Available: #{configurations.keys.inspect}") + def resolve_symbol_connection(spec) + if config = configurations[spec.to_s] + resolve_connection(config).merge("name" => spec.to_s) + else + raise(AdapterNotSpecified, "'#{spec}' database is not configured. Available: #{configurations.keys.inspect}") + end end - end # Accepts a hash. Expands the "url" key that contains a # URL database connection to a full connection # hash and merges with the rest of the hash. # Connection details inside of the "url" key win any merge conflicts - def resolve_hash_connection(spec) - if spec["url"] && spec["url"] !~ /^jdbc:/ - connection_hash = resolve_url_connection(spec.delete("url")) - spec.merge!(connection_hash) + def resolve_hash_connection(spec) + if spec["url"] && spec["url"] !~ /^jdbc:/ + connection_hash = resolve_url_connection(spec.delete("url")) + spec.merge!(connection_hash) + end + spec end - spec - end # Takes a connection URL. # # Resolver.new({}).resolve_url_connection("postgresql://localhost/foo") # # => { "host" => "localhost", "database" => "foo", "adapter" => "postgresql" } # - def resolve_url_connection(url) - ConnectionUrlResolver.new(url).to_hash - end + def resolve_url_connection(url) + ConnectionUrlResolver.new(url).to_hash + end end end end diff --git a/activerecord/lib/active_record/connection_adapters/mysql/column.rb b/activerecord/lib/active_record/connection_adapters/mysql/column.rb index cb068a61c7..5452e44c84 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql/column.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql/column.rb @@ -32,11 +32,11 @@ module ActiveRecord private - def extract_default - if blob_or_text_column? - @default = null || strict ? nil : "" + def extract_default + if blob_or_text_column? + @default = null || strict ? nil : "" + end end - end end end end diff --git a/activerecord/lib/active_record/connection_adapters/mysql/database_statements.rb b/activerecord/lib/active_record/connection_adapters/mysql/database_statements.rb index cd606d11a7..c8238eb266 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql/database_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql/database_statements.rb @@ -56,56 +56,56 @@ module ActiveRecord protected - def last_inserted_id(result) - @connection.last_id - end + def last_inserted_id(result) + @connection.last_id + end private - def select_result(sql, name = nil, binds = []) - if without_prepared_statement?(binds) - execute_and_free(sql, name) { |result| yield result } - else - exec_stmt_and_free(sql, name, binds, cache_stmt: true) { |_, result| yield result } - end - end - - def exec_stmt_and_free(sql, name, binds, cache_stmt: false) - if @connection - # make sure we carry over any changes to ActiveRecord::Base.default_timezone that have been - # made since we established the connection - @connection.query_options[:database_timezone] = ActiveRecord::Base.default_timezone + def select_result(sql, name = nil, binds = []) + if without_prepared_statement?(binds) + execute_and_free(sql, name) { |result| yield result } + else + exec_stmt_and_free(sql, name, binds, cache_stmt: true) { |_, result| yield result } + end end - type_casted_binds = type_casted_binds(binds) - - log(sql, name, binds, type_casted_binds) do - if cache_stmt - cache = @statements[sql] ||= { - stmt: @connection.prepare(sql) - } - stmt = cache[:stmt] - else - stmt = @connection.prepare(sql) + def exec_stmt_and_free(sql, name, binds, cache_stmt: false) + if @connection + # make sure we carry over any changes to ActiveRecord::Base.default_timezone that have been + # made since we established the connection + @connection.query_options[:database_timezone] = ActiveRecord::Base.default_timezone end - begin - result = stmt.execute(*type_casted_binds) - rescue Mysql2::Error => e + type_casted_binds = type_casted_binds(binds) + + log(sql, name, binds, type_casted_binds) do if cache_stmt - @statements.delete(sql) + cache = @statements[sql] ||= { + stmt: @connection.prepare(sql) + } + stmt = cache[:stmt] else - stmt.close + stmt = @connection.prepare(sql) + end + + begin + result = stmt.execute(*type_casted_binds) + rescue Mysql2::Error => e + if cache_stmt + @statements.delete(sql) + else + stmt.close + end + raise e end - raise e - end - ret = yield stmt, result - result.free if result - stmt.close unless cache_stmt - ret + ret = yield stmt, result + result.free if result + stmt.close unless cache_stmt + ret + end end - end end end end 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 5a6b33cb04..0b7dea232f 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 @@ -36,34 +36,34 @@ module ActiveRecord private - 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} - widths << cells_in_column.map(&:length).max + 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} + widths << cells_in_column.map(&:length).max + end end end - end - def build_separator(widths) - padding = 1 - "+" + widths.map {|w| "-" * (w + (padding*2))}.join("+") + "+" - end + def build_separator(widths) + padding = 1 + "+" + widths.map {|w| "-" * (w + (padding*2))}.join("+") + "+" + end - def build_cells(items, widths) - cells = [] - items.each_with_index do |item, i| - item = "NULL" if item.nil? - justifier = item.is_a?(Numeric) ? "rjust" : "ljust" - cells << item.to_s.send(justifier, widths[i]) + def build_cells(items, widths) + cells = [] + items.each_with_index do |item, i| + item = "NULL" if item.nil? + justifier = item.is_a?(Numeric) ? "rjust" : "ljust" + cells << item.to_s.send(justifier, widths[i]) + end + "| " + cells.join(" | ") + " |" end - "| " + cells.join(" | ") + " |" - end - def build_footer(nrows, elapsed) - rows_label = nrows == 1 ? "row" : "rows" - "#{nrows} #{rows_label} in set (%.2f sec)" % elapsed - end + def build_footer(nrows, elapsed) + rows_label = nrows == 1 ? "row" : "rows" + "#{nrows} #{rows_label} in set (%.2f sec)" % elapsed + end end end end diff --git a/activerecord/lib/active_record/connection_adapters/mysql/quoting.rb b/activerecord/lib/active_record/connection_adapters/mysql/quoting.rb index 381787868b..9d11ad28d4 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql/quoting.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql/quoting.rb @@ -38,13 +38,13 @@ module ActiveRecord private - def _quote(value) - if value.is_a?(Type::Binary::Data) - "x'#{value.hex}'" - else - super + def _quote(value) + if value.is_a?(Type::Binary::Data) + "x'#{value.hex}'" + else + super + end end - end end end end diff --git a/activerecord/lib/active_record/connection_adapters/mysql/schema_creation.rb b/activerecord/lib/active_record/connection_adapters/mysql/schema_creation.rb index fd2dc2aee8..d808b50332 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql/schema_creation.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql/schema_creation.rb @@ -7,60 +7,60 @@ module ActiveRecord private - def visit_DropForeignKey(name) - "DROP FOREIGN KEY #{name}" - end - - def visit_ColumnDefinition(o) - o.sql_type = type_to_sql(o.type, o.limit, o.precision, o.scale, o.unsigned) - super - end - - def visit_AddColumnDefinition(o) - add_column_position!(super, column_options(o.column)) - end + def visit_DropForeignKey(name) + "DROP FOREIGN KEY #{name}" + end - def visit_ChangeColumnDefinition(o) - change_column_sql = "CHANGE #{quote_column_name(o.name)} #{accept(o.column)}" - add_column_position!(change_column_sql, column_options(o.column)) - end + def visit_ColumnDefinition(o) + o.sql_type = type_to_sql(o.type, o.limit, o.precision, o.scale, o.unsigned) + super + end - def add_table_options!(create_sql, options) - add_sql_comment!(super, options[:comment]) - end + def visit_AddColumnDefinition(o) + add_column_position!(super, column_options(o.column)) + end - def column_options(o) - column_options = super - column_options[:charset] = o.charset - column_options - end + def visit_ChangeColumnDefinition(o) + change_column_sql = "CHANGE #{quote_column_name(o.name)} #{accept(o.column)}" + add_column_position!(change_column_sql, column_options(o.column)) + end - def add_column_options!(sql, options) - if charset = options[:charset] - sql << " CHARACTER SET #{charset}" + def add_table_options!(create_sql, options) + add_sql_comment!(super, options[:comment]) end - if collation = options[:collation] - sql << " COLLATE #{collation}" + def column_options(o) + column_options = super + column_options[:charset] = o.charset + column_options end - add_sql_comment!(super, options[:comment]) - end + def add_column_options!(sql, options) + if charset = options[:charset] + sql << " CHARACTER SET #{charset}" + end + + if collation = options[:collation] + sql << " COLLATE #{collation}" + end - def add_column_position!(sql, options) - if options[:first] - sql << " FIRST" - elsif options[:after] - sql << " AFTER #{quote_column_name(options[:after])}" + add_sql_comment!(super, options[:comment]) end - sql - end + def add_column_position!(sql, options) + if options[:first] + sql << " FIRST" + elsif options[:after] + sql << " AFTER #{quote_column_name(options[:after])}" + end - def index_in_create(table_name, column_name, options) - index_name, index_type, index_columns, _, _, index_using, comment = @conn.add_index_options(table_name, column_name, options) - add_sql_comment!("#{index_type} INDEX #{quote_column_name(index_name)} #{index_using} (#{index_columns})", comment) - end + sql + end + + def index_in_create(table_name, column_name, options) + index_name, index_type, index_columns, _, _, index_using, comment = @conn.add_index_options(table_name, column_name, options) + add_sql_comment!("#{index_type} INDEX #{quote_column_name(index_name)} #{index_using} (#{index_columns})", comment) + end end end end diff --git a/activerecord/lib/active_record/connection_adapters/mysql/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/mysql/schema_definitions.rb index 157e75dbf7..ce773ed75b 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql/schema_definitions.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql/schema_definitions.rb @@ -80,9 +80,9 @@ module ActiveRecord private - def create_column_definition(name, type) - MySQL::ColumnDefinition.new(name, type) - end + def create_column_definition(name, type) + MySQL::ColumnDefinition.new(name, type) + end end class Table < ActiveRecord::ConnectionAdapters::Table diff --git a/activerecord/lib/active_record/connection_adapters/mysql/schema_dumper.rb b/activerecord/lib/active_record/connection_adapters/mysql/schema_dumper.rb index 3e644f386f..39221eeb0c 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql/schema_dumper.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql/schema_dumper.rb @@ -25,29 +25,29 @@ module ActiveRecord private - def default_primary_key?(column) - super && column.auto_increment? - end + def default_primary_key?(column) + super && column.auto_increment? + end - def schema_type(column) - if column.sql_type == "tinyblob" - :blob - else - super + def schema_type(column) + if column.sql_type == "tinyblob" + :blob + else + super + end end - end - def schema_precision(column) - super unless /time/ === column.sql_type && column.precision == 0 - end + def schema_precision(column) + super unless /time/ === column.sql_type && column.precision == 0 + end - def schema_collation(column) - if column.collation && table_name = column.table_name - @table_collation_cache ||= {} - @table_collation_cache[table_name] ||= select_one("SHOW TABLE STATUS LIKE '#{table_name}'")["Collation"] - column.collation.inspect if column.collation != @table_collation_cache[table_name] + def schema_collation(column) + if column.collation && table_name = column.table_name + @table_collation_cache ||= {} + @table_collation_cache[table_name] ||= select_one("SHOW TABLE STATUS LIKE '#{table_name}'")["Collation"] + column.collation.inspect if column.collation != @table_collation_cache[table_name] + end end - end end end end diff --git a/activerecord/lib/active_record/connection_adapters/mysql/type_metadata.rb b/activerecord/lib/active_record/connection_adapters/mysql/type_metadata.rb index e1e3f7b472..1be5cb4740 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql/type_metadata.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql/type_metadata.rb @@ -23,9 +23,9 @@ module ActiveRecord protected - def attributes_for_hash - [self.class, @type_metadata, extra, strict] - end + def attributes_for_hash + [self.class, @type_metadata, extra, strict] + end end end end diff --git a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb index 154f0b2d3a..0130b4ef62 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb @@ -113,19 +113,19 @@ module ActiveRecord private - def connect - @connection = Mysql2::Client.new(@config) - configure_connection - end + def connect + @connection = Mysql2::Client.new(@config) + configure_connection + end - def configure_connection - @connection.query_options.merge!(as: :array) - super - end + def configure_connection + @connection.query_options.merge!(as: :array) + super + end - def full_version - @full_version ||= @connection.server_info[:version] - end + def full_version + @full_version ||= @connection.server_info[:version] + end end end end 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 b5a3340c18..87338986b9 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb @@ -169,9 +169,9 @@ module ActiveRecord private - def suppress_composite_primary_key(pk) - pk unless pk.is_a?(Array) - end + def suppress_composite_primary_key(pk) + pk unless pk.is_a?(Array) + end end end end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/array.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/array.rb index 9e0e6732c3..1a66afb23a 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/array.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/array.rb @@ -56,13 +56,13 @@ module ActiveRecord private - def type_cast_array(value, method) - if value.is_a?(::Array) - value.map { |item| type_cast_array(item, method) } - else - @subtype.public_send(method, value) + def type_cast_array(value, method) + if value.is_a?(::Array) + value.map { |item| type_cast_array(item, method) } + else + @subtype.public_send(method, value) + end end - end end end end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/bit.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/bit.rb index ea0fa2517f..a6b5a89ec0 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/bit.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/bit.rb @@ -43,7 +43,7 @@ module ActiveRecord protected - attr_reader :value + attr_reader :value end end end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/enum.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/enum.rb index 91d339f32c..950d23d516 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/enum.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/enum.rb @@ -9,9 +9,9 @@ module ActiveRecord private - def cast_value(value) - value.to_s - end + def cast_value(value) + value.to_s + end end end end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/hstore.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/hstore.rb index 2e55a5f8b8..2d3e6a925d 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/hstore.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/hstore.rb @@ -35,23 +35,23 @@ module ActiveRecord private - HstorePair = begin - quoted_string = /"[^"\\]*(?:\\.[^"\\]*)*"/ - unquoted_string = /(?:\\.|[^\s,])[^\s=,\\]*(?:\\.[^\s=,\\]*|=[^,>])*/ - /(#{quoted_string}|#{unquoted_string})\s*=>\s*(#{quoted_string}|#{unquoted_string})/ - end + HstorePair = begin + quoted_string = /"[^"\\]*(?:\\.[^"\\]*)*"/ + unquoted_string = /(?:\\.|[^\s,])[^\s=,\\]*(?:\\.[^\s=,\\]*|=[^,>])*/ + /(#{quoted_string}|#{unquoted_string})\s*=>\s*(#{quoted_string}|#{unquoted_string})/ + end - def escape_hstore(value) - if value.nil? - "NULL" - else - if value == "" - '""' + def escape_hstore(value) + if value.nil? + "NULL" else - '"%s"' % value.to_s.gsub(/(["\\])/, '\\\\\1') + if value == "" + '""' + else + '"%s"' % value.to_s.gsub(/(["\\])/, '\\\\\1') + end end end - end end end end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/point.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/point.rb index 3657f20433..bb4db2564c 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/point.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/point.rb @@ -33,9 +33,9 @@ module ActiveRecord private - def number_for_point(number) - number.to_s.gsub(/\.0$/, "") - end + def number_for_point(number) + number.to_s.gsub(/\.0$/, "") + end end end end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/rails_5_1_point.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/rails_5_1_point.rb index 3a52f05091..845ff5b6a9 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/rails_5_1_point.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/rails_5_1_point.rb @@ -15,7 +15,7 @@ module ActiveRecord case value when ::String return if value.blank? - + if value[0] == "(" && value[-1] == ")" value = value[1...-1] end @@ -38,13 +38,13 @@ module ActiveRecord private - def number_for_point(number) - number.to_s.gsub(/\.0$/, "") - end + def number_for_point(number) + number.to_s.gsub(/\.0$/, "") + end - def build_point(x, y) - ActiveRecord::Point.new(Float(x), Float(y)) - end + def build_point(x, y) + ActiveRecord::Point.new(Float(x), Float(y)) + end end end end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/range.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/range.rb index 58bf5c5640..2c714f4018 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/range.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/range.rb @@ -55,37 +55,37 @@ module ActiveRecord private - def type_cast_single(value) - infinity?(value) ? value : @subtype.deserialize(value) - end + def type_cast_single(value) + infinity?(value) ? value : @subtype.deserialize(value) + end - def type_cast_single_for_database(value) - infinity?(value) ? "" : @subtype.serialize(value) - end + def type_cast_single_for_database(value) + infinity?(value) ? "" : @subtype.serialize(value) + end - def extract_bounds(value) - from, to = value[1..-2].split(",") - { - from: (value[1] == "," || from == "-infinity") ? infinity(negative: true) : from, - to: (value[-2] == "," || to == "infinity") ? infinity : to, - exclude_start: (value[0] == "("), - exclude_end: (value[-1] == ")") - } - end + def extract_bounds(value) + from, to = value[1..-2].split(",") + { + from: (value[1] == "," || from == "-infinity") ? infinity(negative: true) : from, + to: (value[-2] == "," || to == "infinity") ? infinity : to, + exclude_start: (value[0] == "("), + exclude_end: (value[-1] == ")") + } + end - def infinity(negative: false) - if subtype.respond_to?(:infinity) - subtype.infinity(negative: negative) - elsif negative - -::Float::INFINITY - else - ::Float::INFINITY + def infinity(negative: false) + if subtype.respond_to?(:infinity) + subtype.infinity(negative: negative) + elsif negative + -::Float::INFINITY + else + ::Float::INFINITY + end end - end - def infinity?(value) - value.respond_to?(:infinite?) && value.infinite? - end + def infinity?(value) + value.respond_to?(:infinite?) && value.infinite? + end end end end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb index 3a75e8d69d..d9ae1aa7a2 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb @@ -42,66 +42,66 @@ module ActiveRecord end private - def register_mapped_type(row) - alias_type row["oid"], row["typname"] - end + def register_mapped_type(row) + alias_type row["oid"], row["typname"] + end - def register_enum_type(row) - register row["oid"], OID::Enum.new - end + def register_enum_type(row) + register row["oid"], OID::Enum.new + end - def register_array_type(row) - register_with_subtype(row["oid"], row["typelem"].to_i) do |subtype| - OID::Array.new(subtype, row["typdelim"]) + def register_array_type(row) + register_with_subtype(row["oid"], row["typelem"].to_i) do |subtype| + OID::Array.new(subtype, row["typdelim"]) + end end - end - def register_range_type(row) - register_with_subtype(row["oid"], row["rngsubtype"].to_i) do |subtype| - OID::Range.new(subtype, row["typname"].to_sym) + def register_range_type(row) + register_with_subtype(row["oid"], row["rngsubtype"].to_i) do |subtype| + OID::Range.new(subtype, row["typname"].to_sym) + end end - end - def register_domain_type(row) - if base_type = @store.lookup(row["typbasetype"].to_i) - register row["oid"], base_type - else - warn "unknown base type (OID: #{row["typbasetype"]}) for domain #{row["typname"]}." + def register_domain_type(row) + if base_type = @store.lookup(row["typbasetype"].to_i) + register row["oid"], base_type + else + warn "unknown base type (OID: #{row["typbasetype"]}) for domain #{row["typname"]}." + end end - end - def register_composite_type(row) - if subtype = @store.lookup(row["typelem"].to_i) - register row["oid"], OID::Vector.new(row["typdelim"], subtype) + def register_composite_type(row) + if subtype = @store.lookup(row["typelem"].to_i) + register row["oid"], OID::Vector.new(row["typdelim"], subtype) + end end - end - def register(oid, oid_type = nil, &block) - oid = assert_valid_registration(oid, oid_type || block) - if block_given? - @store.register_type(oid, &block) - else - @store.register_type(oid, oid_type) + def register(oid, oid_type = nil, &block) + oid = assert_valid_registration(oid, oid_type || block) + if block_given? + @store.register_type(oid, &block) + else + @store.register_type(oid, oid_type) + end end - end - def alias_type(oid, target) - oid = assert_valid_registration(oid, target) - @store.alias_type(oid, target) - end + def alias_type(oid, target) + oid = assert_valid_registration(oid, target) + @store.alias_type(oid, target) + end - def register_with_subtype(oid, target_oid) - if @store.key?(target_oid) - register(oid) do |_, *args| - yield @store.lookup(target_oid, *args) + def register_with_subtype(oid, target_oid) + if @store.key?(target_oid) + register(oid) do |_, *args| + yield @store.lookup(target_oid, *args) + end end end - end - def assert_valid_registration(oid, oid_type) - raise ArgumentError, "can't register nil type for OID #{oid}" if oid_type.nil? - oid.to_i - end + def assert_valid_registration(oid, oid_type) + raise ArgumentError, "can't register nil type for OID #{oid}" if oid_type.nil? + oid.to_i + end end end end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb b/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb index 90e88b1f3c..b5031d890f 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb @@ -74,42 +74,42 @@ module ActiveRecord private - def _quote(value) - case value - when Type::Binary::Data - "'#{escape_bytea(value.to_s)}'" - when OID::Xml::Data - "xml '#{quote_string(value.to_s)}'" - when OID::Bit::Data - if value.binary? - "B'#{value}'" - elsif value.hex? - "X'#{value}'" - end - when Float - if value.infinite? || value.nan? - "'#{value}'" + def _quote(value) + case value + when Type::Binary::Data + "'#{escape_bytea(value.to_s)}'" + when OID::Xml::Data + "xml '#{quote_string(value.to_s)}'" + when OID::Bit::Data + if value.binary? + "B'#{value}'" + elsif value.hex? + "X'#{value}'" + end + when Float + if value.infinite? || value.nan? + "'#{value}'" + else + super + end else super end - else - super end - end - def _type_cast(value) - case value - when Type::Binary::Data - # Return a bind param hash with format as binary. - # See http://deveiate.org/code/pg/PGconn.html#method-i-exec_prepared-doc - # for more information - { value: value.to_s, format: 1 } - when OID::Xml::Data, OID::Bit::Data - value.to_s - else - super + def _type_cast(value) + case value + when Type::Binary::Data + # Return a bind param hash with format as binary. + # See http://deveiate.org/code/pg/PGconn.html#method-i-exec_prepared-doc + # for more information + { value: value.to_s, format: 1 } + when OID::Xml::Data, OID::Bit::Data + value.to_s + else + super + end end - end end end end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/schema_dumper.rb b/activerecord/lib/active_record/connection_adapters/postgresql/schema_dumper.rb index 2ed8f29b24..c20baf655c 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_dumper.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_dumper.rb @@ -24,23 +24,23 @@ module ActiveRecord private - def default_primary_key?(column) - schema_type(column) == :serial - end + def default_primary_key?(column) + schema_type(column) == :serial + end - def schema_type(column) - return super unless column.serial? + def schema_type(column) + return super unless column.serial? - if column.bigint? - :bigserial - else - :serial + if column.bigint? + :bigserial + else + :serial + end end - end - def schema_expression(column) - super unless column.serial? - end + def schema_expression(column) + super unless column.serial? + end end end end 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 55c5fcafa6..56280f15e9 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb @@ -6,17 +6,17 @@ module ActiveRecord class SchemaCreation < AbstractAdapter::SchemaCreation private - def visit_ColumnDefinition(o) - o.sql_type = type_to_sql(o.type, o.limit, o.precision, o.scale, o.array) - super - end + def visit_ColumnDefinition(o) + o.sql_type = type_to_sql(o.type, o.limit, o.precision, o.scale, o.array) + super + end - def add_column_options!(sql, options) - if options[:collation] - sql << " COLLATE \"#{options[:collation]}\"" + def add_column_options!(sql, options) + if options[:collation] + sql << " COLLATE \"#{options[:collation]}\"" + end + super end - super - end end module SchemaStatements diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/type_metadata.rb b/activerecord/lib/active_record/connection_adapters/postgresql/type_metadata.rb index b2c49989a4..bcef8ac715 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/type_metadata.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/type_metadata.rb @@ -27,9 +27,9 @@ module ActiveRecord protected - def attributes_for_hash - [self.class, @type_metadata, oid, fmod] - end + def attributes_for_hash + [self.class, @type_metadata, oid, fmod] + end end end end diff --git a/activerecord/lib/active_record/connection_adapters/sql_type_metadata.rb b/activerecord/lib/active_record/connection_adapters/sql_type_metadata.rb index ccb7e154ee..9e12ae0de8 100644 --- a/activerecord/lib/active_record/connection_adapters/sql_type_metadata.rb +++ b/activerecord/lib/active_record/connection_adapters/sql_type_metadata.rb @@ -24,9 +24,9 @@ module ActiveRecord protected - def attributes_for_hash - [self.class, sql_type, type, limit, precision, scale] - end + def attributes_for_hash + [self.class, sql_type, type, limit, precision, scale] + end end end end diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3/quoting.rb b/activerecord/lib/active_record/connection_adapters/sqlite3/quoting.rb index fa20175b0e..f01ed67b0f 100644 --- a/activerecord/lib/active_record/connection_adapters/sqlite3/quoting.rb +++ b/activerecord/lib/active_record/connection_adapters/sqlite3/quoting.rb @@ -20,28 +20,28 @@ module ActiveRecord private - def _quote(value) - if value.is_a?(Type::Binary::Data) - "x'#{value.hex}'" - else - super + def _quote(value) + if value.is_a?(Type::Binary::Data) + "x'#{value.hex}'" + else + super + end end - end - def _type_cast(value) - case value - when BigDecimal - value.to_f - when String - if value.encoding == Encoding::ASCII_8BIT - super(value.encode(Encoding::UTF_8)) + def _type_cast(value) + case value + when BigDecimal + value.to_f + when String + if value.encoding == Encoding::ASCII_8BIT + super(value.encode(Encoding::UTF_8)) + else + super + end else super end - else - super end - end end end end diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb index 4558e1f80f..57699badba 100644 --- a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb @@ -70,9 +70,9 @@ module ActiveRecord class StatementPool < ConnectionAdapters::StatementPool private - def dealloc(stmt) - stmt[:stmt].close unless stmt[:stmt].closed? - end + def dealloc(stmt) + stmt[:stmt].close unless stmt[:stmt].closed? + end end def schema_creation # :nodoc: diff --git a/activerecord/lib/active_record/connection_adapters/statement_pool.rb b/activerecord/lib/active_record/connection_adapters/statement_pool.rb index 9b0ed3e08b..273b1b0b5c 100644 --- a/activerecord/lib/active_record/connection_adapters/statement_pool.rb +++ b/activerecord/lib/active_record/connection_adapters/statement_pool.rb @@ -47,13 +47,13 @@ module ActiveRecord private - def cache - @cache[Process.pid] - end + def cache + @cache[Process.pid] + end - def dealloc(stmt) - raise NotImplementedError - end + def dealloc(stmt) + raise NotImplementedError + end end end end diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb index 26a00e62d1..19a2720913 100644 --- a/activerecord/lib/active_record/core.rb +++ b/activerecord/lib/active_record/core.rb @@ -299,26 +299,26 @@ module ActiveRecord private - def cached_find_by_statement(key, &block) # :nodoc: - cache = @find_by_statement_cache[connection.prepared_statements] - cache[key] || cache.synchronize { - cache[key] ||= StatementCache.create(connection, &block) - } - end + def cached_find_by_statement(key, &block) # :nodoc: + cache = @find_by_statement_cache[connection.prepared_statements] + cache[key] || cache.synchronize { + cache[key] ||= StatementCache.create(connection, &block) + } + end - def relation # :nodoc: - relation = Relation.create(self, arel_table, predicate_builder) + def relation # :nodoc: + relation = Relation.create(self, arel_table, predicate_builder) - if finder_needs_type_condition? && !ignore_default_scope? - relation.where(type_condition).create_with(inheritance_column.to_sym => sti_name) - else - relation + if finder_needs_type_condition? && !ignore_default_scope? + relation.where(type_condition).create_with(inheritance_column.to_sym => sti_name) + else + relation + end end - end - def table_metadata # :nodoc: - TableMetadata.new(self, arel_table) - end + def table_metadata # :nodoc: + TableMetadata.new(self, arel_table) + end end # New objects can be instantiated as either empty (pass no construction parameter) or pre-set with @@ -498,11 +498,11 @@ 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| - if has_attribute?(name) - "#{name}: #{attribute_for_inspect(name)}" - end - }.compact.join(", ") + self.class.column_names.collect { |name| + if has_attribute?(name) + "#{name}: #{attribute_for_inspect(name)}" + end + }.compact.join(", ") else "not initialized" end @@ -548,32 +548,32 @@ module ActiveRecord # So we can avoid the method_missing hit by explicitly defining #to_ary as nil here. # # See also http://tenderlovemaking.com/2011/06/28/til-its-ok-to-return-nil-from-to_ary.html - def to_ary # :nodoc: - nil - end + def to_ary # :nodoc: + nil + end - def init_internals - @readonly = false - @destroyed = false - @marked_for_destruction = false - @destroyed_by_association = nil - @new_record = true - @txn = nil - @_start_transaction_state = {} - @transaction_state = nil - end + def init_internals + @readonly = false + @destroyed = false + @marked_for_destruction = false + @destroyed_by_association = nil + @new_record = true + @txn = nil + @_start_transaction_state = {} + @transaction_state = nil + end - def initialize_internals_callback - end + def initialize_internals_callback + end - def thaw - if frozen? - @attributes = @attributes.dup + def thaw + if frozen? + @attributes = @attributes.dup + end end - end - def custom_inspect_method_defined? - self.class.instance_method(:inspect).owner != ActiveRecord::Base.instance_method(:inspect).owner - end + def custom_inspect_method_defined? + self.class.instance_method(:inspect).owner != ActiveRecord::Base.instance_method(:inspect).owner + end end end diff --git a/activerecord/lib/active_record/dynamic_matchers.rb b/activerecord/lib/active_record/dynamic_matchers.rb index b41546064b..fd2fa7410a 100644 --- a/activerecord/lib/active_record/dynamic_matchers.rb +++ b/activerecord/lib/active_record/dynamic_matchers.rb @@ -13,111 +13,111 @@ module ActiveRecord private - def method_missing(name, *arguments, &block) - match = Method.match(self, name) + def method_missing(name, *arguments, &block) + match = Method.match(self, name) - if match && match.valid? - match.define - send(name, *arguments, &block) - else - super + if match && match.valid? + match.define + send(name, *arguments, &block) + else + super + end end - end - class Method - @matchers = [] + class Method + @matchers = [] - class << self - attr_reader :matchers + class << self + attr_reader :matchers - def match(model, name) - klass = matchers.find { |k| k.pattern.match?(name) } - klass.new(model, name) if klass - end + def match(model, name) + klass = matchers.find { |k| k.pattern.match?(name) } + klass.new(model, name) if klass + end - def pattern - @pattern ||= /\A#{prefix}_([_a-zA-Z]\w*)#{suffix}\Z/ - end + def pattern + @pattern ||= /\A#{prefix}_([_a-zA-Z]\w*)#{suffix}\Z/ + end - def prefix - raise NotImplementedError - end + def prefix + raise NotImplementedError + end - def suffix - "" + def suffix + "" + end end - end - attr_reader :model, :name, :attribute_names + attr_reader :model, :name, :attribute_names - def initialize(model, name) - @model = model - @name = name.to_s - @attribute_names = @name.match(self.class.pattern)[1].split("_and_") - @attribute_names.map! { |n| @model.attribute_aliases[n] || n } - end + def initialize(model, name) + @model = model + @name = name.to_s + @attribute_names = @name.match(self.class.pattern)[1].split("_and_") + @attribute_names.map! { |n| @model.attribute_aliases[n] || n } + end - def valid? - attribute_names.all? { |name| model.columns_hash[name] || model.reflect_on_aggregation(name.to_sym) } - end + def valid? + attribute_names.all? { |name| model.columns_hash[name] || model.reflect_on_aggregation(name.to_sym) } + end - def define - model.class_eval <<-CODE, __FILE__, __LINE__ + 1 + def define + model.class_eval <<-CODE, __FILE__, __LINE__ + 1 def self.#{name}(#{signature}) #{body} end CODE - end + end - private + private - def body - "#{finder}(#{attributes_hash})" - end + def body + "#{finder}(#{attributes_hash})" + end - # The parameters in the signature may have reserved Ruby words, in order - # to prevent errors, we start each param name with `_`. - def signature - attribute_names.map { |name| "_#{name}" }.join(", ") - end + # The parameters in the signature may have reserved Ruby words, in order + # to prevent errors, we start each param name with `_`. + def signature + attribute_names.map { |name| "_#{name}" }.join(", ") + end - # Given that the parameters starts with `_`, the finder needs to use the - # same parameter name. - def attributes_hash - "{" + attribute_names.map { |name| ":#{name} => _#{name}" }.join(",") + "}" - end + # Given that the parameters starts with `_`, the finder needs to use the + # same parameter name. + def attributes_hash + "{" + attribute_names.map { |name| ":#{name} => _#{name}" }.join(",") + "}" + end - def finder - raise NotImplementedError + def finder + raise NotImplementedError + end end - end - class FindBy < Method - Method.matchers << self + class FindBy < Method + Method.matchers << self - def self.prefix - "find_by" - end + def self.prefix + "find_by" + end - def finder - "find_by" + def finder + "find_by" + end end - end - class FindByBang < Method - Method.matchers << self + class FindByBang < Method + Method.matchers << self - def self.prefix - "find_by" - end + def self.prefix + "find_by" + end - def self.suffix - "!" - end + def self.suffix + "!" + end - def finder - "find_by!" + def finder + "find_by!" + end end - end end end diff --git a/activerecord/lib/active_record/enum.rb b/activerecord/lib/active_record/enum.rb index dcf1004879..73f122cfd7 100644 --- a/activerecord/lib/active_record/enum.rb +++ b/activerecord/lib/active_record/enum.rb @@ -142,7 +142,7 @@ module ActiveRecord protected - attr_reader :name, :mapping, :subtype + attr_reader :name, :mapping, :subtype end def enum(definitions) diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb index babff9c284..0dc64c8853 100644 --- a/activerecord/lib/active_record/fixtures.rb +++ b/activerecord/lib/active_record/fixtures.rb @@ -426,9 +426,9 @@ module ActiveRecord end def self.default_fixture_table_name(fixture_set_name, config = ActiveRecord::Base) # :nodoc: - "#{ config.table_name_prefix }"\ - "#{ fixture_set_name.tr('/', '_') }"\ - "#{ config.table_name_suffix }".to_sym + "#{ config.table_name_prefix }"\ + "#{ fixture_set_name.tr('/', '_') }"\ + "#{ config.table_name_suffix }".to_sym end def self.reset_cache @@ -494,18 +494,18 @@ module ActiveRecord private - def insert_class(class_names, name, klass) - # We only want to deal with AR objects. - if klass && klass < ActiveRecord::Base - class_names[name] = klass - else - class_names[name] = nil + def insert_class(class_names, name, klass) + # We only want to deal with AR objects. + if klass && klass < ActiveRecord::Base + class_names[name] = klass + else + class_names[name] = nil + end end - end - def default_fixture_model(fs_name, config) - ActiveRecord::FixtureSet.default_fixture_model_name(fs_name, config) - end + def default_fixture_model(fs_name, config) + ActiveRecord::FixtureSet.default_fixture_model_name(fs_name, config) + end end def self.create_fixtures(fixtures_directory, fixture_set_names, class_names = {}, config = ActiveRecord::Base) diff --git a/activerecord/lib/active_record/inheritance.rb b/activerecord/lib/active_record/inheritance.rb index 5863f622b5..4adcd7e65c 100644 --- a/activerecord/lib/active_record/inheritance.rb +++ b/activerecord/lib/active_record/inheritance.rb @@ -134,83 +134,83 @@ module ActiveRecord # Returns the class type of the record using the current module as a prefix. So descendants of # MyApp::Business::Account would appear as MyApp::Business::AccountSubclass. - def compute_type(type_name) - if type_name.match(/^::/) - # If the type is prefixed with a scope operator then we assume that - # the type_name is an absolute reference. - ActiveSupport::Dependencies.constantize(type_name) - else - # Build a list of candidates to search for - candidates = [] - name.scan(/::|$/) { candidates.unshift "#{$`}::#{type_name}" } - candidates << type_name - - candidates.each do |candidate| - constant = ActiveSupport::Dependencies.safe_constantize(candidate) - return constant if candidate == constant.to_s - end + def compute_type(type_name) + if type_name.match(/^::/) + # If the type is prefixed with a scope operator then we assume that + # the type_name is an absolute reference. + ActiveSupport::Dependencies.constantize(type_name) + else + # Build a list of candidates to search for + candidates = [] + name.scan(/::|$/) { candidates.unshift "#{$`}::#{type_name}" } + candidates << type_name - raise NameError.new("uninitialized constant #{candidates.first}", candidates.first) + candidates.each do |candidate| + constant = ActiveSupport::Dependencies.safe_constantize(candidate) + return constant if candidate == constant.to_s + end + + raise NameError.new("uninitialized constant #{candidates.first}", candidates.first) + end end - end private # Called by +instantiate+ to decide which class to use for a new # record instance. For single-table inheritance, we check the record # for a +type+ column and return the corresponding class. - def discriminate_class_for_record(record) - if using_single_table_inheritance?(record) - find_sti_class(record[inheritance_column]) - else - super + def discriminate_class_for_record(record) + if using_single_table_inheritance?(record) + find_sti_class(record[inheritance_column]) + else + super + end end - end - def using_single_table_inheritance?(record) - record[inheritance_column].present? && has_attribute?(inheritance_column) - end + def using_single_table_inheritance?(record) + record[inheritance_column].present? && has_attribute?(inheritance_column) + end - def find_sti_class(type_name) - type_name = base_class.type_for_attribute(inheritance_column).cast(type_name) - subclass = begin - if store_full_sti_class - ActiveSupport::Dependencies.constantize(type_name) - else - compute_type(type_name) + def find_sti_class(type_name) + type_name = base_class.type_for_attribute(inheritance_column).cast(type_name) + subclass = begin + if store_full_sti_class + ActiveSupport::Dependencies.constantize(type_name) + else + compute_type(type_name) + end + rescue NameError + raise SubclassNotFound, + "The single-table inheritance mechanism failed to locate the subclass: '#{type_name}'. " \ + "This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " \ + "Please rename this column if you didn't intend it to be used for storing the inheritance class " \ + "or overwrite #{name}.inheritance_column to use another column for that information." end - rescue NameError - raise SubclassNotFound, - "The single-table inheritance mechanism failed to locate the subclass: '#{type_name}'. " \ - "This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " \ - "Please rename this column if you didn't intend it to be used for storing the inheritance class " \ - "or overwrite #{name}.inheritance_column to use another column for that information." - end - unless subclass == self || descendants.include?(subclass) - raise SubclassNotFound, "Invalid single-table inheritance type: #{subclass.name} is not a subclass of #{name}" + unless subclass == self || descendants.include?(subclass) + raise SubclassNotFound, "Invalid single-table inheritance type: #{subclass.name} is not a subclass of #{name}" + end + subclass end - subclass - end - def type_condition(table = arel_table) - sti_column = arel_attribute(inheritance_column, table) - sti_names = ([self] + descendants).map(&:sti_name) + def type_condition(table = arel_table) + sti_column = arel_attribute(inheritance_column, table) + sti_names = ([self] + descendants).map(&:sti_name) - sti_column.in(sti_names) - end + sti_column.in(sti_names) + end # Detect the subclass from the inheritance column of attrs. If the inheritance column value # is not self or a valid subclass, raises ActiveRecord::SubclassNotFound - def subclass_from_attributes(attrs) - attrs = attrs.to_h if attrs.respond_to?(:permitted?) - if attrs.is_a?(Hash) - subclass_name = attrs.with_indifferent_access[inheritance_column] - - if subclass_name.present? - find_sti_class(subclass_name) + def subclass_from_attributes(attrs) + attrs = attrs.to_h if attrs.respond_to?(:permitted?) + if attrs.is_a?(Hash) + subclass_name = attrs.with_indifferent_access[inheritance_column] + + if subclass_name.present? + find_sti_class(subclass_name) + end end end - end end def initialize_dup(other) @@ -220,21 +220,21 @@ module ActiveRecord private - def initialize_internals_callback - super - ensure_proper_type - end + def initialize_internals_callback + super + ensure_proper_type + end # Sets the attribute used for single table inheritance to this class name if this is not the # ActiveRecord::Base descendant. # Considering the hierarchy Reply < Message < ActiveRecord::Base, this makes it possible to # do Reply.new without having to set Reply[Reply.inheritance_column] = "Reply" yourself. # No such attribute would be set for objects of the Message class in that example. - def ensure_proper_type - klass = self.class - if klass.finder_needs_type_condition? - write_attribute(klass.inheritance_column, klass.sti_name) + def ensure_proper_type + klass = self.class + if klass.finder_needs_type_condition? + write_attribute(klass.inheritance_column, klass.sti_name) + end end - end end end diff --git a/activerecord/lib/active_record/locking/optimistic.rb b/activerecord/lib/active_record/locking/optimistic.rb index 5e519056a3..21a6a2c55f 100644 --- a/activerecord/lib/active_record/locking/optimistic.rb +++ b/activerecord/lib/active_record/locking/optimistic.rb @@ -132,56 +132,56 @@ module ActiveRecord relation end - module ClassMethods - DEFAULT_LOCKING_COLUMN = "lock_version" - - # Returns true if the +lock_optimistically+ flag is set to true - # (which it is, by default) and the table includes the - # +locking_column+ column (defaults to +lock_version+). - def locking_enabled? - lock_optimistically && columns_hash[locking_column] - end + module ClassMethods + DEFAULT_LOCKING_COLUMN = "lock_version" + + # Returns true if the +lock_optimistically+ flag is set to true + # (which it is, by default) and the table includes the + # +locking_column+ column (defaults to +lock_version+). + def locking_enabled? + lock_optimistically && columns_hash[locking_column] + end - # Set the column to use for optimistic locking. Defaults to +lock_version+. - def locking_column=(value) - reload_schema_from_cache - @locking_column = value.to_s - end + # Set the column to use for optimistic locking. Defaults to +lock_version+. + def locking_column=(value) + reload_schema_from_cache + @locking_column = value.to_s + end - # The version column used for optimistic locking. Defaults to +lock_version+. - def locking_column - @locking_column = DEFAULT_LOCKING_COLUMN unless defined?(@locking_column) - @locking_column - end + # The version column used for optimistic locking. Defaults to +lock_version+. + def locking_column + @locking_column = DEFAULT_LOCKING_COLUMN unless defined?(@locking_column) + @locking_column + end - # Reset the column used for optimistic locking back to the +lock_version+ default. - def reset_locking_column - self.locking_column = DEFAULT_LOCKING_COLUMN - end + # Reset the column used for optimistic locking back to the +lock_version+ default. + def reset_locking_column + self.locking_column = DEFAULT_LOCKING_COLUMN + end - # Make sure the lock version column gets updated when counters are - # updated. - def update_counters(id, counters) - counters = counters.merge(locking_column => 1) if locking_enabled? - super - end + # Make sure the lock version column gets updated when counters are + # updated. + def update_counters(id, counters) + counters = counters.merge(locking_column => 1) if locking_enabled? + super + end - private - - # We need to apply this decorator here, rather than on module inclusion. The closure - # created by the matcher would otherwise evaluate for `ActiveRecord::Base`, not the - # sub class being decorated. As such, changes to `lock_optimistically`, or - # `locking_column` would not be picked up. - def inherited(subclass) - subclass.class_eval do - is_lock_column = ->(name, _) { lock_optimistically && name == locking_column } - decorate_matching_attribute_types(is_lock_column, :_optimistic_locking) do |type| - LockingType.new(type) + private + + # We need to apply this decorator here, rather than on module inclusion. The closure + # created by the matcher would otherwise evaluate for `ActiveRecord::Base`, not the + # sub class being decorated. As such, changes to `lock_optimistically`, or + # `locking_column` would not be picked up. + def inherited(subclass) + subclass.class_eval do + is_lock_column = ->(name, _) { lock_optimistically && name == locking_column } + decorate_matching_attribute_types(is_lock_column, :_optimistic_locking) do |type| + LockingType.new(type) + end + end + super end - end - super end - end end diff --git a/activerecord/lib/active_record/log_subscriber.rb b/activerecord/lib/active_record/log_subscriber.rb index c4998ba686..bb9f898cf0 100644 --- a/activerecord/lib/active_record/log_subscriber.rb +++ b/activerecord/lib/active_record/log_subscriber.rb @@ -57,38 +57,38 @@ module ActiveRecord private - def colorize_payload_name(name, payload_name) - if payload_name.blank? || payload_name == "SQL" # SQL vs Model Load/Exists - color(name, MAGENTA, true) - else - color(name, CYAN, true) + def colorize_payload_name(name, payload_name) + if payload_name.blank? || payload_name == "SQL" # SQL vs Model Load/Exists + color(name, MAGENTA, true) + else + color(name, CYAN, true) + end end - end - def sql_color(sql) - case sql - when /\A\s*rollback/mi - RED - when /select .*for update/mi, /\A\s*lock/mi - WHITE - when /\A\s*select/i - BLUE - when /\A\s*insert/i - GREEN - when /\A\s*update/i - YELLOW - when /\A\s*delete/i - RED - when /transaction\s*\Z/i - CYAN - else - MAGENTA + def sql_color(sql) + case sql + when /\A\s*rollback/mi + RED + when /select .*for update/mi, /\A\s*lock/mi + WHITE + when /\A\s*select/i + BLUE + when /\A\s*insert/i + GREEN + when /\A\s*update/i + YELLOW + when /\A\s*delete/i + RED + when /transaction\s*\Z/i + CYAN + else + MAGENTA + end end - end - def logger - ActiveRecord::Base.logger - end + def logger + ActiveRecord::Base.logger + end end end diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb index 0066d30ca6..a8dbda118e 100644 --- a/activerecord/lib/active_record/migration.rb +++ b/activerecord/lib/active_record/migration.rb @@ -555,9 +555,9 @@ module ActiveRecord private - def connection - ActiveRecord::Base.connection - end + def connection + ActiveRecord::Base.connection + end end class << self @@ -922,13 +922,13 @@ module ActiveRecord end private - def execute_block - if connection.respond_to? :execute_block - super # use normal delegation to record the block - else - yield + def execute_block + if connection.respond_to? :execute_block + super # use normal delegation to record the block + else + yield + end end - end end # MigrationProxy is used to defer loading of the actual migration classes @@ -1166,145 +1166,145 @@ module ActiveRecord private # Used for running a specific migration. - def run_without_lock - migration = migrations.detect { |m| m.version == @target_version } - raise UnknownMigrationVersionError.new(@target_version) if migration.nil? - execute_migration_in_transaction(migration, @direction) + def run_without_lock + migration = migrations.detect { |m| m.version == @target_version } + raise UnknownMigrationVersionError.new(@target_version) if migration.nil? + execute_migration_in_transaction(migration, @direction) - record_environment - end + record_environment + end # Used for running multiple migrations up to or down to a certain value. - def migrate_without_lock - if invalid_target? - raise UnknownMigrationVersionError.new(@target_version) - end + def migrate_without_lock + if invalid_target? + raise UnknownMigrationVersionError.new(@target_version) + end - runnable.each do |migration| - execute_migration_in_transaction(migration, @direction) - end + runnable.each do |migration| + execute_migration_in_transaction(migration, @direction) + end - record_environment - end + record_environment + end # Stores the current environment in the database. - def record_environment - return if down? - ActiveRecord::InternalMetadata[:environment] = ActiveRecord::Migrator.current_environment - end + def record_environment + return if down? + ActiveRecord::InternalMetadata[:environment] = ActiveRecord::Migrator.current_environment + end - def ran?(migration) - migrated.include?(migration.version.to_i) - end + def ran?(migration) + migrated.include?(migration.version.to_i) + end # Return true if a valid version is not provided. - def invalid_target? - !target && @target_version && @target_version > 0 - end + def invalid_target? + !target && @target_version && @target_version > 0 + end - def execute_migration_in_transaction(migration, direction) - return if down? && !migrated.include?(migration.version.to_i) - return if up? && migrated.include?(migration.version.to_i) + def execute_migration_in_transaction(migration, direction) + return if down? && !migrated.include?(migration.version.to_i) + return if up? && migrated.include?(migration.version.to_i) - Base.logger.info "Migrating to #{migration.name} (#{migration.version})" if Base.logger + Base.logger.info "Migrating to #{migration.name} (#{migration.version})" if Base.logger - ddl_transaction(migration) do - migration.migrate(direction) - record_version_state_after_migrating(migration.version) + ddl_transaction(migration) do + migration.migrate(direction) + record_version_state_after_migrating(migration.version) + end + rescue => e + msg = "An error has occurred, " + msg << "this and " if use_transaction?(migration) + msg << "all later migrations canceled:\n\n#{e}" + raise StandardError, msg, e.backtrace end - rescue => e - msg = "An error has occurred, " - msg << "this and " if use_transaction?(migration) - msg << "all later migrations canceled:\n\n#{e}" - raise StandardError, msg, e.backtrace - end - def target - migrations.detect { |m| m.version == @target_version } - end + def target + migrations.detect { |m| m.version == @target_version } + end - def finish - migrations.index(target) || migrations.size - 1 - end + def finish + migrations.index(target) || migrations.size - 1 + end - def start - up? ? 0 : (migrations.index(current) || 0) - end + def start + up? ? 0 : (migrations.index(current) || 0) + end - def validate(migrations) - name ,= migrations.group_by(&:name).find { |_,v| v.length > 1 } - raise DuplicateMigrationNameError.new(name) if name + def validate(migrations) + name ,= migrations.group_by(&:name).find { |_,v| v.length > 1 } + raise DuplicateMigrationNameError.new(name) if name - version ,= migrations.group_by(&:version).find { |_,v| v.length > 1 } - raise DuplicateMigrationVersionError.new(version) if version - end + version ,= migrations.group_by(&:version).find { |_,v| v.length > 1 } + raise DuplicateMigrationVersionError.new(version) if version + end - def record_version_state_after_migrating(version) - if down? - migrated.delete(version) - ActiveRecord::SchemaMigration.where(version: version.to_s).delete_all - else - migrated << version - ActiveRecord::SchemaMigration.create!(version: version.to_s) + def record_version_state_after_migrating(version) + if down? + migrated.delete(version) + ActiveRecord::SchemaMigration.where(version: version.to_s).delete_all + else + migrated << version + ActiveRecord::SchemaMigration.create!(version: version.to_s) + end end - end - def self.last_stored_environment - return nil if current_version == 0 - raise NoEnvironmentInSchemaError unless ActiveRecord::InternalMetadata.table_exists? + def self.last_stored_environment + return nil if current_version == 0 + raise NoEnvironmentInSchemaError unless ActiveRecord::InternalMetadata.table_exists? - environment = ActiveRecord::InternalMetadata[:environment] - raise NoEnvironmentInSchemaError unless environment - environment - end + environment = ActiveRecord::InternalMetadata[:environment] + raise NoEnvironmentInSchemaError unless environment + environment + end - def self.current_environment - ActiveRecord::ConnectionHandling::DEFAULT_ENV.call - end + def self.current_environment + ActiveRecord::ConnectionHandling::DEFAULT_ENV.call + end - def self.protected_environment? - ActiveRecord::Base.protected_environments.include?(last_stored_environment) if last_stored_environment - end + def self.protected_environment? + ActiveRecord::Base.protected_environments.include?(last_stored_environment) if last_stored_environment + end - def up? - @direction == :up - end + def up? + @direction == :up + end - def down? - @direction == :down - end + def down? + @direction == :down + end # Wrap the migration in a transaction only if supported by the adapter. - def ddl_transaction(migration) - if use_transaction?(migration) - Base.transaction { yield } - else - yield + def ddl_transaction(migration) + if use_transaction?(migration) + Base.transaction { yield } + else + yield + end end - end - def use_transaction?(migration) - !migration.disable_ddl_transaction && Base.connection.supports_ddl_transactions? - end + def use_transaction?(migration) + !migration.disable_ddl_transaction && Base.connection.supports_ddl_transactions? + end - def use_advisory_lock? - Base.connection.supports_advisory_locks? - end + def use_advisory_lock? + Base.connection.supports_advisory_locks? + end - def with_advisory_lock - lock_id = generate_migrator_advisory_lock_id - got_lock = Base.connection.get_advisory_lock(lock_id) - raise ConcurrentMigrationError unless got_lock - load_migrated # reload schema_migrations to be sure it wasn't changed by another process before we got the lock - yield - ensure - Base.connection.release_advisory_lock(lock_id) if got_lock - end + def with_advisory_lock + lock_id = generate_migrator_advisory_lock_id + got_lock = Base.connection.get_advisory_lock(lock_id) + raise ConcurrentMigrationError unless got_lock + load_migrated # reload schema_migrations to be sure it wasn't changed by another process before we got the lock + yield + ensure + Base.connection.release_advisory_lock(lock_id) if got_lock + end - MIGRATOR_SALT = 2053462845 - def generate_migrator_advisory_lock_id - db_name_hash = Zlib.crc32(Base.connection.current_database) - MIGRATOR_SALT * db_name_hash - end + MIGRATOR_SALT = 2053462845 + def generate_migrator_advisory_lock_id + db_name_hash = Zlib.crc32(Base.connection.current_database) + MIGRATOR_SALT * db_name_hash + end end end diff --git a/activerecord/lib/active_record/migration/command_recorder.rb b/activerecord/lib/active_record/migration/command_recorder.rb index 0fa665c7e0..6b2c5d8da5 100644 --- a/activerecord/lib/active_record/migration/command_recorder.rb +++ b/activerecord/lib/active_record/migration/command_recorder.rb @@ -112,127 +112,127 @@ module ActiveRecord private - module StraightReversions - private - { transaction: :transaction, - execute_block: :execute_block, - create_table: :drop_table, - create_join_table: :drop_join_table, - add_column: :remove_column, - add_timestamps: :remove_timestamps, - add_reference: :remove_reference, - enable_extension: :disable_extension - }.each do |cmd, inv| - [[inv, cmd], [cmd, inv]].uniq.each do |method, inverse| - class_eval <<-EOV, __FILE__, __LINE__ + 1 + module StraightReversions + private + { transaction: :transaction, + execute_block: :execute_block, + create_table: :drop_table, + create_join_table: :drop_join_table, + add_column: :remove_column, + add_timestamps: :remove_timestamps, + add_reference: :remove_reference, + enable_extension: :disable_extension + }.each do |cmd, inv| + [[inv, cmd], [cmd, inv]].uniq.each do |method, inverse| + class_eval <<-EOV, __FILE__, __LINE__ + 1 def invert_#{method}(args, &block) # def invert_create_table(args, &block) [:#{inverse}, args, block] # [:drop_table, args, block] end # end EOV - end + end + end end - end - include StraightReversions + include StraightReversions - def invert_drop_table(args, &block) - if args.size == 1 && block == nil - raise ActiveRecord::IrreversibleMigration, "To avoid mistakes, drop_table is only reversible if given options or a block (can be empty)." + def invert_drop_table(args, &block) + if args.size == 1 && block == nil + raise ActiveRecord::IrreversibleMigration, "To avoid mistakes, drop_table is only reversible if given options or a block (can be empty)." + end + super end - super - end - def invert_rename_table(args) - [:rename_table, args.reverse] - end + def invert_rename_table(args) + [:rename_table, args.reverse] + end - def invert_remove_column(args) - raise ActiveRecord::IrreversibleMigration, "remove_column is only reversible if given a type." if args.size <= 2 - super - end + def invert_remove_column(args) + raise ActiveRecord::IrreversibleMigration, "remove_column is only reversible if given a type." if args.size <= 2 + super + end - def invert_rename_index(args) - [:rename_index, [args.first] + args.last(2).reverse] - end + def invert_rename_index(args) + [:rename_index, [args.first] + args.last(2).reverse] + end - def invert_rename_column(args) - [:rename_column, [args.first] + args.last(2).reverse] - end + def invert_rename_column(args) + [:rename_column, [args.first] + args.last(2).reverse] + end - def invert_add_index(args) - table, columns, options = *args - options ||= {} + def invert_add_index(args) + table, columns, options = *args + options ||= {} - index_name = options[:name] - options_hash = index_name ? { name: index_name } : { column: columns } + index_name = options[:name] + options_hash = index_name ? { name: index_name } : { column: columns } - [:remove_index, [table, options_hash]] - end + [:remove_index, [table, options_hash]] + end - def invert_remove_index(args) - table, options_or_column = *args - if (options = options_or_column).is_a?(Hash) - unless options[:column] - raise ActiveRecord::IrreversibleMigration, "remove_index is only reversible if given a :column option." + def invert_remove_index(args) + table, options_or_column = *args + if (options = options_or_column).is_a?(Hash) + unless options[:column] + raise ActiveRecord::IrreversibleMigration, "remove_index is only reversible if given a :column option." + end + options = options.dup + [:add_index, [table, options.delete(:column), options]] + elsif (column = options_or_column).present? + [:add_index, [table, column]] end - options = options.dup - [:add_index, [table, options.delete(:column), options]] - elsif (column = options_or_column).present? - [:add_index, [table, column]] end - end - alias :invert_add_belongs_to :invert_add_reference - alias :invert_remove_belongs_to :invert_remove_reference + alias :invert_add_belongs_to :invert_add_reference + alias :invert_remove_belongs_to :invert_remove_reference + + def invert_change_column_default(args) + table, column, options = *args - def invert_change_column_default(args) - table, column, options = *args + unless options && options.is_a?(Hash) && options.has_key?(:from) && options.has_key?(:to) + raise ActiveRecord::IrreversibleMigration, "change_column_default is only reversible if given a :from and :to option." + end - unless options && options.is_a?(Hash) && options.has_key?(:from) && options.has_key?(:to) - raise ActiveRecord::IrreversibleMigration, "change_column_default is only reversible if given a :from and :to option." + [:change_column_default, [table, column, from: options[:to], to: options[:from]]] end - [:change_column_default, [table, column, from: options[:to], to: options[:from]]] - end + def invert_change_column_null(args) + args[2] = !args[2] + [:change_column_null, args] + end - def invert_change_column_null(args) - args[2] = !args[2] - [:change_column_null, args] - end + def invert_add_foreign_key(args) + from_table, to_table, add_options = args + add_options ||= {} - def invert_add_foreign_key(args) - from_table, to_table, add_options = args - add_options ||= {} + if add_options[:name] + options = { name: add_options[:name] } + elsif add_options[:column] + options = { column: add_options[:column] } + else + options = to_table + end - if add_options[:name] - options = { name: add_options[:name] } - elsif add_options[:column] - options = { column: add_options[:column] } - else - options = to_table + [:remove_foreign_key, [from_table, options]] end - [:remove_foreign_key, [from_table, options]] - end - - def invert_remove_foreign_key(args) - from_table, to_table, remove_options = args - raise ActiveRecord::IrreversibleMigration, "remove_foreign_key is only reversible if given a second table" if to_table.nil? || to_table.is_a?(Hash) + def invert_remove_foreign_key(args) + from_table, to_table, remove_options = args + raise ActiveRecord::IrreversibleMigration, "remove_foreign_key is only reversible if given a second table" if to_table.nil? || to_table.is_a?(Hash) - reversed_args = [from_table, to_table] - reversed_args << remove_options if remove_options + reversed_args = [from_table, to_table] + reversed_args << remove_options if remove_options - [:add_foreign_key, reversed_args] - end + [:add_foreign_key, reversed_args] + end # Forwards any missing method call to the \target. - def method_missing(method, *args, &block) - if @delegate.respond_to?(method) - @delegate.send(method, *args, &block) - else - super + def method_missing(method, *args, &block) + if @delegate.respond_to?(method) + @delegate.send(method, *args, &block) + else + super + end end - end end end end diff --git a/activerecord/lib/active_record/migration/compatibility.rb b/activerecord/lib/active_record/migration/compatibility.rb index 5baca7183b..a79251f908 100644 --- a/activerecord/lib/active_record/migration/compatibility.rb +++ b/activerecord/lib/active_record/migration/compatibility.rb @@ -83,23 +83,23 @@ module ActiveRecord private - def index_name_for_remove(table_name, options = {}) - index_name = index_name(table_name, options) + def index_name_for_remove(table_name, options = {}) + index_name = index_name(table_name, options) - unless index_name_exists?(table_name, index_name, true) - if options.is_a?(Hash) && options.has_key?(:name) - options_without_column = options.dup - options_without_column.delete :column - index_name_without_column = index_name(table_name, options_without_column) + unless index_name_exists?(table_name, index_name, true) + if options.is_a?(Hash) && options.has_key?(:name) + options_without_column = options.dup + options_without_column.delete :column + index_name_without_column = index_name(table_name, options_without_column) - return index_name_without_column if index_name_exists?(table_name, index_name_without_column, false) + return index_name_without_column if index_name_exists?(table_name, index_name_without_column, false) + end + + raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' does not exist" end - raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' does not exist" + index_name end - - index_name - end end class V5_0 < V5_1 diff --git a/activerecord/lib/active_record/migration/join_table.rb b/activerecord/lib/active_record/migration/join_table.rb index 05569fadbd..89789f00ea 100644 --- a/activerecord/lib/active_record/migration/join_table.rb +++ b/activerecord/lib/active_record/migration/join_table.rb @@ -3,13 +3,13 @@ module ActiveRecord module JoinTable #:nodoc: private - def find_join_table_name(table_1, table_2, options = {}) - options.delete(:table_name) || join_table_name(table_1, table_2) - end + def find_join_table_name(table_1, table_2, options = {}) + options.delete(:table_name) || join_table_name(table_1, table_2) + end - def join_table_name(table_1, table_2) - ModelSchema.derive_join_table_name(table_1, table_2).to_sym - end + def join_table_name(table_1, table_2) + ModelSchema.derive_join_table_name(table_1, table_2).to_sym + end end end end diff --git a/activerecord/lib/active_record/model_schema.rb b/activerecord/lib/active_record/model_schema.rb index 63312a8d11..1537fffc22 100644 --- a/activerecord/lib/active_record/model_schema.rb +++ b/activerecord/lib/active_record/model_schema.rb @@ -357,80 +357,80 @@ module ActiveRecord private - def schema_loaded? - defined?(@columns_hash) && @columns_hash - end + def schema_loaded? + defined?(@columns_hash) && @columns_hash + end - def load_schema - unless schema_loaded? - load_schema! + def load_schema + unless schema_loaded? + load_schema! + end end - end - def load_schema! - @columns_hash = connection.schema_cache.columns_hash(table_name).except(*ignored_columns) - @columns_hash.each do |name, column| - warn_if_deprecated_type(column) - define_attribute( - name, - connection.lookup_cast_type_from_column(column), - default: column.default, - user_provided_default: false - ) + def load_schema! + @columns_hash = connection.schema_cache.columns_hash(table_name).except(*ignored_columns) + @columns_hash.each do |name, column| + warn_if_deprecated_type(column) + define_attribute( + name, + connection.lookup_cast_type_from_column(column), + default: column.default, + user_provided_default: false + ) + end end - end - def reload_schema_from_cache - @arel_engine = nil - @arel_table = nil - @column_names = nil - @attribute_types = nil - @content_columns = nil - @default_attributes = nil - @inheritance_column = nil unless defined?(@explicit_inheritance_column) && @explicit_inheritance_column - @attributes_builder = nil - @columns = nil - @columns_hash = nil - @attribute_names = nil - @yaml_encoder = nil - direct_descendants.each do |descendant| - descendant.send(:reload_schema_from_cache) + def reload_schema_from_cache + @arel_engine = nil + @arel_table = nil + @column_names = nil + @attribute_types = nil + @content_columns = nil + @default_attributes = nil + @inheritance_column = nil unless defined?(@explicit_inheritance_column) && @explicit_inheritance_column + @attributes_builder = nil + @columns = nil + @columns_hash = nil + @attribute_names = nil + @yaml_encoder = nil + direct_descendants.each do |descendant| + descendant.send(:reload_schema_from_cache) + end end - end # Guesses the table name, but does not decorate it with prefix and suffix information. - def undecorated_table_name(class_name = base_class.name) - table_name = class_name.to_s.demodulize.underscore - pluralize_table_names ? table_name.pluralize : table_name - end + def undecorated_table_name(class_name = base_class.name) + table_name = class_name.to_s.demodulize.underscore + pluralize_table_names ? table_name.pluralize : table_name + end # Computes and returns a table name according to default conventions. - def compute_table_name - base = base_class - if self == base - # Nested classes are prefixed with singular parent table name. - if parent < Base && !parent.abstract_class? - contained = parent.table_name - contained = contained.singularize if parent.pluralize_table_names - contained += "_" + def compute_table_name + base = base_class + if self == base + # Nested classes are prefixed with singular parent table name. + if parent < Base && !parent.abstract_class? + contained = parent.table_name + contained = contained.singularize if parent.pluralize_table_names + contained += "_" + end + + "#{full_table_name_prefix}#{contained}#{undecorated_table_name(name)}#{full_table_name_suffix}" + else + # STI subclasses always use their superclass' table. + base.table_name end - - "#{full_table_name_prefix}#{contained}#{undecorated_table_name(name)}#{full_table_name_suffix}" - else - # STI subclasses always use their superclass' table. - base.table_name end - end - def warn_if_deprecated_type(column) - return if attributes_to_define_after_schema_loads.key?(column.name) - if column.respond_to?(:oid) && column.sql_type.start_with?("point") - if column.array? - array_arguments = ", array: true" - else - array_arguments = "" - end - ActiveSupport::Deprecation.warn(<<-WARNING.strip_heredoc) + def warn_if_deprecated_type(column) + return if attributes_to_define_after_schema_loads.key?(column.name) + if column.respond_to?(:oid) && column.sql_type.start_with?("point") + if column.array? + array_arguments = ", array: true" + else + array_arguments = "" + end + 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}: @@ -441,8 +441,8 @@ module ActiveRecord attribute :#{column.name}, :point#{array_arguments} WARNING + end end - end end end end diff --git a/activerecord/lib/active_record/nested_attributes.rb b/activerecord/lib/active_record/nested_attributes.rb index c9fe1167e8..682b404060 100644 --- a/activerecord/lib/active_record/nested_attributes.rb +++ b/activerecord/lib/active_record/nested_attributes.rb @@ -352,8 +352,8 @@ module ActiveRecord # This redirects the attempts to write objects in an association through # the helper methods defined below. Makes it seem like the nested # associations are just regular associations. - def generate_association_writer(association_name, type) - generated_association_methods.module_eval <<-eoruby, __FILE__, __LINE__ + 1 + def generate_association_writer(association_name, type) + generated_association_methods.module_eval <<-eoruby, __FILE__, __LINE__ + 1 if method_defined?(:#{association_name}_attributes=) remove_method(:#{association_name}_attributes=) end @@ -361,7 +361,7 @@ module ActiveRecord assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes) end eoruby - end + end end # Returns ActiveRecord::AutosaveAssociation::marked_for_destruction? It's @@ -377,7 +377,7 @@ module ActiveRecord # Attribute hash keys that should not be assigned as normal attributes. # These hash keys are nested attributes implementation details. - UNASSIGNABLE_KEYS = %w( id _destroy ) + UNASSIGNABLE_KEYS = %w( id _destroy ) # Assigns the given attributes to the association. # @@ -392,37 +392,37 @@ module ActiveRecord # If the given attributes include a matching :id attribute, or # update_only is true, and a :_destroy key set to a truthy value, # then the existing record will be marked for destruction. - def assign_nested_attributes_for_one_to_one_association(association_name, attributes) - options = self.nested_attributes_options[association_name] - if attributes.respond_to?(:permitted?) - attributes = attributes.to_h - end - attributes = attributes.with_indifferent_access - existing_record = send(association_name) + def assign_nested_attributes_for_one_to_one_association(association_name, attributes) + options = self.nested_attributes_options[association_name] + if attributes.respond_to?(:permitted?) + attributes = attributes.to_h + end + attributes = attributes.with_indifferent_access + existing_record = send(association_name) - if (options[:update_only] || !attributes["id"].blank?) && existing_record && - (options[:update_only] || existing_record.id.to_s == attributes["id"].to_s) - assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy]) unless call_reject_if(association_name, attributes) + if (options[:update_only] || !attributes["id"].blank?) && existing_record && + (options[:update_only] || existing_record.id.to_s == attributes["id"].to_s) + assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy]) unless call_reject_if(association_name, attributes) - elsif attributes["id"].present? - raise_nested_attributes_record_not_found!(association_name, attributes["id"]) + elsif attributes["id"].present? + raise_nested_attributes_record_not_found!(association_name, attributes["id"]) - elsif !reject_new_record?(association_name, attributes) - assignable_attributes = attributes.except(*UNASSIGNABLE_KEYS) + elsif !reject_new_record?(association_name, attributes) + assignable_attributes = attributes.except(*UNASSIGNABLE_KEYS) - if existing_record && existing_record.new_record? - existing_record.assign_attributes(assignable_attributes) - association(association_name).initialize_attributes(existing_record) - else - method = "build_#{association_name}" - if respond_to?(method) - send(method, assignable_attributes) + if existing_record && existing_record.new_record? + existing_record.assign_attributes(assignable_attributes) + association(association_name).initialize_attributes(existing_record) else - raise ArgumentError, "Cannot build association `#{association_name}'. Are you trying to build a polymorphic one-to-one association?" + method = "build_#{association_name}" + if respond_to?(method) + send(method, assignable_attributes) + else + raise ArgumentError, "Cannot build association `#{association_name}'. Are you trying to build a polymorphic one-to-one association?" + end end end end - end # Assigns the given attributes to the collection association. # @@ -451,65 +451,65 @@ module ActiveRecord # { name: 'John' }, # { id: '2', _destroy: true } # ]) - def assign_nested_attributes_for_collection_association(association_name, attributes_collection) - options = self.nested_attributes_options[association_name] - if attributes_collection.respond_to?(:permitted?) - attributes_collection = attributes_collection.to_h - end + def assign_nested_attributes_for_collection_association(association_name, attributes_collection) + options = self.nested_attributes_options[association_name] + if attributes_collection.respond_to?(:permitted?) + attributes_collection = attributes_collection.to_h + end - unless attributes_collection.is_a?(Hash) || attributes_collection.is_a?(Array) - raise ArgumentError, "Hash or Array expected, got #{attributes_collection.class.name} (#{attributes_collection.inspect})" - end + unless attributes_collection.is_a?(Hash) || attributes_collection.is_a?(Array) + raise ArgumentError, "Hash or Array expected, got #{attributes_collection.class.name} (#{attributes_collection.inspect})" + end - check_record_limit!(options[:limit], attributes_collection) + check_record_limit!(options[:limit], attributes_collection) - if attributes_collection.is_a? Hash - keys = attributes_collection.keys - attributes_collection = if keys.include?("id") || keys.include?(:id) - [attributes_collection] - else - attributes_collection.values + if attributes_collection.is_a? Hash + keys = attributes_collection.keys + attributes_collection = if keys.include?("id") || keys.include?(:id) + [attributes_collection] + else + attributes_collection.values + end end - end - - association = association(association_name) - existing_records = if association.loaded? - association.target - else - attribute_ids = attributes_collection.map {|a| a["id"] || a[:id] }.compact - attribute_ids.empty? ? [] : association.scope.where(association.klass.primary_key => attribute_ids) - end + association = association(association_name) - attributes_collection.each do |attributes| - if attributes.respond_to?(:permitted?) - attributes = attributes.to_h + existing_records = if association.loaded? + association.target + else + attribute_ids = attributes_collection.map {|a| a["id"] || a[:id] }.compact + attribute_ids.empty? ? [] : association.scope.where(association.klass.primary_key => attribute_ids) end - attributes = attributes.with_indifferent_access - if attributes["id"].blank? - unless reject_new_record?(association_name, attributes) - association.build(attributes.except(*UNASSIGNABLE_KEYS)) + attributes_collection.each do |attributes| + if attributes.respond_to?(:permitted?) + attributes = attributes.to_h end - elsif existing_record = existing_records.detect { |record| record.id.to_s == attributes["id"].to_s } - unless call_reject_if(association_name, attributes) - # Make sure we are operating on the actual object which is in the association's - # proxy_target array (either by finding it, or adding it if not found) - # Take into account that the proxy_target may have changed due to callbacks - target_record = association.target.detect { |record| record.id.to_s == attributes["id"].to_s } - if target_record - existing_record = target_record - else - association.add_to_target(existing_record, :skip_callbacks) - end + attributes = attributes.with_indifferent_access - assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy]) + if attributes["id"].blank? + unless reject_new_record?(association_name, attributes) + association.build(attributes.except(*UNASSIGNABLE_KEYS)) + end + elsif existing_record = existing_records.detect { |record| record.id.to_s == attributes["id"].to_s } + unless call_reject_if(association_name, attributes) + # Make sure we are operating on the actual object which is in the association's + # proxy_target array (either by finding it, or adding it if not found) + # Take into account that the proxy_target may have changed due to callbacks + target_record = association.target.detect { |record| record.id.to_s == attributes["id"].to_s } + if target_record + existing_record = target_record + else + association.add_to_target(existing_record, :skip_callbacks) + end + + assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy]) + end + else + raise_nested_attributes_record_not_found!(association_name, attributes["id"]) end - else - raise_nested_attributes_record_not_found!(association_name, attributes["id"]) end end - end # Takes in a limit and checks if the attributes_collection has too many # records. It accepts limit in the form of symbol, proc, or @@ -517,71 +517,71 @@ module ActiveRecord # # Raises TooManyRecords error if the attributes_collection is # larger than the limit. - def check_record_limit!(limit, attributes_collection) - if limit - limit = case limit - when Symbol - send(limit) - when Proc - limit.call - else - limit - end + def check_record_limit!(limit, attributes_collection) + if limit + limit = case limit + when Symbol + send(limit) + when Proc + limit.call + else + limit + end - if limit && attributes_collection.size > limit - raise TooManyRecords, "Maximum #{limit} records are allowed. Got #{attributes_collection.size} records instead." + if limit && attributes_collection.size > limit + raise TooManyRecords, "Maximum #{limit} records are allowed. Got #{attributes_collection.size} records instead." + end end end - end # Updates a record with the +attributes+ or marks it for destruction if # +allow_destroy+ is +true+ and has_destroy_flag? returns +true+. - def assign_to_or_mark_for_destruction(record, attributes, allow_destroy) - record.assign_attributes(attributes.except(*UNASSIGNABLE_KEYS)) - record.mark_for_destruction if has_destroy_flag?(attributes) && allow_destroy - end + def assign_to_or_mark_for_destruction(record, attributes, allow_destroy) + record.assign_attributes(attributes.except(*UNASSIGNABLE_KEYS)) + record.mark_for_destruction if has_destroy_flag?(attributes) && allow_destroy + end # Determines if a hash contains a truthy _destroy key. - def has_destroy_flag?(hash) - Type::Boolean.new.cast(hash["_destroy"]) - end + def has_destroy_flag?(hash) + Type::Boolean.new.cast(hash["_destroy"]) + end # Determines if a new record should be rejected by checking # has_destroy_flag? or if a :reject_if proc exists for this # association and evaluates to +true+. - def reject_new_record?(association_name, attributes) - will_be_destroyed?(association_name, attributes) || call_reject_if(association_name, attributes) - end + def reject_new_record?(association_name, attributes) + will_be_destroyed?(association_name, attributes) || call_reject_if(association_name, attributes) + end # Determines if a record with the particular +attributes+ should be # rejected by calling the reject_if Symbol or Proc (if defined). # The reject_if option is defined by +accepts_nested_attributes_for+. # # Returns false if there is a +destroy_flag+ on the attributes. - def call_reject_if(association_name, attributes) - return false if will_be_destroyed?(association_name, attributes) - - case callback = self.nested_attributes_options[association_name][:reject_if] - when Symbol - method(callback).arity == 0 ? send(callback) : send(callback, attributes) - when Proc - callback.call(attributes) + def call_reject_if(association_name, attributes) + return false if will_be_destroyed?(association_name, attributes) + + case callback = self.nested_attributes_options[association_name][:reject_if] + when Symbol + method(callback).arity == 0 ? send(callback) : send(callback, attributes) + when Proc + callback.call(attributes) + end end - end # Only take into account the destroy flag if :allow_destroy is true - def will_be_destroyed?(association_name, attributes) - allow_destroy?(association_name) && has_destroy_flag?(attributes) - end + def will_be_destroyed?(association_name, attributes) + allow_destroy?(association_name) && has_destroy_flag?(attributes) + end - def allow_destroy?(association_name) - self.nested_attributes_options[association_name][:allow_destroy] - end + def allow_destroy?(association_name) + self.nested_attributes_options[association_name][:allow_destroy] + end - def raise_nested_attributes_record_not_found!(association_name, record_id) - model = self.class._reflect_on_association(association_name).klass.name - raise RecordNotFound.new("Couldn't find #{model} with ID=#{record_id} for #{self.class.name} with ID=#{id}", - model, "id", record_id) - end + def raise_nested_attributes_record_not_found!(association_name, record_id) + model = self.class._reflect_on_association(association_name).klass.name + raise RecordNotFound.new("Couldn't find #{model} with ID=#{record_id} for #{self.class.name} with ID=#{id}", + model, "id", record_id) + end end end diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake index 3532465fee..6f0dbeb9e5 100644 --- a/activerecord/lib/active_record/railties/databases.rake +++ b/activerecord/lib/active_record/railties/databases.rake @@ -204,13 +204,13 @@ db_namespace = namespace :db do base_dir = ActiveRecord::Tasks::DatabaseTasks.fixtures_path fixtures_dir = if ENV["FIXTURES_DIR"] - File.join base_dir, ENV["FIXTURES_DIR"] + File.join base_dir, ENV["FIXTURES_DIR"] else base_dir end fixture_files = if ENV["FIXTURES"] - ENV["FIXTURES"].split(",") + 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] } diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index e96adc9af8..60ccb73d50 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -685,48 +685,48 @@ module ActiveRecord private - def exec_queries - @records = eager_loading? ? find_with_associations.freeze : @klass.find_by_sql(arel, bound_attributes).freeze - - preload = preload_values - preload += includes_values unless eager_loading? - preloader = build_preloader - preload.each do |associations| - preloader.preload @records, associations - end + def exec_queries + @records = eager_loading? ? find_with_associations.freeze : @klass.find_by_sql(arel, bound_attributes).freeze + + preload = preload_values + preload += includes_values unless eager_loading? + preloader = build_preloader + preload.each do |associations| + preloader.preload @records, associations + end - @records.each(&:readonly!) if readonly_value + @records.each(&:readonly!) if readonly_value - @loaded = true - @records - end + @loaded = true + @records + end - def build_preloader - ActiveRecord::Associations::Preloader.new - end + def build_preloader + ActiveRecord::Associations::Preloader.new + end - def references_eager_loaded_tables? - joined_tables = arel.join_sources.map do |join| - if join.is_a?(Arel::Nodes::StringJoin) - tables_in_string(join.left) - else - [join.left.table_name, join.left.table_alias] + def references_eager_loaded_tables? + joined_tables = arel.join_sources.map do |join| + if join.is_a?(Arel::Nodes::StringJoin) + tables_in_string(join.left) + else + [join.left.table_name, join.left.table_alias] + end end - end - joined_tables += [table.name, table.table_alias] + joined_tables += [table.name, table.table_alias] - # always convert table names to downcase as in Oracle quoted table names are in uppercase - joined_tables = joined_tables.flatten.compact.map(&:downcase).uniq + # always convert table names to downcase as in Oracle quoted table names are in uppercase + joined_tables = joined_tables.flatten.compact.map(&:downcase).uniq - (references_values - joined_tables).any? - end + (references_values - joined_tables).any? + end - def tables_in_string(string) - return [] if string.blank? - # always convert table names to downcase as in Oracle quoted table names are in uppercase - # ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries - string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map(&:downcase).uniq - ["raw_sql_"] - end + def tables_in_string(string) + return [] if string.blank? + # always convert table names to downcase as in Oracle quoted table names are in uppercase + # ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries + string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map(&:downcase).uniq - ["raw_sql_"] + end end end diff --git a/activerecord/lib/active_record/relation/batches.rb b/activerecord/lib/active_record/relation/batches.rb index f4dd106edf..4b2987ac6d 100644 --- a/activerecord/lib/active_record/relation/batches.rb +++ b/activerecord/lib/active_record/relation/batches.rb @@ -249,24 +249,24 @@ module ActiveRecord private - def apply_limits(relation, start, finish) - relation = relation.where(arel_attribute(primary_key).gteq(start)) if start - relation = relation.where(arel_attribute(primary_key).lteq(finish)) if finish - relation - end + def apply_limits(relation, start, finish) + relation = relation.where(arel_attribute(primary_key).gteq(start)) if start + relation = relation.where(arel_attribute(primary_key).lteq(finish)) if finish + relation + end - def batch_order - "#{quoted_table_name}.#{quoted_primary_key} ASC" - end + def batch_order + "#{quoted_table_name}.#{quoted_primary_key} ASC" + end - def act_on_ignored_order(error_on_ignore) - raise_error = (error_on_ignore.nil? ? self.klass.error_on_ignored_order : error_on_ignore) + def act_on_ignored_order(error_on_ignore) + raise_error = (error_on_ignore.nil? ? self.klass.error_on_ignored_order : error_on_ignore) - if raise_error - raise ArgumentError.new(ORDER_IGNORE_MESSAGE) - elsif logger - logger.warn(ORDER_IGNORE_MESSAGE) + if raise_error + raise ArgumentError.new(ORDER_IGNORE_MESSAGE) + elsif logger + logger.warn(ORDER_IGNORE_MESSAGE) + end end - end end end diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb index 4af9f0859a..233a0622d5 100644 --- a/activerecord/lib/active_record/relation/calculations.rb +++ b/activerecord/lib/active_record/relation/calculations.rb @@ -185,147 +185,147 @@ module ActiveRecord private - def has_include?(column_name) - eager_loading? || (includes_values.present? && column_name && column_name != :all) - end + def has_include?(column_name) + eager_loading? || (includes_values.present? && column_name && column_name != :all) + end - def perform_calculation(operation, column_name) - operation = operation.to_s.downcase + def perform_calculation(operation, column_name) + operation = operation.to_s.downcase - # If #count is used with #distinct (i.e. `relation.distinct.count`) it is - # considered distinct. - distinct = self.distinct_value + # If #count is used with #distinct (i.e. `relation.distinct.count`) it is + # considered distinct. + distinct = self.distinct_value - if operation == "count" - column_name ||= select_for_count + if operation == "count" + column_name ||= select_for_count + + unless arel.ast.grep(Arel::Nodes::OuterJoin).empty? + distinct = true + end - unless arel.ast.grep(Arel::Nodes::OuterJoin).empty? - distinct = true + column_name = primary_key if column_name == :all && distinct + distinct = nil if column_name =~ /\s*DISTINCT[\s(]+/i end - column_name = primary_key if column_name == :all && distinct - distinct = nil if column_name =~ /\s*DISTINCT[\s(]+/i + if group_values.any? + execute_grouped_calculation(operation, column_name, distinct) + else + execute_simple_calculation(operation, column_name, distinct) + end end - if group_values.any? - execute_grouped_calculation(operation, column_name, distinct) - else - execute_simple_calculation(operation, column_name, distinct) - end - end + def aggregate_column(column_name) + return column_name if Arel::Expressions === column_name - def aggregate_column(column_name) - return column_name if Arel::Expressions === column_name + if @klass.column_names.include?(column_name.to_s) + Arel::Attribute.new(@klass.unscoped.table, column_name) + else + Arel.sql(column_name == :all ? "*" : column_name.to_s) + end + end - if @klass.column_names.include?(column_name.to_s) - Arel::Attribute.new(@klass.unscoped.table, column_name) - else - Arel.sql(column_name == :all ? "*" : column_name.to_s) + def operation_over_aggregate_column(column, operation, distinct) + operation == "count" ? column.count(distinct) : column.send(operation) end - end - def operation_over_aggregate_column(column, operation, distinct) - operation == "count" ? column.count(distinct) : column.send(operation) - end + def execute_simple_calculation(operation, column_name, distinct) #:nodoc: + # PostgreSQL doesn't like ORDER BY when there are no GROUP BY + relation = unscope(:order) - def execute_simple_calculation(operation, column_name, distinct) #:nodoc: - # PostgreSQL doesn't like ORDER BY when there are no GROUP BY - relation = unscope(:order) + column_alias = column_name - column_alias = column_name + if operation == "count" && (relation.limit_value || relation.offset_value) + # Shortcut when limit is zero. + return 0 if relation.limit_value == 0 - if operation == "count" && (relation.limit_value || relation.offset_value) - # Shortcut when limit is zero. - return 0 if relation.limit_value == 0 + query_builder = build_count_subquery(relation, column_name, distinct) + else + column = aggregate_column(column_name) - query_builder = build_count_subquery(relation, column_name, distinct) - else - column = aggregate_column(column_name) + select_value = operation_over_aggregate_column(column, operation, distinct) - select_value = operation_over_aggregate_column(column, operation, distinct) + column_alias = select_value.alias + column_alias ||= @klass.connection.column_name_for_operation(operation, select_value) + relation.select_values = [select_value] - column_alias = select_value.alias - column_alias ||= @klass.connection.column_name_for_operation(operation, select_value) - relation.select_values = [select_value] + query_builder = relation.arel + end - query_builder = relation.arel - end + result = @klass.connection.select_all(query_builder, nil, bound_attributes) + row = result.first + value = row && row.values.first + column = result.column_types.fetch(column_alias) do + type_for(column_name) + end - result = @klass.connection.select_all(query_builder, nil, bound_attributes) - row = result.first - value = row && row.values.first - column = result.column_types.fetch(column_alias) do - type_for(column_name) + type_cast_calculated_value(value, column, operation) end - type_cast_calculated_value(value, column, operation) - end + def execute_grouped_calculation(operation, column_name, distinct) #:nodoc: + group_attrs = group_values - def execute_grouped_calculation(operation, column_name, distinct) #:nodoc: - group_attrs = group_values - - if group_attrs.first.respond_to?(:to_sym) - association = @klass._reflect_on_association(group_attrs.first) - associated = group_attrs.size == 1 && association && association.belongs_to? # only count belongs_to associations - group_fields = Array(associated ? association.foreign_key : group_attrs) - else - group_fields = group_attrs - end - group_fields = arel_columns(group_fields) + if group_attrs.first.respond_to?(:to_sym) + association = @klass._reflect_on_association(group_attrs.first) + associated = group_attrs.size == 1 && association && association.belongs_to? # only count belongs_to associations + group_fields = Array(associated ? association.foreign_key : group_attrs) + else + group_fields = group_attrs + end + group_fields = arel_columns(group_fields) - group_aliases = group_fields.map { |field| column_alias_for(field) } - group_columns = group_aliases.zip(group_fields) + group_aliases = group_fields.map { |field| column_alias_for(field) } + group_columns = group_aliases.zip(group_fields) - if operation == "count" && column_name == :all - aggregate_alias = "count_all" - else - aggregate_alias = column_alias_for([operation, column_name].join(" ")) - end - - select_values = [ - operation_over_aggregate_column( - aggregate_column(column_name), - operation, - distinct).as(aggregate_alias) - ] - select_values += select_values unless having_clause.empty? - - select_values.concat group_columns.map { |aliaz, field| - if field.respond_to?(:as) - field.as(aliaz) + if operation == "count" && column_name == :all + aggregate_alias = "count_all" else - "#{field} AS #{aliaz}" + aggregate_alias = column_alias_for([operation, column_name].join(" ")) end - } - relation = except(:group) - relation.group_values = group_fields - relation.select_values = select_values + select_values = [ + operation_over_aggregate_column( + aggregate_column(column_name), + operation, + distinct).as(aggregate_alias) + ] + select_values += select_values unless having_clause.empty? + + select_values.concat group_columns.map { |aliaz, field| + if field.respond_to?(:as) + field.as(aliaz) + else + "#{field} AS #{aliaz}" + end + } - calculated_data = @klass.connection.select_all(relation, nil, relation.bound_attributes) + relation = except(:group) + relation.group_values = group_fields + relation.select_values = select_values - if association - key_ids = calculated_data.collect { |row| row[group_aliases.first] } - key_records = association.klass.base_class.where(association.klass.base_class.primary_key => key_ids) - key_records = Hash[key_records.map { |r| [r.id, r] }] - end + calculated_data = @klass.connection.select_all(relation, nil, relation.bound_attributes) - Hash[calculated_data.map do |row| - key = group_columns.map { |aliaz, col_name| - column = type_for(col_name) do - calculated_data.column_types.fetch(aliaz) do - Type::Value.new - end - end - type_cast_calculated_value(row[aliaz], column) - } - key = key.first if key.size == 1 - key = key_records[key] if associated + if association + key_ids = calculated_data.collect { |row| row[group_aliases.first] } + key_records = association.klass.base_class.where(association.klass.base_class.primary_key => key_ids) + key_records = Hash[key_records.map { |r| [r.id, r] }] + end - column_type = calculated_data.column_types.fetch(aggregate_alias) { type_for(column_name) } - [key, type_cast_calculated_value(row[aggregate_alias], column_type, operation)] - end] - end + Hash[calculated_data.map do |row| + key = group_columns.map { |aliaz, col_name| + column = type_for(col_name) do + calculated_data.column_types.fetch(aliaz) do + Type::Value.new + end + end + type_cast_calculated_value(row[aliaz], column) + } + key = key.first if key.size == 1 + key = key_records[key] if associated + + column_type = calculated_data.column_types.fetch(aggregate_alias) { type_for(column_name) } + [key, type_cast_calculated_value(row[aggregate_alias], column_type, operation)] + end] + end # Converts the given keys to the value that the database adapter returns as # a usable column name: @@ -334,54 +334,54 @@ module ActiveRecord # column_alias_for("sum(id)") # => "sum_id" # column_alias_for("count(distinct users.id)") # => "count_distinct_users_id" # column_alias_for("count(*)") # => "count_all" - def column_alias_for(keys) - if keys.respond_to? :name - keys = "#{keys.relation.name}.#{keys.name}" - end + def column_alias_for(keys) + if keys.respond_to? :name + keys = "#{keys.relation.name}.#{keys.name}" + end - table_name = keys.to_s.downcase - table_name.gsub!(/\*/, "all") - table_name.gsub!(/\W+/, " ") - table_name.strip! - table_name.gsub!(/ +/, "_") + table_name = keys.to_s.downcase + table_name.gsub!(/\*/, "all") + table_name.gsub!(/\W+/, " ") + table_name.strip! + table_name.gsub!(/ +/, "_") - @klass.connection.table_alias_for(table_name) - end + @klass.connection.table_alias_for(table_name) + end - def type_for(field, &block) - field_name = field.respond_to?(:name) ? field.name.to_s : field.to_s.split(".").last - @klass.type_for_attribute(field_name, &block) - end + def type_for(field, &block) + field_name = field.respond_to?(:name) ? field.name.to_s : field.to_s.split(".").last + @klass.type_for_attribute(field_name, &block) + end - def type_cast_calculated_value(value, type, operation = nil) - case operation - when "count" then value.to_i - when "sum" then type.deserialize(value || 0) - when "average" then value.respond_to?(:to_d) ? value.to_d : value - else type.deserialize(value) + def type_cast_calculated_value(value, type, operation = nil) + case operation + when "count" then value.to_i + when "sum" then type.deserialize(value || 0) + when "average" then value.respond_to?(:to_d) ? value.to_d : value + else type.deserialize(value) + end end - end - def select_for_count - if select_values.present? - return select_values.first if select_values.one? - select_values.join(", ") - else - :all + def select_for_count + if select_values.present? + return select_values.first if select_values.one? + select_values.join(", ") + else + :all + end end - end - def build_count_subquery(relation, column_name, distinct) - column_alias = Arel.sql("count_column") - subquery_alias = Arel.sql("subquery_for_count") + def build_count_subquery(relation, column_name, distinct) + column_alias = Arel.sql("count_column") + subquery_alias = Arel.sql("subquery_for_count") - aliased_column = aggregate_column(column_name == :all ? 1 : column_name).as(column_alias) - relation.select_values = [aliased_column] - subquery = relation.arel.as(subquery_alias) + aliased_column = aggregate_column(column_name == :all ? 1 : column_name).as(column_alias) + relation.select_values = [aliased_column] + subquery = relation.arel.as(subquery_alias) - sm = Arel::SelectManager.new relation.engine - select_value = operation_over_aggregate_column(column_alias, "count", distinct) - sm.project(select_value).from(subquery) - end + sm = Arel::SelectManager.new relation.engine + select_value = operation_over_aggregate_column(column_alias, "count", distinct) + sm.project(select_value).from(subquery) + end end end diff --git a/activerecord/lib/active_record/relation/delegation.rb b/activerecord/lib/active_record/relation/delegation.rb index 6b28d85a49..b4147ce434 100644 --- a/activerecord/lib/active_record/relation/delegation.rb +++ b/activerecord/lib/active_record/relation/delegation.rb @@ -83,17 +83,17 @@ module ActiveRecord protected - def method_missing(method, *args, &block) - if @klass.respond_to?(method) - self.class.delegate_to_scoped_klass(method) - scoping { @klass.public_send(method, *args, &block) } - elsif arel.respond_to?(method) - self.class.delegate method, to: :arel - arel.public_send(method, *args, &block) - else - super + def method_missing(method, *args, &block) + if @klass.respond_to?(method) + self.class.delegate_to_scoped_klass(method) + scoping { @klass.public_send(method, *args, &block) } + elsif arel.respond_to?(method) + self.class.delegate method, to: :arel + arel.public_send(method, *args, &block) + else + super + end end - end end module ClassMethods # :nodoc: @@ -103,9 +103,9 @@ module ActiveRecord private - def relation_class_for(klass) - klass.relation_delegate_class(self) - end + def relation_class_for(klass) + klass.relation_delegate_class(self) + end end def respond_to?(method, include_private = false) @@ -115,14 +115,14 @@ module ActiveRecord protected - def method_missing(method, *args, &block) - if @klass.respond_to?(method) - scoping { @klass.public_send(method, *args, &block) } - elsif arel.respond_to?(method) - arel.public_send(method, *args, &block) - else - super + def method_missing(method, *args, &block) + if @klass.respond_to?(method) + scoping { @klass.public_send(method, *args, &block) } + elsif arel.respond_to?(method) + arel.public_send(method, *args, &block) + else + super + end end - end end end diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index 6241e0dbdb..6349701dba 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -361,232 +361,232 @@ module ActiveRecord private - def offset_index - offset_value || 0 - end + def offset_index + offset_value || 0 + end - def find_with_associations - # NOTE: the JoinDependency constructed here needs to know about - # any joins already present in `self`, so pass them in - # - # failing to do so means that in cases like activerecord/test/cases/associations/inner_join_association_test.rb:136 - # incorrect SQL is generated. In that case, the join dependency for - # SpecialCategorizations is constructed without knowledge of the - # preexisting join in joins_values to categorizations (by way of - # the `has_many :through` for categories). - # - join_dependency = construct_join_dependency(joins_values) - - aliases = join_dependency.aliases - relation = select aliases.columns - relation = apply_join_dependency(relation, join_dependency) - - if block_given? - yield relation - else - if ActiveRecord::NullRelation === relation - [] + def find_with_associations + # NOTE: the JoinDependency constructed here needs to know about + # any joins already present in `self`, so pass them in + # + # failing to do so means that in cases like activerecord/test/cases/associations/inner_join_association_test.rb:136 + # incorrect SQL is generated. In that case, the join dependency for + # SpecialCategorizations is constructed without knowledge of the + # preexisting join in joins_values to categorizations (by way of + # the `has_many :through` for categories). + # + join_dependency = construct_join_dependency(joins_values) + + aliases = join_dependency.aliases + relation = select aliases.columns + relation = apply_join_dependency(relation, join_dependency) + + if block_given? + yield relation else - arel = relation.arel - rows = connection.select_all(arel, "SQL", relation.bound_attributes) - join_dependency.instantiate(rows, aliases) + if ActiveRecord::NullRelation === relation + [] + else + arel = relation.arel + rows = connection.select_all(arel, "SQL", relation.bound_attributes) + join_dependency.instantiate(rows, aliases) + end end end - end - def construct_join_dependency(joins = [], eager_loading: true) - including = eager_load_values + includes_values - ActiveRecord::Associations::JoinDependency.new(@klass, including, joins, eager_loading: eager_loading) - end + def construct_join_dependency(joins = [], eager_loading: true) + including = eager_load_values + includes_values + ActiveRecord::Associations::JoinDependency.new(@klass, including, joins, eager_loading: eager_loading) + end - def construct_relation_for_association_calculations - apply_join_dependency(self, construct_join_dependency(joins_values)) - end + def construct_relation_for_association_calculations + apply_join_dependency(self, construct_join_dependency(joins_values)) + end - def apply_join_dependency(relation, join_dependency) - relation = relation.except(:includes, :eager_load, :preload) - relation = relation.joins join_dependency + def apply_join_dependency(relation, join_dependency) + relation = relation.except(:includes, :eager_load, :preload) + relation = relation.joins join_dependency - if using_limitable_reflections?(join_dependency.reflections) - relation - else - if relation.limit_value - limited_ids = limited_ids_for(relation) - limited_ids.empty? ? relation.none! : relation.where!(primary_key => limited_ids) + if using_limitable_reflections?(join_dependency.reflections) + relation + else + if relation.limit_value + limited_ids = limited_ids_for(relation) + limited_ids.empty? ? relation.none! : relation.where!(primary_key => limited_ids) + end + relation.except(:limit, :offset) end - relation.except(:limit, :offset) end - end - def limited_ids_for(relation) - values = @klass.connection.columns_for_distinct( - "#{quoted_table_name}.#{quoted_primary_key}", relation.order_values) + def limited_ids_for(relation) + values = @klass.connection.columns_for_distinct( + "#{quoted_table_name}.#{quoted_primary_key}", relation.order_values) - relation = relation.except(:select).select(values).distinct! - arel = relation.arel + relation = relation.except(:select).select(values).distinct! + arel = relation.arel - id_rows = @klass.connection.select_all(arel, "SQL", relation.bound_attributes) - id_rows.map {|row| row[primary_key]} - end + id_rows = @klass.connection.select_all(arel, "SQL", relation.bound_attributes) + id_rows.map {|row| row[primary_key]} + end - def using_limitable_reflections?(reflections) - reflections.none?(&:collection?) - end + def using_limitable_reflections?(reflections) + reflections.none?(&:collection?) + end protected - def find_with_ids(*ids) - raise UnknownPrimaryKey.new(@klass) if primary_key.nil? + def find_with_ids(*ids) + raise UnknownPrimaryKey.new(@klass) if primary_key.nil? - expects_array = ids.first.kind_of?(Array) - return ids.first if expects_array && ids.first.empty? + expects_array = ids.first.kind_of?(Array) + return ids.first if expects_array && ids.first.empty? - ids = ids.flatten.compact.uniq + ids = ids.flatten.compact.uniq - case ids.size - when 0 - raise RecordNotFound, "Couldn't find #{@klass.name} without an ID" - when 1 - result = find_one(ids.first) - expects_array ? [ result ] : result - else - find_some(ids) + case ids.size + when 0 + raise RecordNotFound, "Couldn't find #{@klass.name} without an ID" + when 1 + result = find_one(ids.first) + expects_array ? [ result ] : result + else + find_some(ids) + end + rescue RangeError + raise RecordNotFound, "Couldn't find #{@klass.name} with an out of range ID" end - rescue RangeError - raise RecordNotFound, "Couldn't find #{@klass.name} with an out of range ID" - end - def find_one(id) - if ActiveRecord::Base === id - id = id.id - ActiveSupport::Deprecation.warn(<<-MSG.squish) + def find_one(id) + if ActiveRecord::Base === id + id = id.id + ActiveSupport::Deprecation.warn(<<-MSG.squish) You are passing an instance of ActiveRecord::Base to `find`. Please pass the id of the object by calling `.id`. MSG - end + end - relation = where(primary_key => id) - record = relation.take + relation = where(primary_key => id) + record = relation.take - raise_record_not_found_exception!(id, 0, 1) unless record + raise_record_not_found_exception!(id, 0, 1) unless record - record - end + record + end - def find_some(ids) - return find_some_ordered(ids) unless order_values.present? + def find_some(ids) + return find_some_ordered(ids) unless order_values.present? - result = where(primary_key => ids).to_a + result = where(primary_key => ids).to_a - expected_size = - if limit_value && ids.size > limit_value - limit_value - else - ids.size - end + expected_size = + if limit_value && ids.size > limit_value + limit_value + else + ids.size + end - # 11 ids with limit 3, offset 9 should give 2 results. - if offset_value && (ids.size - offset_value < expected_size) - expected_size = ids.size - offset_value - end + # 11 ids with limit 3, offset 9 should give 2 results. + if offset_value && (ids.size - offset_value < expected_size) + expected_size = ids.size - offset_value + end - if result.size == expected_size - result - else - raise_record_not_found_exception!(ids, result.size, expected_size) + if result.size == expected_size + result + else + raise_record_not_found_exception!(ids, result.size, expected_size) + end end - end - def find_some_ordered(ids) - ids = ids.slice(offset_value || 0, limit_value || ids.size) || [] + def find_some_ordered(ids) + ids = ids.slice(offset_value || 0, limit_value || ids.size) || [] - result = except(:limit, :offset).where(primary_key => ids).records + result = except(:limit, :offset).where(primary_key => ids).records - if result.size == ids.size - pk_type = @klass.type_for_attribute(primary_key) + if result.size == ids.size + pk_type = @klass.type_for_attribute(primary_key) - records_by_id = result.index_by(&:id) - ids.map { |id| records_by_id.fetch(pk_type.cast(id)) } - else - raise_record_not_found_exception!(ids, result.size, ids.size) + records_by_id = result.index_by(&:id) + ids.map { |id| records_by_id.fetch(pk_type.cast(id)) } + else + raise_record_not_found_exception!(ids, result.size, ids.size) + end end - end - def find_take - if loaded? - records.first - else - @take ||= limit(1).records.first + def find_take + if loaded? + records.first + else + @take ||= limit(1).records.first + end 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) + 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 - 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)}]") - 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 - end + def find_nth!(index) + find_nth(index) or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql(@klass.arel_engine)}]") + end - def find_nth_from_last(index) - if loaded? - records[-index] - else + 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) + order(arel_attribute(primary_key).asc) else self end - relation.to_a[-index] - # TODO: can be made more performant on large result sets by - # for instance, last(index)[-index] (which would require - # refactoring the last(n) finder method to make test suite pass), - # or by using a combination of reverse_order, limit, and offset, - # e.g., reverse_order.offset(index-1).first + relation = relation.offset(index) unless index.zero? + relation.limit(limit).to_a + end + + def find_nth_from_last(index) + if loaded? + records[-index] + else + relation = if order_values.empty? && primary_key + order(arel_attribute(primary_key).asc) + else + self + end + + relation.to_a[-index] + # TODO: can be made more performant on large result sets by + # for instance, last(index)[-index] (which would require + # refactoring the last(n) finder method to make test suite pass), + # or by using a combination of reverse_order, limit, and offset, + # e.g., reverse_order.offset(index-1).first + end end - end 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) + 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 - end - def find_last(limit) - limit ? records.last(limit) : records.last - end + def find_last(limit) + limit ? records.last(limit) : records.last + end end end diff --git a/activerecord/lib/active_record/relation/merger.rb b/activerecord/lib/active_record/relation/merger.rb index 87a97803d5..df43b5c64b 100644 --- a/activerecord/lib/active_record/relation/merger.rb +++ b/activerecord/lib/active_record/relation/merger.rb @@ -83,85 +83,85 @@ module ActiveRecord private - def merge_preloads - return if other.preload_values.empty? && other.includes_values.empty? - - if other.klass == relation.klass - relation.preload!(*other.preload_values) unless other.preload_values.empty? - relation.includes!(other.includes_values) unless other.includes_values.empty? - else - reflection = relation.klass.reflect_on_all_associations.find do |r| - r.class_name == other.klass.name - end || return - - unless other.preload_values.empty? - relation.preload! reflection.name => other.preload_values - end + def merge_preloads + return if other.preload_values.empty? && other.includes_values.empty? + + if other.klass == relation.klass + relation.preload!(*other.preload_values) unless other.preload_values.empty? + relation.includes!(other.includes_values) unless other.includes_values.empty? + else + reflection = relation.klass.reflect_on_all_associations.find do |r| + r.class_name == other.klass.name + end || return - unless other.includes_values.empty? - relation.includes! reflection.name => other.includes_values + unless other.preload_values.empty? + relation.preload! reflection.name => other.preload_values + end + + unless other.includes_values.empty? + relation.includes! reflection.name => other.includes_values + end end end - end - def merge_joins - return if other.joins_values.blank? + def merge_joins + return if other.joins_values.blank? - if other.klass == relation.klass - relation.joins!(*other.joins_values) - else - joins_dependency, rest = other.joins_values.partition do |join| - case join - when Hash, Symbol, Array - true - else - false + if other.klass == relation.klass + relation.joins!(*other.joins_values) + else + joins_dependency, rest = other.joins_values.partition do |join| + case join + when Hash, Symbol, Array + true + else + false + end end - end - join_dependency = ActiveRecord::Associations::JoinDependency.new(other.klass, - joins_dependency, - []) - relation.joins! rest + join_dependency = ActiveRecord::Associations::JoinDependency.new(other.klass, + joins_dependency, + []) + relation.joins! rest - @relation = relation.joins join_dependency + @relation = relation.joins join_dependency + end end - end - def merge_multi_values - if other.reordering_value - # override any order specified in the original relation - relation.reorder! other.order_values - elsif other.order_values - # merge in order_values from relation - relation.order! other.order_values + def merge_multi_values + if other.reordering_value + # override any order specified in the original relation + relation.reorder! other.order_values + elsif other.order_values + # merge in order_values from relation + relation.order! other.order_values + end + + relation.extend(*other.extending_values) unless other.extending_values.blank? end - relation.extend(*other.extending_values) unless other.extending_values.blank? - end + def merge_single_values + if relation.from_clause.empty? + relation.from_clause = other.from_clause + end + relation.lock_value ||= other.lock_value - def merge_single_values - if relation.from_clause.empty? - relation.from_clause = other.from_clause + unless other.create_with_value.blank? + relation.create_with_value = (relation.create_with_value || {}).merge(other.create_with_value) + end end - relation.lock_value ||= other.lock_value - unless other.create_with_value.blank? - relation.create_with_value = (relation.create_with_value || {}).merge(other.create_with_value) + CLAUSE_METHOD_NAMES = CLAUSE_METHODS.map do |name| + ["#{name}_clause", "#{name}_clause="] end - end - - CLAUSE_METHOD_NAMES = CLAUSE_METHODS.map do |name| - ["#{name}_clause", "#{name}_clause="] - end - def merge_clauses - CLAUSE_METHOD_NAMES.each do |(reader, writer)| - clause = relation.send(reader) - other_clause = other.send(reader) - relation.send(writer, clause.merge(other_clause)) + def merge_clauses + CLAUSE_METHOD_NAMES.each do |(reader, writer)| + clause = relation.send(reader) + other_clause = other.send(reader) + relation.send(writer, clause.merge(other_clause)) + end end - end end end end diff --git a/activerecord/lib/active_record/relation/predicate_builder.rb b/activerecord/lib/active_record/relation/predicate_builder.rb index 8dbff84950..df663a84ed 100644 --- a/activerecord/lib/active_record/relation/predicate_builder.rb +++ b/activerecord/lib/active_record/relation/predicate_builder.rb @@ -78,91 +78,91 @@ module ActiveRecord protected - attr_reader :table + attr_reader :table - def expand_from_hash(attributes) - return ["1=0"] if attributes.empty? + def expand_from_hash(attributes) + return ["1=0"] if attributes.empty? - attributes.flat_map do |key, value| - if value.is_a?(Hash) - associated_predicate_builder(key).expand_from_hash(value) - else - expand(key, value) + attributes.flat_map do |key, value| + if value.is_a?(Hash) + associated_predicate_builder(key).expand_from_hash(value) + else + expand(key, value) + end end end - end - def create_binds_for_hash(attributes) - 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) - result[column_name] = attrs - binds += bvs - when Relation - binds += value.bound_attributes - when Range - first = value.begin - last = value.end - unless first.respond_to?(:infinite?) && first.infinite? - binds << build_bind_param(column_name, first) - first = Arel::Nodes::BindParam.new - end - unless last.respond_to?(:infinite?) && last.infinite? - binds << build_bind_param(column_name, last) - last = Arel::Nodes::BindParam.new - 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) + def create_binds_for_hash(attributes) + 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) + result[column_name] = attrs + binds += bvs + when Relation + binds += value.bound_attributes + when Range + first = value.begin + last = value.end + unless first.respond_to?(:infinite?) && first.infinite? + binds << build_bind_param(column_name, first) + first = Arel::Nodes::BindParam.new + end + unless last.respond_to?(:infinite?) && last.infinite? + binds << build_bind_param(column_name, last) + last = Arel::Nodes::BindParam.new + 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 end end - end - [result, binds] - end + [result, binds] + end private - def associated_predicate_builder(association_name) - self.class.new(table.associated_table(association_name)) - end - - def convert_dot_notation_to_hash(attributes) - dot_notation = attributes.select do |k, v| - k.include?(".".freeze) && !v.is_a?(Hash) + def associated_predicate_builder(association_name) + self.class.new(table.associated_table(association_name)) end - dot_notation.each_key do |key| - table_name, column_name = key.split(".".freeze) - value = attributes.delete(key) - attributes[table_name] ||= {} + def convert_dot_notation_to_hash(attributes) + dot_notation = attributes.select do |k, v| + k.include?(".".freeze) && !v.is_a?(Hash) + end - attributes[table_name] = attributes[table_name].merge(column_name => value) - end + dot_notation.each_key do |key| + table_name, column_name = key.split(".".freeze) + value = attributes.delete(key) + attributes[table_name] ||= {} - attributes - end + attributes[table_name] = attributes[table_name].merge(column_name => value) + end - def handler_for(object) - @handlers.detect { |klass, _| klass === object }.last - end + attributes + end - def can_be_bound?(column_name, value) - !value.nil? && - handler_for(value).is_a?(BasicObjectHandler) && - !table.associated_with?(column_name) - end + def handler_for(object) + @handlers.detect { |klass, _| klass === object }.last + end - def build_bind_param(column_name, value) - Relation::QueryAttribute.new(column_name.to_s, value, table.type(column_name)) - end + def can_be_bound?(column_name, value) + !value.nil? && + handler_for(value).is_a?(BasicObjectHandler) && + !table.associated_with?(column_name) + end + + def build_bind_param(column_name, value) + Relation::QueryAttribute.new(column_name.to_s, value, table.type(column_name)) + end end end diff --git a/activerecord/lib/active_record/relation/predicate_builder/array_handler.rb b/activerecord/lib/active_record/relation/predicate_builder/array_handler.rb index 95dbd6a77f..6400caba06 100644 --- a/activerecord/lib/active_record/relation/predicate_builder/array_handler.rb +++ b/activerecord/lib/active_record/relation/predicate_builder/array_handler.rb @@ -31,13 +31,13 @@ module ActiveRecord protected - attr_reader :predicate_builder + attr_reader :predicate_builder - module NullPredicate # :nodoc: - def self.or(other) - other + module NullPredicate # :nodoc: + def self.or(other) + other + end end - end end end end diff --git a/activerecord/lib/active_record/relation/predicate_builder/association_query_handler.rb b/activerecord/lib/active_record/relation/predicate_builder/association_query_handler.rb index 413cb9fd84..7e20cb2c63 100644 --- a/activerecord/lib/active_record/relation/predicate_builder/association_query_handler.rb +++ b/activerecord/lib/active_record/relation/predicate_builder/association_query_handler.rb @@ -30,7 +30,7 @@ module ActiveRecord protected - attr_reader :predicate_builder + attr_reader :predicate_builder end class AssociationQueryValue # :nodoc: @@ -60,30 +60,30 @@ module ActiveRecord private - def primary_key - associated_table.association_primary_key(base_class) - end + def primary_key + associated_table.association_primary_key(base_class) + end - def polymorphic_base_class_from_value - case value - when Relation - value.klass.base_class - when Array - val = value.compact.first - val.class.base_class if val.is_a?(Base) - when Base - value.class.base_class + def polymorphic_base_class_from_value + case value + when Relation + value.klass.base_class + when Array + val = value.compact.first + val.class.base_class if val.is_a?(Base) + when Base + value.class.base_class + end end - end - def convert_to_id(value) - case value - when Base - value._read_attribute(primary_key) - else - value + def convert_to_id(value) + case value + when Base + value._read_attribute(primary_key) + else + value + end end - end end end end diff --git a/activerecord/lib/active_record/relation/predicate_builder/base_handler.rb b/activerecord/lib/active_record/relation/predicate_builder/base_handler.rb index 6fa5b16f73..65c5159704 100644 --- a/activerecord/lib/active_record/relation/predicate_builder/base_handler.rb +++ b/activerecord/lib/active_record/relation/predicate_builder/base_handler.rb @@ -11,7 +11,7 @@ module ActiveRecord protected - attr_reader :predicate_builder + attr_reader :predicate_builder end end end diff --git a/activerecord/lib/active_record/relation/predicate_builder/class_handler.rb b/activerecord/lib/active_record/relation/predicate_builder/class_handler.rb index ed313fc9d4..73ad864765 100644 --- a/activerecord/lib/active_record/relation/predicate_builder/class_handler.rb +++ b/activerecord/lib/active_record/relation/predicate_builder/class_handler.rb @@ -12,16 +12,16 @@ module ActiveRecord protected - attr_reader :predicate_builder + attr_reader :predicate_builder private - def print_deprecation_warning - ActiveSupport::Deprecation.warn(<<-MSG.squish) + def print_deprecation_warning + ActiveSupport::Deprecation.warn(<<-MSG.squish) Passing a class as a value in an Active Record query is deprecated and will be removed. Pass a string instead. MSG - end + end end end end diff --git a/activerecord/lib/active_record/relation/predicate_builder/polymorphic_array_handler.rb b/activerecord/lib/active_record/relation/predicate_builder/polymorphic_array_handler.rb index b6c6240343..0c7f92b3d0 100644 --- a/activerecord/lib/active_record/relation/predicate_builder/polymorphic_array_handler.rb +++ b/activerecord/lib/active_record/relation/predicate_builder/polymorphic_array_handler.rb @@ -23,7 +23,7 @@ module ActiveRecord protected - attr_reader :predicate_builder + attr_reader :predicate_builder end class PolymorphicArrayValue # :nodoc: @@ -41,17 +41,17 @@ module ActiveRecord private - def primary_key(value) - associated_table.association_primary_key(base_class(value)) - end + def primary_key(value) + associated_table.association_primary_key(base_class(value)) + end - def base_class(value) - value.class.base_class - end + def base_class(value) + value.class.base_class + end - def convert_to_id(value) - value._read_attribute(primary_key(value)) - end + def convert_to_id(value) + value._read_attribute(primary_key(value)) + 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 3b86f1c605..619b947f57 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -952,241 +952,241 @@ module ActiveRecord private - def assert_mutability! - raise ImmutableRelation if @loaded - raise ImmutableRelation if defined?(@arel) && @arel - end + def assert_mutability! + raise ImmutableRelation if @loaded + raise ImmutableRelation if defined?(@arel) && @arel + end - def build_arel - arel = Arel::SelectManager.new(table) + def build_arel + arel = Arel::SelectManager.new(table) - build_joins(arel, joins_values.flatten) unless joins_values.empty? - build_left_outer_joins(arel, left_outer_joins_values.flatten) unless left_outer_joins_values.empty? + build_joins(arel, joins_values.flatten) unless joins_values.empty? + build_left_outer_joins(arel, left_outer_joins_values.flatten) unless left_outer_joins_values.empty? - arel.where(where_clause.ast) unless where_clause.empty? - arel.having(having_clause.ast) unless having_clause.empty? - if limit_value - if string_containing_comma?(limit_value) - arel.take(connection.sanitize_limit(limit_value)) - else - arel.take(Arel::Nodes::BindParam.new) + arel.where(where_clause.ast) unless where_clause.empty? + arel.having(having_clause.ast) unless having_clause.empty? + if limit_value + if string_containing_comma?(limit_value) + arel.take(connection.sanitize_limit(limit_value)) + else + arel.take(Arel::Nodes::BindParam.new) + end end - end - arel.skip(Arel::Nodes::BindParam.new) if offset_value - arel.group(*arel_columns(group_values.uniq.reject(&:blank?))) unless group_values.empty? + arel.skip(Arel::Nodes::BindParam.new) if offset_value + arel.group(*arel_columns(group_values.uniq.reject(&:blank?))) unless group_values.empty? - build_order(arel) + build_order(arel) - build_select(arel) + build_select(arel) - arel.distinct(distinct_value) - arel.from(build_from) unless from_clause.empty? - arel.lock(lock_value) if lock_value + arel.distinct(distinct_value) + arel.from(build_from) unless from_clause.empty? + arel.lock(lock_value) if lock_value - arel - end - - def symbol_unscoping(scope) - if !VALID_UNSCOPING_VALUES.include?(scope) - raise ArgumentError, "Called unscope() with invalid unscoping argument ':#{scope}'. Valid arguments are :#{VALID_UNSCOPING_VALUES.to_a.join(", :")}." + arel end - clause_method = Relation::CLAUSE_METHODS.include?(scope) - multi_val_method = Relation::MULTI_VALUE_METHODS.include?(scope) - if clause_method - unscope_code = "#{scope}_clause=" - else - unscope_code = "#{scope}_value#{'s' if multi_val_method}=" - end + def symbol_unscoping(scope) + if !VALID_UNSCOPING_VALUES.include?(scope) + raise ArgumentError, "Called unscope() with invalid unscoping argument ':#{scope}'. Valid arguments are :#{VALID_UNSCOPING_VALUES.to_a.join(", :")}." + end - case scope - when :order - result = [] - else - result = [] if multi_val_method - end + clause_method = Relation::CLAUSE_METHODS.include?(scope) + multi_val_method = Relation::MULTI_VALUE_METHODS.include?(scope) + if clause_method + unscope_code = "#{scope}_clause=" + else + unscope_code = "#{scope}_value#{'s' if multi_val_method}=" + end - self.send(unscope_code, result) - end + case scope + when :order + result = [] + else + result = [] if multi_val_method + end - def build_from - opts = from_clause.value - name = from_clause.name - case opts - when Relation - name ||= "subquery" - opts.arel.as(name.to_s) - else - opts + self.send(unscope_code, result) end - end - def build_left_outer_joins(manager, outer_joins) - buckets = outer_joins.group_by do |join| - case join - when Hash, Symbol, Array - :association_join + def build_from + opts = from_clause.value + name = from_clause.name + case opts + when Relation + name ||= "subquery" + opts.arel.as(name.to_s) else - raise ArgumentError, "only Hash, Symbol and Array are allowed" + opts end end - build_join_query(manager, buckets, Arel::Nodes::OuterJoin) - end - - def build_joins(manager, joins) - buckets = joins.group_by do |join| - case join - when String - :string_join - when Hash, Symbol, Array - :association_join - when ActiveRecord::Associations::JoinDependency - :stashed_join - when Arel::Nodes::Join - :join_node - else - raise "unknown class: %s" % join.class.name + def build_left_outer_joins(manager, outer_joins) + buckets = outer_joins.group_by do |join| + case join + when Hash, Symbol, Array + :association_join + else + raise ArgumentError, "only Hash, Symbol and Array are allowed" + end end + + build_join_query(manager, buckets, Arel::Nodes::OuterJoin) end - build_join_query(manager, buckets, Arel::Nodes::InnerJoin) - end + def build_joins(manager, joins) + buckets = joins.group_by do |join| + case join + when String + :string_join + when Hash, Symbol, Array + :association_join + when ActiveRecord::Associations::JoinDependency + :stashed_join + when Arel::Nodes::Join + :join_node + else + raise "unknown class: %s" % join.class.name + end + end - def build_join_query(manager, buckets, join_type) - buckets.default = [] + build_join_query(manager, buckets, Arel::Nodes::InnerJoin) + end - association_joins = buckets[:association_join] - stashed_association_joins = buckets[:stashed_join] - join_nodes = buckets[:join_node].uniq - string_joins = buckets[:string_join].map(&:strip).uniq + def build_join_query(manager, buckets, join_type) + buckets.default = [] - join_list = join_nodes + convert_join_strings_to_ast(manager, string_joins) + association_joins = buckets[:association_join] + stashed_association_joins = buckets[:stashed_join] + join_nodes = buckets[:join_node].uniq + string_joins = buckets[:string_join].map(&:strip).uniq - join_dependency = ActiveRecord::Associations::JoinDependency.new( - @klass, - association_joins, - join_list - ) + join_list = join_nodes + convert_join_strings_to_ast(manager, string_joins) - join_infos = join_dependency.join_constraints stashed_association_joins, join_type + join_dependency = ActiveRecord::Associations::JoinDependency.new( + @klass, + association_joins, + join_list + ) - join_infos.each do |info| - info.joins.each { |join| manager.from(join) } - manager.bind_values.concat info.binds - end + join_infos = join_dependency.join_constraints stashed_association_joins, join_type - manager.join_sources.concat(join_list) + join_infos.each do |info| + info.joins.each { |join| manager.from(join) } + manager.bind_values.concat info.binds + end - manager - end + manager.join_sources.concat(join_list) - def convert_join_strings_to_ast(table, joins) - joins - .flatten - .reject(&:blank?) - .map { |join| table.create_string_join(Arel.sql(join)) } - end + manager + end - def build_select(arel) - if select_values.any? - arel.project(*arel_columns(select_values.uniq)) - else - arel.project(@klass.arel_table[Arel.star]) + def convert_join_strings_to_ast(table, joins) + joins + .flatten + .reject(&:blank?) + .map { |join| table.create_string_join(Arel.sql(join)) } end - end - def arel_columns(columns) - columns.map do |field| - if (Symbol === field || String === field) && (klass.has_attribute?(field) || klass.attribute_alias?(field)) && !from_clause.value - arel_attribute(field) - elsif Symbol === field - connection.quote_table_name(field.to_s) + def build_select(arel) + if select_values.any? + arel.project(*arel_columns(select_values.uniq)) else - field + arel.project(@klass.arel_table[Arel.star]) end end - end - def reverse_sql_order(order_query) - if order_query.empty? - return [arel_attribute(primary_key).desc] if primary_key - raise IrreversibleOrderError, - "Relation has no current order and table has no primary key to be used as default order" + def arel_columns(columns) + columns.map do |field| + if (Symbol === field || String === field) && (klass.has_attribute?(field) || klass.attribute_alias?(field)) && !from_clause.value + arel_attribute(field) + elsif Symbol === field + connection.quote_table_name(field.to_s) + else + field + end + end end - order_query.flat_map do |o| - case o - when Arel::Attribute - o.desc - when Arel::Nodes::Ordering - o.reverse - when String - if does_not_support_reverse?(o) - raise IrreversibleOrderError, "Order #{o.inspect} can not be reversed automatically" - end - o.split(",").map! do |s| - s.strip! - s.gsub!(/\sasc\Z/i, " DESC") || s.gsub!(/\sdesc\Z/i, " ASC") || s.concat(" DESC") + def reverse_sql_order(order_query) + if order_query.empty? + return [arel_attribute(primary_key).desc] if primary_key + raise IrreversibleOrderError, + "Relation has no current order and table has no primary key to be used as default order" + end + + order_query.flat_map do |o| + case o + when Arel::Attribute + o.desc + when Arel::Nodes::Ordering + o.reverse + when String + if does_not_support_reverse?(o) + raise IrreversibleOrderError, "Order #{o.inspect} can not be reversed automatically" + end + o.split(",").map! do |s| + s.strip! + s.gsub!(/\sasc\Z/i, " DESC") || s.gsub!(/\sdesc\Z/i, " ASC") || s.concat(" DESC") + end + else + o end - else - o end end - end - 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) - end + 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) + end - def build_order(arel) - orders = order_values.uniq - orders.reject!(&:blank?) + def build_order(arel) + orders = order_values.uniq + orders.reject!(&:blank?) - arel.order(*orders) unless orders.empty? - end + arel.order(*orders) unless orders.empty? + end - VALID_DIRECTIONS = [:asc, :desc, :ASC, :DESC, - "asc", "desc", "ASC", "DESC"] # :nodoc: + VALID_DIRECTIONS = [:asc, :desc, :ASC, :DESC, + "asc", "desc", "ASC", "DESC"] # :nodoc: - def validate_order_args(args) - args.each do |arg| - next unless arg.is_a?(Hash) - arg.each do |_key, value| - raise ArgumentError, "Direction \"#{value}\" is invalid. Valid " \ - "directions are: #{VALID_DIRECTIONS.inspect}" unless VALID_DIRECTIONS.include?(value) + def validate_order_args(args) + args.each do |arg| + next unless arg.is_a?(Hash) + arg.each do |_key, value| + raise ArgumentError, "Direction \"#{value}\" is invalid. Valid " \ + "directions are: #{VALID_DIRECTIONS.inspect}" unless VALID_DIRECTIONS.include?(value) + end end end - end - - def preprocess_order_args(order_args) - order_args.map! do |arg| - klass.send(:sanitize_sql_for_order, arg) - end - order_args.flatten! - validate_order_args(order_args) - references = order_args.grep(String) - references.map! { |arg| arg =~ /^([a-zA-Z]\w*)\.(\w+)/ && $1 }.compact! - references!(references) if references.any? - - # if a symbol is given we prepend the quoted table name - order_args.map! do |arg| - case arg - when Symbol - arel_attribute(arg).asc - when Hash - arg.map { |field, dir| - arel_attribute(field).send(dir.downcase) - } - else - arg + def preprocess_order_args(order_args) + order_args.map! do |arg| + klass.send(:sanitize_sql_for_order, arg) end - end.flatten! - end + order_args.flatten! + validate_order_args(order_args) + + references = order_args.grep(String) + references.map! { |arg| arg =~ /^([a-zA-Z]\w*)\.(\w+)/ && $1 }.compact! + references!(references) if references.any? + + # if a symbol is given we prepend the quoted table name + order_args.map! do |arg| + case arg + when Symbol + arel_attribute(arg).asc + when Hash + arg.map { |field, dir| + arel_attribute(field).send(dir.downcase) + } + else + arg + end + end.flatten! + end # Checks to make sure that the arguments are not blank. Note that if some # blank-like object were initially passed into the query method, then this @@ -1204,34 +1204,34 @@ module ActiveRecord # check_if_method_has_arguments!("references", args) # ... # end - def check_if_method_has_arguments!(method_name, args) - if args.blank? - raise ArgumentError, "The method .#{method_name}() must contain arguments." + def check_if_method_has_arguments!(method_name, args) + if args.blank? + raise ArgumentError, "The method .#{method_name}() must contain arguments." + end end - end - def structurally_incompatible_values_for_or(other) - Relation::SINGLE_VALUE_METHODS.reject { |m| send("#{m}_value") == other.send("#{m}_value") } + - (Relation::MULTI_VALUE_METHODS - [:extending]).reject { |m| send("#{m}_values") == other.send("#{m}_values") } + - (Relation::CLAUSE_METHODS - [:having, :where]).reject { |m| send("#{m}_clause") == other.send("#{m}_clause") } - end + def structurally_incompatible_values_for_or(other) + Relation::SINGLE_VALUE_METHODS.reject { |m| send("#{m}_value") == other.send("#{m}_value") } + + (Relation::MULTI_VALUE_METHODS - [:extending]).reject { |m| send("#{m}_values") == other.send("#{m}_values") } + + (Relation::CLAUSE_METHODS - [:having, :where]).reject { |m| send("#{m}_clause") == other.send("#{m}_clause") } + end - def new_where_clause - Relation::WhereClause.empty - end - alias new_having_clause new_where_clause + def new_where_clause + Relation::WhereClause.empty + end + alias new_having_clause new_where_clause - def where_clause_factory - @where_clause_factory ||= Relation::WhereClauseFactory.new(klass, predicate_builder) - end - alias having_clause_factory where_clause_factory + def where_clause_factory + @where_clause_factory ||= Relation::WhereClauseFactory.new(klass, predicate_builder) + end + alias having_clause_factory where_clause_factory - def new_from_clause - Relation::FromClause.empty - end + def new_from_clause + Relation::FromClause.empty + end - def string_containing_comma?(value) - ::String === value && value.include?(",") - end + def string_containing_comma?(value) + ::String === value && value.include?(",") + end end end diff --git a/activerecord/lib/active_record/relation/where_clause.rb b/activerecord/lib/active_record/relation/where_clause.rb index e1376ce00a..402f8acfd1 100644 --- a/activerecord/lib/active_record/relation/where_clause.rb +++ b/activerecord/lib/active_record/relation/where_clause.rb @@ -86,89 +86,89 @@ module ActiveRecord protected - attr_reader :predicates + attr_reader :predicates - def referenced_columns - @referenced_columns ||= begin - equality_nodes = predicates.select { |n| equality_node?(n) } - Set.new(equality_nodes, &:left) + def referenced_columns + @referenced_columns ||= begin + equality_nodes = predicates.select { |n| equality_node?(n) } + Set.new(equality_nodes, &:left) + end end - end private - def predicates_unreferenced_by(other) - predicates.reject do |n| - equality_node?(n) && other.referenced_columns.include?(n.left) + def predicates_unreferenced_by(other) + predicates.reject do |n| + equality_node?(n) && other.referenced_columns.include?(n.left) + end end - end - def equality_node?(node) - node.respond_to?(:operator) && node.operator == :== - end - - def non_conflicting_binds(other) - conflicts = referenced_columns & other.referenced_columns - conflicts.map! { |node| node.name.to_s } - binds.reject { |attr| conflicts.include?(attr.name) } - end + def equality_node?(node) + node.respond_to?(:operator) && node.operator == :== + end - def inverted_predicates - predicates.map { |node| invert_predicate(node) } - end + def non_conflicting_binds(other) + conflicts = referenced_columns & other.referenced_columns + conflicts.map! { |node| node.name.to_s } + binds.reject { |attr| conflicts.include?(attr.name) } + end - def invert_predicate(node) - case node - when NilClass - raise ArgumentError, "Invalid argument for .where.not(), got nil." - when Arel::Nodes::In - Arel::Nodes::NotIn.new(node.left, node.right) - when Arel::Nodes::Equality - Arel::Nodes::NotEqual.new(node.left, node.right) - when String - Arel::Nodes::Not.new(Arel::Nodes::SqlLiteral.new(node)) - else - Arel::Nodes::Not.new(node) + def inverted_predicates + predicates.map { |node| invert_predicate(node) } end - end - def predicates_except(columns) - predicates.reject do |node| + def invert_predicate(node) case node - when Arel::Nodes::Between, Arel::Nodes::In, Arel::Nodes::NotIn, Arel::Nodes::Equality, Arel::Nodes::NotEqual, Arel::Nodes::LessThan, Arel::Nodes::LessThanOrEqual, Arel::Nodes::GreaterThan, Arel::Nodes::GreaterThanOrEqual - subrelation = (node.left.kind_of?(Arel::Attributes::Attribute) ? node.left : node.right) - columns.include?(subrelation.name.to_s) + when NilClass + raise ArgumentError, "Invalid argument for .where.not(), got nil." + when Arel::Nodes::In + Arel::Nodes::NotIn.new(node.left, node.right) + when Arel::Nodes::Equality + Arel::Nodes::NotEqual.new(node.left, node.right) + when String + Arel::Nodes::Not.new(Arel::Nodes::SqlLiteral.new(node)) + else + Arel::Nodes::Not.new(node) end end - end - def binds_except(columns) - binds.reject do |attr| - columns.include?(attr.name) + def predicates_except(columns) + predicates.reject do |node| + case node + when Arel::Nodes::Between, Arel::Nodes::In, Arel::Nodes::NotIn, Arel::Nodes::Equality, Arel::Nodes::NotEqual, Arel::Nodes::LessThan, Arel::Nodes::LessThanOrEqual, Arel::Nodes::GreaterThan, Arel::Nodes::GreaterThanOrEqual + subrelation = (node.left.kind_of?(Arel::Attributes::Attribute) ? node.left : node.right) + columns.include?(subrelation.name.to_s) + end + end end - end - def predicates_with_wrapped_sql_literals - non_empty_predicates.map do |node| - if Arel::Nodes::Equality === node - node - else - wrap_sql_literal(node) + def binds_except(columns) + binds.reject do |attr| + columns.include?(attr.name) end end - end - ARRAY_WITH_EMPTY_STRING = [""] - def non_empty_predicates - predicates - ARRAY_WITH_EMPTY_STRING - end + def predicates_with_wrapped_sql_literals + non_empty_predicates.map do |node| + if Arel::Nodes::Equality === node + node + else + wrap_sql_literal(node) + end + end + end - def wrap_sql_literal(node) - if ::String === node - node = Arel.sql(node) + ARRAY_WITH_EMPTY_STRING = [""] + def non_empty_predicates + predicates - ARRAY_WITH_EMPTY_STRING + end + + def wrap_sql_literal(node) + if ::String === node + node = Arel.sql(node) + end + Arel::Nodes::Grouping.new(node) end - Arel::Nodes::Grouping.new(node) - end end end end diff --git a/activerecord/lib/active_record/relation/where_clause_factory.rb b/activerecord/lib/active_record/relation/where_clause_factory.rb index dbf172a577..038ebbfe21 100644 --- a/activerecord/lib/active_record/relation/where_clause_factory.rb +++ b/activerecord/lib/active_record/relation/where_clause_factory.rb @@ -32,7 +32,7 @@ module ActiveRecord protected - attr_reader :klass, :predicate_builder + attr_reader :klass, :predicate_builder end end end diff --git a/activerecord/lib/active_record/result.rb b/activerecord/lib/active_record/result.rb index b9fd0f5326..f5383f4c14 100644 --- a/activerecord/lib/active_record/result.rb +++ b/activerecord/lib/active_record/result.rb @@ -103,36 +103,36 @@ module ActiveRecord private - def column_type(name, type_overrides = {}) - type_overrides.fetch(name) do - column_types.fetch(name, IDENTITY_TYPE) + def column_type(name, type_overrides = {}) + type_overrides.fetch(name) do + column_types.fetch(name, IDENTITY_TYPE) + end end - end - def hash_rows - @hash_rows ||= - begin - # We freeze the strings to prevent them getting duped when - # used as keys in ActiveRecord::Base's @attributes hash - columns = @columns.map { |c| c.dup.freeze } - @rows.map { |row| - # In the past we used Hash[columns.zip(row)] - # though elegant, the verbose way is much more efficient - # both time and memory wise cause it avoids a big array allocation - # this method is called a lot and needs to be micro optimised - hash = {} - - index = 0 - length = columns.length - - while index < length - hash[columns[index]] = row[index] - index += 1 - end - - hash - } - end - end + def hash_rows + @hash_rows ||= + begin + # We freeze the strings to prevent them getting duped when + # used as keys in ActiveRecord::Base's @attributes hash + columns = @columns.map { |c| c.dup.freeze } + @rows.map { |row| + # In the past we used Hash[columns.zip(row)] + # though elegant, the verbose way is much more efficient + # both time and memory wise cause it avoids a big array allocation + # this method is called a lot and needs to be micro optimised + hash = {} + + index = 0 + length = columns.length + + while index < length + hash[columns[index]] = row[index] + index += 1 + end + + hash + } + end + end end end diff --git a/activerecord/lib/active_record/sanitization.rb b/activerecord/lib/active_record/sanitization.rb index 26679bb1c3..6617008344 100644 --- a/activerecord/lib/active_record/sanitization.rb +++ b/activerecord/lib/active_record/sanitization.rb @@ -28,16 +28,16 @@ module ActiveRecord # # sanitize_sql_for_conditions("name='foo''bar' and group_id='4'") # # => "name='foo''bar' and group_id='4'" - def sanitize_sql_for_conditions(condition) - return nil if condition.blank? + def sanitize_sql_for_conditions(condition) + return nil if condition.blank? - case condition - when Array; sanitize_sql_array(condition) - else condition + case condition + when Array; sanitize_sql_array(condition) + else condition + end end - end - alias_method :sanitize_sql, :sanitize_sql_for_conditions - alias_method :sanitize_conditions, :sanitize_sql + alias_method :sanitize_sql, :sanitize_sql_for_conditions + alias_method :sanitize_conditions, :sanitize_sql # Accepts an array, hash, or string of SQL conditions and sanitizes # them into a valid SQL fragment for a SET clause. @@ -53,13 +53,13 @@ module ActiveRecord # # sanitize_sql_for_assignment("name=NULL and group_id='4'") # # => "name=NULL and group_id='4'" - def sanitize_sql_for_assignment(assignments, default_table_name = self.table_name) - case assignments - when Array; sanitize_sql_array(assignments) - when Hash; sanitize_sql_hash_for_assignment(assignments, default_table_name) - else assignments + def sanitize_sql_for_assignment(assignments, default_table_name = self.table_name) + case assignments + when Array; sanitize_sql_array(assignments) + when Hash; sanitize_sql_hash_for_assignment(assignments, default_table_name) + else assignments + end end - end # Accepts an array, or string of SQL conditions and sanitizes # them into a valid SQL fragment for an ORDER clause. @@ -69,13 +69,13 @@ module ActiveRecord # # sanitize_sql_for_order("id ASC") # # => "id ASC" - def sanitize_sql_for_order(condition) - if condition.is_a?(Array) && condition.first.to_s.include?("?") - sanitize_sql_array(condition) - else - condition + def sanitize_sql_for_order(condition) + if condition.is_a?(Array) && condition.first.to_s.include?("?") + sanitize_sql_array(condition) + else + condition + end end - end # Accepts a hash of SQL conditions and replaces those attributes # that correspond to a {#composed_of}[rdoc-ref:Aggregations::ClassMethods#composed_of] @@ -92,36 +92,36 @@ module ActiveRecord # # { address: Address.new("813 abc st.", "chicago") } # # => { address_street: "813 abc st.", address_city: "chicago" } - def expand_hash_conditions_for_aggregates(attrs) - expanded_attrs = {} - attrs.each do |attr, value| - if aggregation = reflect_on_aggregation(attr.to_sym) - mapping = aggregation.mapping - mapping.each do |field_attr, aggregate_attr| - if mapping.size == 1 && !value.respond_to?(aggregate_attr) - expanded_attrs[field_attr] = value - else - expanded_attrs[field_attr] = value.send(aggregate_attr) + def expand_hash_conditions_for_aggregates(attrs) + expanded_attrs = {} + attrs.each do |attr, value| + if aggregation = reflect_on_aggregation(attr.to_sym) + mapping = aggregation.mapping + mapping.each do |field_attr, aggregate_attr| + if mapping.size == 1 && !value.respond_to?(aggregate_attr) + expanded_attrs[field_attr] = value + else + expanded_attrs[field_attr] = value.send(aggregate_attr) + end end + else + expanded_attrs[attr] = value end - else - expanded_attrs[attr] = value end + expanded_attrs end - expanded_attrs - end # Sanitizes a hash of attribute/value pairs into SQL conditions for a SET clause. # # sanitize_sql_hash_for_assignment({ status: nil, group_id: 1 }, "posts") # # => "`posts`.`status` = NULL, `posts`.`group_id` = 1" - def sanitize_sql_hash_for_assignment(attrs, table) - c = connection - attrs.map do |attr, value| - value = type_for_attribute(attr.to_s).serialize(value) - "#{c.quote_table_name_for_assignment(table, attr)} = #{c.quote(value)}" - end.join(", ") - end + def sanitize_sql_hash_for_assignment(attrs, table) + c = connection + attrs.map do |attr, value| + value = type_for_attribute(attr.to_s).serialize(value) + "#{c.quote_table_name_for_assignment(table, attr)} = #{c.quote(value)}" + end.join(", ") + end # Sanitizes a +string+ so that it is safe to use within an SQL # LIKE statement. This method uses +escape_character+ to escape all occurrences of "\", "_" and "%". @@ -137,10 +137,10 @@ module ActiveRecord # # sanitize_sql_like("snake_cased_string", "!") # # => "snake!_cased!_string" - def sanitize_sql_like(string, escape_character = "\\") - pattern = Regexp.union(escape_character, "%", "_") - string.gsub(pattern) { |x| [escape_character, x].join } - end + def sanitize_sql_like(string, escape_character = "\\") + pattern = Regexp.union(escape_character, "%", "_") + string.gsub(pattern) { |x| [escape_character, x].join } + end # Accepts an array of conditions. The array has each value # sanitized and interpolated into the SQL statement. @@ -153,65 +153,65 @@ module ActiveRecord # # sanitize_sql_array(["name='%s' and group_id='%s'", "foo'bar", 4]) # # => "name='foo''bar' and group_id='4'" - def sanitize_sql_array(ary) - statement, *values = ary - if values.first.is_a?(Hash) && /:\w+/.match?(statement) - replace_named_bind_variables(statement, values.first) - elsif statement.include?("?") - replace_bind_variables(statement, values) - elsif statement.blank? - statement - else - statement % values.collect { |value| connection.quote_string(value.to_s) } + def sanitize_sql_array(ary) + statement, *values = ary + if values.first.is_a?(Hash) && /:\w+/.match?(statement) + replace_named_bind_variables(statement, values.first) + elsif statement.include?("?") + replace_bind_variables(statement, values) + elsif statement.blank? + statement + else + statement % values.collect { |value| connection.quote_string(value.to_s) } + end end - end - def replace_bind_variables(statement, values) # :nodoc: - raise_if_bind_arity_mismatch(statement, statement.count("?"), values.size) - bound = values.dup - c = connection - statement.gsub(/\?/) do - replace_bind_variable(bound.shift, c) + def replace_bind_variables(statement, values) # :nodoc: + raise_if_bind_arity_mismatch(statement, statement.count("?"), values.size) + bound = values.dup + c = connection + statement.gsub(/\?/) do + replace_bind_variable(bound.shift, c) + end end - end - def replace_bind_variable(value, c = connection) # :nodoc: - if ActiveRecord::Relation === value - value.to_sql - else - quote_bound_value(value, c) + def replace_bind_variable(value, c = connection) # :nodoc: + if ActiveRecord::Relation === value + value.to_sql + else + quote_bound_value(value, c) + end end - end - def replace_named_bind_variables(statement, bind_vars) # :nodoc: - statement.gsub(/(:?):([a-zA-Z]\w*)/) do |match| - if $1 == ":" # skip postgresql casts - match # return the whole match - elsif bind_vars.include?(match = $2.to_sym) - replace_bind_variable(bind_vars[match]) - else - raise PreparedStatementInvalid, "missing value for :#{match} in #{statement}" + def replace_named_bind_variables(statement, bind_vars) # :nodoc: + statement.gsub(/(:?):([a-zA-Z]\w*)/) do |match| + if $1 == ":" # skip postgresql casts + match # return the whole match + elsif bind_vars.include?(match = $2.to_sym) + replace_bind_variable(bind_vars[match]) + else + raise PreparedStatementInvalid, "missing value for :#{match} in #{statement}" + end end end - end - def quote_bound_value(value, c = connection) # :nodoc: - if value.respond_to?(:map) && !value.acts_like?(:string) - if value.respond_to?(:empty?) && value.empty? - c.quote(nil) + def quote_bound_value(value, c = connection) # :nodoc: + if value.respond_to?(:map) && !value.acts_like?(:string) + if value.respond_to?(:empty?) && value.empty? + c.quote(nil) + else + value.map { |v| c.quote(v) }.join(",") + end else - value.map { |v| c.quote(v) }.join(",") + c.quote(value) end - else - c.quote(value) end - end - def raise_if_bind_arity_mismatch(statement, expected, provided) # :nodoc: - unless expected == provided - raise PreparedStatementInvalid, "wrong number of bind variables (#{provided} for #{expected}) in: #{statement}" + def raise_if_bind_arity_mismatch(statement, expected, provided) # :nodoc: + unless expected == provided + raise PreparedStatementInvalid, "wrong number of bind variables (#{provided} for #{expected}) in: #{statement}" + end end - end end # TODO: Deprecate this diff --git a/activerecord/lib/active_record/scoping.rb b/activerecord/lib/active_record/scoping.rb index 78231594d4..d1bd1cd89a 100644 --- a/activerecord/lib/active_record/scoping.rb +++ b/activerecord/lib/active_record/scoping.rb @@ -94,11 +94,11 @@ module ActiveRecord private - def raise_invalid_scope_type!(scope_type) - if !VALID_SCOPE_TYPES.include?(scope_type) - raise ArgumentError, "Invalid scope type '#{scope_type}' sent to the registry. Scope types must be included in VALID_SCOPE_TYPES" + def raise_invalid_scope_type!(scope_type) + if !VALID_SCOPE_TYPES.include?(scope_type) + raise ArgumentError, "Invalid scope type '#{scope_type}' sent to the registry. Scope types must be included in VALID_SCOPE_TYPES" + end end - end end end end diff --git a/activerecord/lib/active_record/scoping/default.rb b/activerecord/lib/active_record/scoping/default.rb index 9eab59ac78..572a45aac9 100644 --- a/activerecord/lib/active_record/scoping/default.rb +++ b/activerecord/lib/active_record/scoping/default.rb @@ -87,62 +87,62 @@ module ActiveRecord # # Should return a scope, you can call 'super' here etc. # end # end - def default_scope(scope = nil) - scope = Proc.new if block_given? - - if scope.is_a?(Relation) || !scope.respond_to?(:call) - raise ArgumentError, - "Support for calling #default_scope without a block is removed. For example instead " \ - "of `default_scope where(color: 'red')`, please use " \ - "`default_scope { where(color: 'red') }`. (Alternatively you can just redefine " \ - "self.default_scope.)" - end + def default_scope(scope = nil) + scope = Proc.new if block_given? + + if scope.is_a?(Relation) || !scope.respond_to?(:call) + raise ArgumentError, + "Support for calling #default_scope without a block is removed. For example instead " \ + "of `default_scope where(color: 'red')`, please use " \ + "`default_scope { where(color: 'red') }`. (Alternatively you can just redefine " \ + "self.default_scope.)" + end - self.default_scopes += [scope] - end + self.default_scopes += [scope] + end - def build_default_scope(base_rel = nil) # :nodoc: - return if abstract_class? + def build_default_scope(base_rel = nil) # :nodoc: + return if abstract_class? - if self.default_scope_override.nil? - self.default_scope_override = !Base.is_a?(method(:default_scope).owner) - end + if self.default_scope_override.nil? + self.default_scope_override = !Base.is_a?(method(:default_scope).owner) + end - if self.default_scope_override - # The user has defined their own default scope method, so call that - evaluate_default_scope { default_scope } - elsif default_scopes.any? - base_rel ||= relation - evaluate_default_scope do - default_scopes.inject(base_rel) do |default_scope, scope| - scope = scope.respond_to?(:to_proc) ? scope : scope.method(:call) - default_scope.merge(base_rel.instance_exec(&scope)) + if self.default_scope_override + # The user has defined their own default scope method, so call that + evaluate_default_scope { default_scope } + elsif default_scopes.any? + base_rel ||= relation + evaluate_default_scope do + default_scopes.inject(base_rel) do |default_scope, scope| + scope = scope.respond_to?(:to_proc) ? scope : scope.method(:call) + default_scope.merge(base_rel.instance_exec(&scope)) + end end end end - end - def ignore_default_scope? # :nodoc: - ScopeRegistry.value_for(:ignore_default_scope, base_class) - end + def ignore_default_scope? # :nodoc: + ScopeRegistry.value_for(:ignore_default_scope, base_class) + end - def ignore_default_scope=(ignore) # :nodoc: - ScopeRegistry.set_value_for(:ignore_default_scope, base_class, ignore) - end + def ignore_default_scope=(ignore) # :nodoc: + ScopeRegistry.set_value_for(:ignore_default_scope, base_class, ignore) + end # The ignore_default_scope flag is used to prevent an infinite recursion # situation where a default scope references a scope which has a default # scope which references a scope... - def evaluate_default_scope # :nodoc: - return if ignore_default_scope? - - begin - self.ignore_default_scope = true - yield - ensure - self.ignore_default_scope = false + def evaluate_default_scope # :nodoc: + return if ignore_default_scope? + + begin + self.ignore_default_scope = true + yield + ensure + self.ignore_default_scope = false + end end - end end end end diff --git a/activerecord/lib/active_record/store.rb b/activerecord/lib/active_record/store.rb index 2169d64137..f6bf2c7e48 100644 --- a/activerecord/lib/active_record/store.rb +++ b/activerecord/lib/active_record/store.rb @@ -177,34 +177,34 @@ module ActiveRecord end end - class IndifferentCoder # :nodoc: - def initialize(coder_or_class_name) - @coder = - if coder_or_class_name.respond_to?(:load) && coder_or_class_name.respond_to?(:dump) - coder_or_class_name - else - ActiveRecord::Coders::YAMLColumn.new(coder_or_class_name || Object) - end - end + class IndifferentCoder # :nodoc: + def initialize(coder_or_class_name) + @coder = + if coder_or_class_name.respond_to?(:load) && coder_or_class_name.respond_to?(:dump) + coder_or_class_name + else + ActiveRecord::Coders::YAMLColumn.new(coder_or_class_name || Object) + end + end - def dump(obj) - @coder.dump self.class.as_indifferent_hash(obj) - end + def dump(obj) + @coder.dump self.class.as_indifferent_hash(obj) + end - def load(yaml) - self.class.as_indifferent_hash(@coder.load(yaml || "")) - end + def load(yaml) + self.class.as_indifferent_hash(@coder.load(yaml || "")) + end - def self.as_indifferent_hash(obj) - case obj - when ActiveSupport::HashWithIndifferentAccess - obj - when Hash - obj.with_indifferent_access - else - ActiveSupport::HashWithIndifferentAccess.new + def self.as_indifferent_hash(obj) + case obj + when ActiveSupport::HashWithIndifferentAccess + obj + when Hash + obj.with_indifferent_access + else + ActiveSupport::HashWithIndifferentAccess.new + end end end - end end end diff --git a/activerecord/lib/active_record/table_metadata.rb b/activerecord/lib/active_record/table_metadata.rb index 5fe0d8b5e4..e8d6a144f9 100644 --- a/activerecord/lib/active_record/table_metadata.rb +++ b/activerecord/lib/active_record/table_metadata.rb @@ -64,6 +64,6 @@ module ActiveRecord protected - attr_reader :klass, :arel_table, :association + attr_reader :klass, :arel_table, :association end end diff --git a/activerecord/lib/active_record/tasks/database_tasks.rb b/activerecord/lib/active_record/tasks/database_tasks.rb index 269a1488f5..c0764fc4ab 100644 --- a/activerecord/lib/active_record/tasks/database_tasks.rb +++ b/activerecord/lib/active_record/tasks/database_tasks.rb @@ -77,7 +77,7 @@ module ActiveRecord def fixtures_path @fixtures_path ||= if ENV["FIXTURES_PATH"] - File.join(root, ENV["FIXTURES_PATH"]) + File.join(root, ENV["FIXTURES_PATH"]) else File.join(root, "test", "fixtures") end @@ -275,39 +275,39 @@ module ActiveRecord private - def class_for_adapter(adapter) - key = @tasks.keys.detect { |pattern| adapter[pattern] } - unless key - raise DatabaseNotSupported, "Rake tasks not supported by '#{adapter}' adapter" + def class_for_adapter(adapter) + key = @tasks.keys.detect { |pattern| adapter[pattern] } + unless key + raise DatabaseNotSupported, "Rake tasks not supported by '#{adapter}' adapter" + end + @tasks[key] end - @tasks[key] - end - def each_current_configuration(environment) - environments = [environment] - environments << "test" if environment == "development" + def each_current_configuration(environment) + environments = [environment] + environments << "test" if environment == "development" - configurations = ActiveRecord::Base.configurations.values_at(*environments) - configurations.compact.each do |configuration| - yield configuration unless configuration["database"].blank? + configurations = ActiveRecord::Base.configurations.values_at(*environments) + configurations.compact.each do |configuration| + yield configuration unless configuration["database"].blank? + end end - end - def each_local_configuration - ActiveRecord::Base.configurations.each_value do |configuration| - next unless configuration["database"] + def each_local_configuration + ActiveRecord::Base.configurations.each_value do |configuration| + next unless configuration["database"] - if local_database?(configuration) - yield configuration - else - $stderr.puts "This task only modifies local databases. #{configuration['database']} is on a remote host." + if local_database?(configuration) + yield configuration + else + $stderr.puts "This task only modifies local databases. #{configuration['database']} is on a remote host." + end end end - end - def local_database?(configuration) - configuration["host"].blank? || LOCAL_HOSTS.include?(configuration["host"]) - end + def local_database?(configuration) + configuration["host"].blank? || LOCAL_HOSTS.include?(configuration["host"]) + end end end end diff --git a/activerecord/lib/active_record/tasks/mysql_database_tasks.rb b/activerecord/lib/active_record/tasks/mysql_database_tasks.rb index d10c1b05cd..c8b89f1fdf 100644 --- a/activerecord/lib/active_record/tasks/mysql_database_tasks.rb +++ b/activerecord/lib/active_record/tasks/mysql_database_tasks.rb @@ -74,79 +74,79 @@ module ActiveRecord private - def configuration - @configuration - end + def configuration + @configuration + end - def configuration_without_database - configuration.merge("database" => nil) - end + def configuration_without_database + configuration.merge("database" => nil) + end - def creation_options - Hash.new.tap do |options| - options[:charset] = configuration["encoding"] if configuration.include? "encoding" - options[:collation] = configuration["collation"] if configuration.include? "collation" + def creation_options + Hash.new.tap do |options| + options[:charset] = configuration["encoding"] if configuration.include? "encoding" + options[:collation] = configuration["collation"] if configuration.include? "collation" + end end - end - def error_class - if configuration["adapter"].include?("jdbc") - require "active_record/railties/jdbcmysql_error" - ArJdbcMySQL::Error - elsif defined?(Mysql2) - Mysql2::Error - else - StandardError + def error_class + if configuration["adapter"].include?("jdbc") + require "active_record/railties/jdbcmysql_error" + ArJdbcMySQL::Error + elsif defined?(Mysql2) + Mysql2::Error + else + StandardError + end end - end - def grant_statement - <<-SQL + def grant_statement + <<-SQL GRANT ALL PRIVILEGES ON #{configuration['database']}.* TO '#{configuration['username']}'@'localhost' IDENTIFIED BY '#{configuration['password']}' WITH GRANT OPTION; SQL - end + end - def root_configuration_without_database - configuration_without_database.merge( - "username" => "root", - "password" => root_password - ) - end + def root_configuration_without_database + configuration_without_database.merge( + "username" => "root", + "password" => root_password + ) + end - def root_password - $stdout.print "Please provide the root password for your MySQL installation\n>" - $stdin.gets.strip - end + def root_password + $stdout.print "Please provide the root password for your MySQL installation\n>" + $stdin.gets.strip + end - def prepare_command_options - args = { - "host" => "--host", - "port" => "--port", - "socket" => "--socket", - "username" => "--user", - "password" => "--password", - "encoding" => "--default-character-set", - "sslca" => "--ssl-ca", - "sslcert" => "--ssl-cert", - "sslcapath" => "--ssl-capath", - "sslcipher" => "--ssl-cipher", - "sslkey" => "--ssl-key" - }.map { |opt, arg| "#{arg}=#{configuration[opt]}" if configuration[opt] }.compact - - args - end + def prepare_command_options + args = { + "host" => "--host", + "port" => "--port", + "socket" => "--socket", + "username" => "--user", + "password" => "--password", + "encoding" => "--default-character-set", + "sslca" => "--ssl-ca", + "sslcert" => "--ssl-cert", + "sslcapath" => "--ssl-capath", + "sslcipher" => "--ssl-cipher", + "sslkey" => "--ssl-key" + }.map { |opt, arg| "#{arg}=#{configuration[opt]}" if configuration[opt] }.compact + + args + end - def run_cmd(cmd, args, action) - fail run_cmd_error(cmd, args, action) unless Kernel.system(cmd, *args) - end + def run_cmd(cmd, args, action) + fail run_cmd_error(cmd, args, action) unless Kernel.system(cmd, *args) + end - def run_cmd_error(cmd, args, action) - msg = "failed to execute: `#{cmd}`\n" - msg << "Please check the output above for any errors and make sure that `#{cmd}` is installed in your PATH and has proper permissions.\n\n" - msg - end + def run_cmd_error(cmd, args, action) + msg = "failed to execute: `#{cmd}`\n" + msg << "Please check the output above for any errors and make sure that `#{cmd}` is installed in your PATH and has proper permissions.\n\n" + msg + end end end end diff --git a/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb b/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb index d290b12b73..c9e7262709 100644 --- a/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb +++ b/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb @@ -74,38 +74,38 @@ module ActiveRecord private - def configuration - @configuration - end + def configuration + @configuration + end - def encoding - configuration["encoding"] || DEFAULT_ENCODING - end + def encoding + configuration["encoding"] || DEFAULT_ENCODING + end - def establish_master_connection - establish_connection configuration.merge( - "database" => "postgres", - "schema_search_path" => "public" - ) - end + def establish_master_connection + establish_connection configuration.merge( + "database" => "postgres", + "schema_search_path" => "public" + ) + end - def set_psql_env - ENV["PGHOST"] = configuration["host"] if configuration["host"] - ENV["PGPORT"] = configuration["port"].to_s if configuration["port"] - ENV["PGPASSWORD"] = configuration["password"].to_s if configuration["password"] - ENV["PGUSER"] = configuration["username"].to_s if configuration["username"] - end + def set_psql_env + ENV["PGHOST"] = configuration["host"] if configuration["host"] + ENV["PGPORT"] = configuration["port"].to_s if configuration["port"] + ENV["PGPASSWORD"] = configuration["password"].to_s if configuration["password"] + ENV["PGUSER"] = configuration["username"].to_s if configuration["username"] + end - def run_cmd(cmd, args, action) - fail run_cmd_error(cmd, args, action) unless Kernel.system(cmd, *args) - end + def run_cmd(cmd, args, action) + fail run_cmd_error(cmd, args, action) unless Kernel.system(cmd, *args) + end - def run_cmd_error(cmd, args, action) - msg = "failed to execute:\n" - msg << "#{cmd} #{args.join(' ')}\n\n" - msg << "Please check the output above for any errors and make sure that `#{cmd}` is installed in your PATH and has proper permissions.\n\n" - msg - end + def run_cmd_error(cmd, args, action) + msg = "failed to execute:\n" + msg << "#{cmd} #{args.join(' ')}\n\n" + msg << "Please check the output above for any errors and make sure that `#{cmd}` is installed in your PATH and has proper permissions.\n\n" + msg + end end end end diff --git a/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb b/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb index 8533fb6aa5..31f1b7efd4 100644 --- a/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb +++ b/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb @@ -47,13 +47,13 @@ module ActiveRecord private - def configuration - @configuration - end + def configuration + @configuration + end - def root - @root - end + def root + @root + end end end end diff --git a/activerecord/lib/active_record/transactions.rb b/activerecord/lib/active_record/transactions.rb index a140dd236f..b19ae5c46e 100644 --- a/activerecord/lib/active_record/transactions.rb +++ b/activerecord/lib/active_record/transactions.rb @@ -286,23 +286,23 @@ module ActiveRecord private - def set_options_for_callbacks!(args, enforced_options = {}) - options = args.extract_options!.merge!(enforced_options) - args << options - - if options[:on] - fire_on = Array(options[:on]) - assert_valid_transaction_action(fire_on) - options[:if] = Array(options[:if]) - options[:if] << "transaction_include_any_action?(#{fire_on})" + def set_options_for_callbacks!(args, enforced_options = {}) + options = args.extract_options!.merge!(enforced_options) + args << options + + if options[:on] + fire_on = Array(options[:on]) + assert_valid_transaction_action(fire_on) + options[:if] = Array(options[:if]) + options[:if] << "transaction_include_any_action?(#{fire_on})" + end end - end - def assert_valid_transaction_action(actions) - if (actions - ACTIONS).any? - raise ArgumentError, ":on conditions for after_commit and after_rollback callbacks have to be one of #{ACTIONS}" + def assert_valid_transaction_action(actions) + if (actions - ACTIONS).any? + raise ArgumentError, ":on conditions for after_commit and after_rollback callbacks have to be one of #{ACTIONS}" + end end - end end # See ActiveRecord::Transactions::ClassMethods for detailed documentation. @@ -410,73 +410,73 @@ module ActiveRecord protected # Save the new record state and id of a record so it can be restored later if a transaction fails. - def remember_transaction_record_state #:nodoc: - @_start_transaction_state[:id] = id - @_start_transaction_state.reverse_merge!( - new_record: @new_record, - destroyed: @destroyed, - frozen?: frozen?, - ) - @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) + 1 - end + def remember_transaction_record_state #:nodoc: + @_start_transaction_state[:id] = id + @_start_transaction_state.reverse_merge!( + new_record: @new_record, + destroyed: @destroyed, + frozen?: frozen?, + ) + @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) + 1 + end # Clear the new record state and id of a record. - def clear_transaction_record_state #:nodoc: - @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1 - force_clear_transaction_record_state if @_start_transaction_state[:level] < 1 - end + def clear_transaction_record_state #:nodoc: + @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1 + force_clear_transaction_record_state if @_start_transaction_state[:level] < 1 + end # Force to clear the transaction record state. - def force_clear_transaction_record_state #:nodoc: - @_start_transaction_state.clear - end + def force_clear_transaction_record_state #:nodoc: + @_start_transaction_state.clear + end # Restore the new record state and id of a record that was previously saved by a call to save_record_state. - def restore_transaction_record_state(force = false) #:nodoc: - unless @_start_transaction_state.empty? - transaction_level = (@_start_transaction_state[:level] || 0) - 1 - if transaction_level < 1 || force - restore_state = @_start_transaction_state - thaw - @new_record = restore_state[:new_record] - @destroyed = restore_state[:destroyed] - pk = self.class.primary_key - if pk && read_attribute(pk) != restore_state[:id] - write_attribute(pk, restore_state[:id]) + def restore_transaction_record_state(force = false) #:nodoc: + unless @_start_transaction_state.empty? + transaction_level = (@_start_transaction_state[:level] || 0) - 1 + if transaction_level < 1 || force + restore_state = @_start_transaction_state + thaw + @new_record = restore_state[:new_record] + @destroyed = restore_state[:destroyed] + pk = self.class.primary_key + if pk && read_attribute(pk) != restore_state[:id] + write_attribute(pk, restore_state[:id]) + end + freeze if restore_state[:frozen?] end - freeze if restore_state[:frozen?] end end - end # Determine if a record was created or destroyed in a transaction. State should be one of :new_record or :destroyed. - def transaction_record_state(state) #:nodoc: - @_start_transaction_state[state] - end + def transaction_record_state(state) #:nodoc: + @_start_transaction_state[state] + end # Determine if a transaction included an action for :create, :update, or :destroy. Used in filtering callbacks. - def transaction_include_any_action?(actions) #:nodoc: - actions.any? do |action| - case action - when :create - transaction_record_state(:new_record) - when :destroy - destroyed? - when :update - !(transaction_record_state(:new_record) || destroyed?) + def transaction_include_any_action?(actions) #:nodoc: + actions.any? do |action| + case action + when :create + transaction_record_state(:new_record) + when :destroy + destroyed? + when :update + !(transaction_record_state(:new_record) || destroyed?) + end end end - end private - def set_transaction_state(state) # :nodoc: - @transaction_state = state - end + def set_transaction_state(state) # :nodoc: + @transaction_state = state + end - def has_transactional_callbacks? # :nodoc: - !_rollback_callbacks.empty? || !_commit_callbacks.empty? || !_before_commit_callbacks.empty? - end + def has_transactional_callbacks? # :nodoc: + !_rollback_callbacks.empty? || !_commit_callbacks.empty? || !_before_commit_callbacks.empty? + end # Updates the attributes on this particular Active Record object so that # if it's associated with a transaction, then the state of the Active Record @@ -495,15 +495,15 @@ module ActiveRecord # Since Active Record objects can be inside multiple transactions, this # method recursively goes through the parent of the TransactionState and # checks if the Active Record object reflects the state of the object. - def sync_with_transaction_state - update_attributes_from_transaction_state(@transaction_state) - end + def sync_with_transaction_state + update_attributes_from_transaction_state(@transaction_state) + end - def update_attributes_from_transaction_state(transaction_state) - if transaction_state && transaction_state.finalized? - restore_transaction_record_state if transaction_state.rolledback? - clear_transaction_record_state + def update_attributes_from_transaction_state(transaction_state) + if transaction_state && transaction_state.finalized? + restore_transaction_record_state if transaction_state.rolledback? + clear_transaction_record_state + end end - end end end diff --git a/activerecord/lib/active_record/type/adapter_specific_registry.rb b/activerecord/lib/active_record/type/adapter_specific_registry.rb index 208bc8def5..d0f9581576 100644 --- a/activerecord/lib/active_record/type/adapter_specific_registry.rb +++ b/activerecord/lib/active_record/type/adapter_specific_registry.rb @@ -10,15 +10,15 @@ module ActiveRecord private - def registration_klass - Registration - end + def registration_klass + Registration + end - def find_registration(symbol, *args) - registrations - .select { |registration| registration.matches?(symbol, *args) } - .max - end + def find_registration(symbol, *args) + registrations + .select { |registration| registration.matches?(symbol, *args) } + .max + end end class Registration @@ -52,42 +52,42 @@ module ActiveRecord protected - attr_reader :name, :block, :adapter, :override - - def priority - result = 0 - if adapter - result |= 1 - end - if override - result |= 2 + attr_reader :name, :block, :adapter, :override + + def priority + result = 0 + if adapter + result |= 1 + end + if override + result |= 2 + end + result end - result - end - def priority_except_adapter - priority & 0b111111100 - end + def priority_except_adapter + priority & 0b111111100 + end private - def matches_adapter?(adapter: nil, **) - (self.adapter.nil? || adapter == self.adapter) - end + def matches_adapter?(adapter: nil, **) + (self.adapter.nil? || adapter == self.adapter) + end - def conflicts_with?(other) - same_priority_except_adapter?(other) && - has_adapter_conflict?(other) - end + def conflicts_with?(other) + same_priority_except_adapter?(other) && + has_adapter_conflict?(other) + end - def same_priority_except_adapter?(other) - priority_except_adapter == other.priority_except_adapter - end + def same_priority_except_adapter?(other) + priority_except_adapter == other.priority_except_adapter + end - def has_adapter_conflict?(other) - (override.nil? && other.adapter) || - (adapter && other.override.nil?) - end + def has_adapter_conflict?(other) + (override.nil? && other.adapter) || + (adapter && other.override.nil?) + end end class DecorationRegistration < Registration @@ -112,15 +112,15 @@ module ActiveRecord protected - attr_reader :options, :klass + attr_reader :options, :klass private - def matches_options?(**kwargs) - options.all? do |key, value| - kwargs[key] == value + def matches_options?(**kwargs) + options.all? do |key, value| + kwargs[key] == value + end end - end end end diff --git a/activerecord/lib/active_record/type/hash_lookup_type_map.rb b/activerecord/lib/active_record/type/hash_lookup_type_map.rb index 3b01e3f8ca..0145d5d6c1 100644 --- a/activerecord/lib/active_record/type/hash_lookup_type_map.rb +++ b/activerecord/lib/active_record/type/hash_lookup_type_map.rb @@ -15,9 +15,9 @@ module ActiveRecord private - def perform_fetch(type, *args, &block) - @mapping.fetch(type, block).call(type, *args) - end + def perform_fetch(type, *args, &block) + @mapping.fetch(type, block).call(type, *args) + end end end end diff --git a/activerecord/lib/active_record/type/serialized.rb b/activerecord/lib/active_record/type/serialized.rb index a3a5241780..ac9134bfcb 100644 --- a/activerecord/lib/active_record/type/serialized.rb +++ b/activerecord/lib/active_record/type/serialized.rb @@ -49,15 +49,15 @@ module ActiveRecord private - def default_value?(value) - value == coder.load(nil) - end + def default_value?(value) + value == coder.load(nil) + end - def encoded(value) - unless default_value?(value) - coder.dump(value) + def encoded(value) + unless default_value?(value) + coder.dump(value) + end end - end end end end diff --git a/activerecord/lib/active_record/type/time.rb b/activerecord/lib/active_record/type/time.rb index 7da49e43c7..b9bac87c67 100644 --- a/activerecord/lib/active_record/type/time.rb +++ b/activerecord/lib/active_record/type/time.rb @@ -17,4 +17,3 @@ module ActiveRecord end end end - diff --git a/activerecord/lib/active_record/type/type_map.rb b/activerecord/lib/active_record/type/type_map.rb index 1f744ef115..9618ff8787 100644 --- a/activerecord/lib/active_record/type/type_map.rb +++ b/activerecord/lib/active_record/type/type_map.rb @@ -44,21 +44,21 @@ module ActiveRecord private - def perform_fetch(lookup_key, *args) - matching_pair = @mapping.reverse_each.detect do |key, _| - key === lookup_key - end + def perform_fetch(lookup_key, *args) + matching_pair = @mapping.reverse_each.detect do |key, _| + key === lookup_key + end - if matching_pair - matching_pair.last.call(lookup_key, *args) - else - yield lookup_key, *args + if matching_pair + matching_pair.last.call(lookup_key, *args) + else + yield lookup_key, *args + end end - end - def default_value - @default_value ||= ActiveModel::Type::Value.new - end + def default_value + @default_value ||= ActiveModel::Type::Value.new + end end end end diff --git a/activerecord/lib/active_record/type_caster/connection.rb b/activerecord/lib/active_record/type_caster/connection.rb index 7ed8dcc313..6c54792e26 100644 --- a/activerecord/lib/active_record/type_caster/connection.rb +++ b/activerecord/lib/active_record/type_caster/connection.rb @@ -14,16 +14,16 @@ module ActiveRecord protected - attr_reader :table_name - delegate :connection, to: :@klass + attr_reader :table_name + delegate :connection, to: :@klass private - def column_for(attribute_name) - if connection.schema_cache.data_source_exists?(table_name) - connection.schema_cache.columns_hash(table_name)[attribute_name.to_s] + def column_for(attribute_name) + if connection.schema_cache.data_source_exists?(table_name) + connection.schema_cache.columns_hash(table_name)[attribute_name.to_s] + end end - end end end end diff --git a/activerecord/lib/active_record/type_caster/map.rb b/activerecord/lib/active_record/type_caster/map.rb index 3a367b3999..52529a6b42 100644 --- a/activerecord/lib/active_record/type_caster/map.rb +++ b/activerecord/lib/active_record/type_caster/map.rb @@ -13,7 +13,7 @@ module ActiveRecord protected - attr_reader :types + attr_reader :types end end end 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 66ef62a76c..76182a3c24 100644 --- a/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb +++ b/activerecord/lib/rails/generators/active_record/migration/migration_generator.rb @@ -15,43 +15,43 @@ module ActiveRecord end protected - attr_reader :migration_action, :join_tables + attr_reader :migration_action, :join_tables # Sets the default migration template that is being used for the generation of the migration. # Depending on command line arguments, the migration template and the table name instance # variables are set up. - def set_local_assigns! - @migration_template = "migration.rb" - case file_name - when /^(add|remove)_.*_(?:to|from)_(.*)/ - @migration_action = $1 - @table_name = normalize_table_name($2) - when /join_table/ - if attributes.length == 2 - @migration_action = "join" - @join_tables = pluralize_table_names? ? attributes.map(&:plural_name) : attributes.map(&:singular_name) + def set_local_assigns! + @migration_template = "migration.rb" + case file_name + when /^(add|remove)_.*_(?:to|from)_(.*)/ + @migration_action = $1 + @table_name = normalize_table_name($2) + when /join_table/ + if attributes.length == 2 + @migration_action = "join" + @join_tables = pluralize_table_names? ? attributes.map(&:plural_name) : attributes.map(&:singular_name) - set_index_names + set_index_names + end + when /^create_(.+)/ + @table_name = normalize_table_name($1) + @migration_template = "create_table_migration.rb" end - when /^create_(.+)/ - @table_name = normalize_table_name($1) - @migration_template = "create_table_migration.rb" end - end - def set_index_names - attributes.each_with_index do |attr, i| - attr.index_name = [attr, attributes[i - 1]].map{ |a| index_name_for(a) } + def set_index_names + attributes.each_with_index do |attr, i| + attr.index_name = [attr, attributes[i - 1]].map{ |a| index_name_for(a) } + end end - end - def index_name_for(attribute) - if attribute.foreign_key? - attribute.name - else - attribute.name.singularize.foreign_key - end.to_sym - end + def index_name_for(attribute) + if attribute.foreign_key? + attribute.name + else + attribute.name.singularize.foreign_key + end.to_sym + end private def attributes_with_index diff --git a/activerecord/test/cases/adapters/mysql2/connection_test.rb b/activerecord/test/cases/adapters/mysql2/connection_test.rb index 475269d5cb..a3f83e73a6 100644 --- a/activerecord/test/cases/adapters/mysql2/connection_test.rb +++ b/activerecord/test/cases/adapters/mysql2/connection_test.rb @@ -167,7 +167,7 @@ class Mysql2ConnectionTest < ActiveRecord::Mysql2TestCase protected - def test_lock_free(lock_name) - @connection.select_value("SELECT IS_FREE_LOCK(#{@connection.quote(lock_name)})") == 1 - end + def test_lock_free(lock_name) + @connection.select_value("SELECT IS_FREE_LOCK(#{@connection.quote(lock_name)})") == 1 + end end diff --git a/activerecord/test/cases/adapters/mysql2/json_test.rb b/activerecord/test/cases/adapters/mysql2/json_test.rb index 87b6a07f65..f0e670d4b8 100644 --- a/activerecord/test/cases/adapters/mysql2/json_test.rb +++ b/activerecord/test/cases/adapters/mysql2/json_test.rb @@ -2,178 +2,178 @@ require "cases/helper" require "support/schema_dumping_helper" if ActiveRecord::Base.connection.supports_json? -class Mysql2JSONTest < ActiveRecord::Mysql2TestCase - include SchemaDumpingHelper - self.use_transactional_tests = false + class Mysql2JSONTest < ActiveRecord::Mysql2TestCase + include SchemaDumpingHelper + self.use_transactional_tests = false - class JsonDataType < ActiveRecord::Base - self.table_name = "json_data_type" + class JsonDataType < ActiveRecord::Base + self.table_name = "json_data_type" - store_accessor :settings, :resolution - end + store_accessor :settings, :resolution + end - def setup - @connection = ActiveRecord::Base.connection - begin - @connection.create_table("json_data_type") do |t| - t.json "payload" - t.json "settings" + def setup + @connection = ActiveRecord::Base.connection + begin + @connection.create_table("json_data_type") do |t| + t.json "payload" + t.json "settings" + end end end - end - def teardown - @connection.drop_table :json_data_type, if_exists: true - JsonDataType.reset_column_information - end + def teardown + @connection.drop_table :json_data_type, if_exists: true + JsonDataType.reset_column_information + end - def test_column - column = JsonDataType.columns_hash["payload"] - assert_equal :json, column.type - assert_equal "json", column.sql_type + def test_column + column = JsonDataType.columns_hash["payload"] + assert_equal :json, column.type + assert_equal "json", column.sql_type - type = JsonDataType.type_for_attribute("payload") - assert_not type.binary? - end + type = JsonDataType.type_for_attribute("payload") + assert_not type.binary? + end - def test_change_table_supports_json - @connection.change_table("json_data_type") do |t| - t.json "users" + def test_change_table_supports_json + @connection.change_table("json_data_type") do |t| + t.json "users" + end + JsonDataType.reset_column_information + column = JsonDataType.columns_hash["users"] + assert_equal :json, column.type end - JsonDataType.reset_column_information - column = JsonDataType.columns_hash["users"] - assert_equal :json, column.type - end - def test_schema_dumping - output = dump_table_schema("json_data_type") - assert_match(/t\.json\s+"settings"/, output) - end + def test_schema_dumping + output = dump_table_schema("json_data_type") + assert_match(/t\.json\s+"settings"/, output) + 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.save - assert_equal({"string" => "foo", "symbol" => "bar"}, x.reload.payload) - 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.save + assert_equal({"string" => "foo", "symbol" => "bar"}, x.reload.payload) + end - def test_type_cast_json - type = JsonDataType.type_for_attribute("payload") + def test_type_cast_json + type = JsonDataType.type_for_attribute("payload") - 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)) + 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({}, 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"}))) - end + 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"}))) + end - def test_rewrite - @connection.execute "insert into json_data_type (payload) VALUES ('{\"k\":\"v\"}')" - x = JsonDataType.first - x.payload = { '"a\'' => "b" } - assert x.save! - end + def test_rewrite + @connection.execute "insert into json_data_type (payload) VALUES ('{\"k\":\"v\"}')" + x = JsonDataType.first + x.payload = { '"a\'' => "b" } + assert x.save! + end - def test_select - @connection.execute "insert into json_data_type (payload) VALUES ('{\"k\":\"v\"}')" - x = JsonDataType.first - assert_equal({"k" => "v"}, x.payload) - end + def test_select + @connection.execute "insert into json_data_type (payload) VALUES ('{\"k\":\"v\"}')" + x = JsonDataType.first + 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) - 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) + end - def test_null_json - @connection.execute %q|insert into json_data_type (payload) VALUES(null)| - x = JsonDataType.first - assert_equal(nil, x.payload) - end + def test_null_json + @connection.execute %q|insert into json_data_type (payload) VALUES(null)| + x = JsonDataType.first + assert_equal(nil, x.payload) + end - 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) - end + 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) + 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"] - assert x.save! - 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"] + assert x.save! + end - def test_with_store_accessors - x = JsonDataType.new(resolution: "320×480") - assert_equal "320×480", x.resolution + def test_with_store_accessors + x = JsonDataType.new(resolution: "320×480") + assert_equal "320×480", x.resolution - x.save! - x = JsonDataType.first - assert_equal "320×480", x.resolution + x.save! + x = JsonDataType.first + assert_equal "320×480", x.resolution - x.resolution = "640×1136" - x.save! + x.resolution = "640×1136" + x.save! - x = JsonDataType.first - assert_equal "640×1136", x.resolution - end + x = JsonDataType.first + assert_equal "640×1136", x.resolution + end - def test_duplication_with_store_accessors - x = JsonDataType.new(resolution: "320×480") - assert_equal "320×480", x.resolution + def test_duplication_with_store_accessors + x = JsonDataType.new(resolution: "320×480") + assert_equal "320×480", x.resolution - y = x.dup - assert_equal "320×480", y.resolution - end + y = x.dup + assert_equal "320×480", y.resolution + end - def test_yaml_round_trip_with_store_accessors - x = JsonDataType.new(resolution: "320×480") - assert_equal "320×480", x.resolution + def test_yaml_round_trip_with_store_accessors + x = JsonDataType.new(resolution: "320×480") + assert_equal "320×480", x.resolution - y = YAML.load(YAML.dump(x)) - assert_equal "320×480", y.resolution - end + y = YAML.load(YAML.dump(x)) + assert_equal "320×480", y.resolution + end - def test_changes_in_place - json = JsonDataType.new - assert_not json.changed? + def test_changes_in_place + json = JsonDataType.new + assert_not json.changed? - json.payload = { "one" => "two" } - assert json.changed? - assert json.payload_changed? + json.payload = { "one" => "two" } + assert json.changed? + assert json.payload_changed? - json.save! - assert_not json.changed? + json.save! + assert_not json.changed? - json.payload["three"] = "four" - assert json.payload_changed? + json.payload["three"] = "four" + assert json.payload_changed? - json.save! - json.reload + json.save! + json.reload - assert_equal({ "one" => "two", "three" => "four" }, json.payload) - assert_not json.changed? - end + assert_equal({ "one" => "two", "three" => "four" }, json.payload) + assert_not json.changed? + end - def test_assigning_string_literal - json = JsonDataType.create(payload: "foo") - assert_equal "foo", json.payload - end + def test_assigning_string_literal + json = JsonDataType.create(payload: "foo") + assert_equal "foo", json.payload + end - def test_assigning_number - json = JsonDataType.create(payload: 1.234) - assert_equal 1.234, json.payload - end + def test_assigning_number + json = JsonDataType.create(payload: 1.234) + assert_equal 1.234, json.payload + end - def test_assigning_boolean - json = JsonDataType.create(payload: true) - assert_equal true, json.payload + def test_assigning_boolean + json = JsonDataType.create(payload: true) + assert_equal true, json.payload + end end end -end diff --git a/activerecord/test/cases/adapters/mysql2/mysql2_adapter_test.rb b/activerecord/test/cases/adapters/mysql2/mysql2_adapter_test.rb index ac74b7f80f..69336eb906 100644 --- a/activerecord/test/cases/adapters/mysql2/mysql2_adapter_test.rb +++ b/activerecord/test/cases/adapters/mysql2/mysql2_adapter_test.rb @@ -67,7 +67,7 @@ class Mysql2AdapterTest < ActiveRecord::Mysql2TestCase private - def with_example_table(definition = "id int auto_increment primary key, number int, data varchar(255)", &block) - super(@conn, "ex", definition, &block) - end + def with_example_table(definition = "id int auto_increment primary key, number int, data varchar(255)", &block) + super(@conn, "ex", definition, &block) + end end diff --git a/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb index 8092cd1d4c..ff78bca173 100644 --- a/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb +++ b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb @@ -131,22 +131,22 @@ class Mysql2ReservedWordTest < ActiveRecord::Mysql2TestCase private # custom fixture loader, uses FixtureSet#create_fixtures and appends base_path to the current file's path - def create_test_fixtures(*fixture_names) - ActiveRecord::FixtureSet.create_fixtures(FIXTURES_ROOT + "/reserved_words", fixture_names) - end + def create_test_fixtures(*fixture_names) + ActiveRecord::FixtureSet.create_fixtures(FIXTURES_ROOT + "/reserved_words", fixture_names) + end # custom drop table, uses execute on connection to drop a table if it exists. note: escapes table_name - def drop_tables_directly(table_names, connection = @connection) - table_names.each do |name| - connection.drop_table name, if_exists: true + def drop_tables_directly(table_names, connection = @connection) + table_names.each do |name| + connection.drop_table name, if_exists: true + end end - end # custom create table, uses execute on connection to create a table, note: escapes table_name, does NOT escape columns - def create_tables_directly (tables, connection = @connection) - tables.each do |table_name, column_properties| - connection.execute("CREATE TABLE `#{table_name}` ( #{column_properties} )") + def create_tables_directly (tables, connection = @connection) + tables.each do |table_name, column_properties| + connection.execute("CREATE TABLE `#{table_name}` ( #{column_properties} )") + end end - end end diff --git a/activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb b/activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb index cdd8f06801..fa54aac6b3 100644 --- a/activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb +++ b/activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb @@ -35,25 +35,25 @@ class SchemaMigrationsTest < ActiveRecord::Mysql2TestCase private - def with_encoding_utf8mb4 - database_name = connection.current_database - database_info = connection.select_one("SELECT * FROM information_schema.schemata WHERE schema_name = '#{database_name}'") + def with_encoding_utf8mb4 + database_name = connection.current_database + database_info = connection.select_one("SELECT * FROM information_schema.schemata WHERE schema_name = '#{database_name}'") - original_charset = database_info["DEFAULT_CHARACTER_SET_NAME"] - original_collation = database_info["DEFAULT_COLLATION_NAME"] + original_charset = database_info["DEFAULT_CHARACTER_SET_NAME"] + original_collation = database_info["DEFAULT_COLLATION_NAME"] - execute("ALTER DATABASE #{database_name} DEFAULT CHARACTER SET utf8mb4") + execute("ALTER DATABASE #{database_name} DEFAULT CHARACTER SET utf8mb4") - yield - ensure - execute("ALTER DATABASE #{database_name} DEFAULT CHARACTER SET #{original_charset} COLLATE #{original_collation}") - end + yield + ensure + execute("ALTER DATABASE #{database_name} DEFAULT CHARACTER SET #{original_charset} COLLATE #{original_collation}") + end - def connection - @connection ||= ActiveRecord::Base.connection - end + def connection + @connection ||= ActiveRecord::Base.connection + end - def execute(sql) - connection.execute(sql) - end + def execute(sql) + connection.execute(sql) + end end diff --git a/activerecord/test/cases/adapters/postgresql/array_test.rb b/activerecord/test/cases/adapters/postgresql/array_test.rb index a26547b8f1..26f3e66324 100644 --- a/activerecord/test/cases/adapters/postgresql/array_test.rb +++ b/activerecord/test/cases/adapters/postgresql/array_test.rb @@ -306,17 +306,17 @@ class PostgresqlArrayTest < ActiveRecord::PostgreSQLTestCase end private - def assert_cycle field, array - # test creation - x = PgArray.create!(field => array) - x.reload - assert_equal(array, x.public_send(field)) - - # test updating - x = PgArray.create!(field => []) - x.public_send("#{field}=", array) - x.save! - x.reload - assert_equal(array, x.public_send(field)) - end + def assert_cycle field, array + # test creation + x = PgArray.create!(field => array) + x.reload + assert_equal(array, x.public_send(field)) + + # test updating + x = PgArray.create!(field => []) + x.public_send("#{field}=", array) + x.save! + x.reload + assert_equal(array, x.public_send(field)) + end end diff --git a/activerecord/test/cases/adapters/postgresql/composite_test.rb b/activerecord/test/cases/adapters/postgresql/composite_test.rb index 9377837810..1da2a9e2ac 100644 --- a/activerecord/test/cases/adapters/postgresql/composite_test.rb +++ b/activerecord/test/cases/adapters/postgresql/composite_test.rb @@ -69,12 +69,12 @@ class PostgresqlCompositeTest < ActiveRecord::PostgreSQLTestCase end private - def ensure_warning_is_issued - warning = capture(:stderr) do - PostgresqlComposite.columns_hash + def ensure_warning_is_issued + warning = capture(:stderr) do + PostgresqlComposite.columns_hash + end + assert_match(/unknown OID \d+: failed to recognize type of 'address'\. It will be treated as String\./, warning) end - assert_match(/unknown OID \d+: failed to recognize type of 'address'\. It will be treated as String\./, warning) - end end class PostgresqlCompositeWithCustomOIDTest < ActiveRecord::PostgreSQLTestCase diff --git a/activerecord/test/cases/adapters/postgresql/connection_test.rb b/activerecord/test/cases/adapters/postgresql/connection_test.rb index 78b4bfbdaa..d01f601031 100644 --- a/activerecord/test/cases/adapters/postgresql/connection_test.rb +++ b/activerecord/test/cases/adapters/postgresql/connection_test.rb @@ -247,11 +247,11 @@ module ActiveRecord protected - def with_warning_suppression - log_level = @connection.client_min_messages - @connection.client_min_messages = "error" - yield - @connection.client_min_messages = log_level - end + def with_warning_suppression + log_level = @connection.client_min_messages + @connection.client_min_messages = "error" + yield + @connection.client_min_messages = log_level + end end end diff --git a/activerecord/test/cases/adapters/postgresql/geometric_test.rb b/activerecord/test/cases/adapters/postgresql/geometric_test.rb index e35c5eb269..27a7467326 100644 --- a/activerecord/test/cases/adapters/postgresql/geometric_test.rb +++ b/activerecord/test/cases/adapters/postgresql/geometric_test.rb @@ -374,12 +374,12 @@ class PostgreSQLGeometricTypesTest < ActiveRecord::PostgreSQLTestCase private - def assert_column_exists(column_name) - assert connection.column_exists?(table_name, column_name) - end + def assert_column_exists(column_name) + assert connection.column_exists?(table_name, column_name) + end - def assert_type_correct(column_name, type) - column = connection.columns(table_name).find { |c| c.name == column_name.to_s } - assert_equal type, column.type - end + def assert_type_correct(column_name, type) + column = connection.columns(table_name).find { |c| c.name == column_name.to_s } + assert_equal type, column.type + end end diff --git a/activerecord/test/cases/adapters/postgresql/hstore_test.rb b/activerecord/test/cases/adapters/postgresql/hstore_test.rb index 6197e517d5..5da4a3ac0f 100644 --- a/activerecord/test/cases/adapters/postgresql/hstore_test.rb +++ b/activerecord/test/cases/adapters/postgresql/hstore_test.rb @@ -322,32 +322,32 @@ if ActiveRecord::Base.connection.supports_extensions? end private - def assert_array_cycle(array) - # test creation - x = Hstore.create!(payload: array) - x.reload - assert_equal(array, x.payload) - - # test updating - x = Hstore.create!(payload: []) - x.payload = array - x.save! - x.reload - assert_equal(array, x.payload) - end - - def assert_cycle(hash) - # test creation - x = Hstore.create!(tags: hash) - x.reload - assert_equal(hash, x.tags) + def assert_array_cycle(array) + # test creation + x = Hstore.create!(payload: array) + x.reload + assert_equal(array, x.payload) + + # test updating + x = Hstore.create!(payload: []) + x.payload = array + x.save! + x.reload + assert_equal(array, x.payload) + end - # test updating - x = Hstore.create!(tags: {}) - x.tags = hash - x.save! - x.reload - assert_equal(hash, x.tags) - end + def assert_cycle(hash) + # test creation + x = Hstore.create!(tags: hash) + x.reload + assert_equal(hash, x.tags) + + # test updating + x = Hstore.create!(tags: {}) + x.tags = hash + x.save! + x.reload + assert_equal(hash, x.tags) + end end end diff --git a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb index 79d99c8a58..4b8d06be4b 100644 --- a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb +++ b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb @@ -390,13 +390,13 @@ module ActiveRecord private - def with_example_table(definition = "id serial primary key, number integer, data character varying(255)", &block) - super(@connection, "ex", definition, &block) - end + def with_example_table(definition = "id serial primary key, number integer, data character varying(255)", &block) + super(@connection, "ex", definition, &block) + end - def connection_without_insert_returning - ActiveRecord::Base.postgresql_connection(ActiveRecord::Base.configurations["arunit"].merge(insert_returning: false)) - end + def connection_without_insert_returning + ActiveRecord::Base.postgresql_connection(ActiveRecord::Base.configurations["arunit"].merge(insert_returning: false)) + end end end end diff --git a/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb b/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb index 6997044d81..0ff04bfa27 100644 --- a/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb +++ b/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb @@ -105,7 +105,7 @@ class PostgreSQLReferentialIntegrityTest < ActiveRecord::PostgreSQLTestCase private - def assert_transaction_is_not_broken - assert_equal 1, @connection.select_value("SELECT 1") - end + def assert_transaction_is_not_broken + assert_equal 1, @connection.select_value("SELECT 1") + end end diff --git a/activerecord/test/cases/adapters/postgresql/rename_table_test.rb b/activerecord/test/cases/adapters/postgresql/rename_table_test.rb index bd64bae308..461353d239 100644 --- a/activerecord/test/cases/adapters/postgresql/rename_table_test.rb +++ b/activerecord/test/cases/adapters/postgresql/rename_table_test.rb @@ -24,11 +24,11 @@ class PostgresqlRenameTableTest < ActiveRecord::PostgreSQLTestCase private - def num_indices_named(name) - @connection.execute(<<-SQL).values.length + def num_indices_named(name) + @connection.execute(<<-SQL).values.length SELECT 1 FROM "pg_index" JOIN "pg_class" ON "pg_index"."indexrelid" = "pg_class"."oid" WHERE "pg_class"."relname" = '#{name}' SQL - end + end end diff --git a/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb b/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb index 72ae11966a..84af276874 100644 --- a/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb +++ b/activerecord/test/cases/adapters/postgresql/schema_authorization_test.rb @@ -110,7 +110,7 @@ class SchemaAuthorizationTest < ActiveRecord::PostgreSQLTestCase private def set_session_auth auth = nil - @connection.session_auth = auth || "default" + @connection.session_auth = auth || "default" end def bind_param(value) diff --git a/activerecord/test/cases/adapters/postgresql/transaction_test.rb b/activerecord/test/cases/adapters/postgresql/transaction_test.rb index c5164fc1f8..d992e22305 100644 --- a/activerecord/test/cases/adapters/postgresql/transaction_test.rb +++ b/activerecord/test/cases/adapters/postgresql/transaction_test.rb @@ -87,11 +87,11 @@ module ActiveRecord protected - def with_warning_suppression - log_level = @connection.client_min_messages - @connection.client_min_messages = "error" - yield - @connection.client_min_messages = log_level - end + def with_warning_suppression + log_level = @connection.client_min_messages + @connection.client_min_messages = "error" + yield + @connection.client_min_messages = log_level + end end end diff --git a/activerecord/test/cases/adapters/postgresql/uuid_test.rb b/activerecord/test/cases/adapters/postgresql/uuid_test.rb index 2052d3851d..104c71f0d3 100644 --- a/activerecord/test/cases/adapters/postgresql/uuid_test.rb +++ b/activerecord/test/cases/adapters/postgresql/uuid_test.rb @@ -266,8 +266,8 @@ class PostgresqlUUIDTestInverseOf < ActiveRecord::PostgreSQLTestCase end teardown do - drop_table "pg_uuid_comments" - drop_table "pg_uuid_posts" + drop_table "pg_uuid_comments" + drop_table "pg_uuid_posts" end if ActiveRecord::Base.connection.supports_extensions? diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb index 7edec0cb47..ca775e3704 100644 --- a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb @@ -420,22 +420,22 @@ module ActiveRecord private - def assert_logged logs - subscriber = SQLSubscriber.new - subscription = ActiveSupport::Notifications.subscribe("sql.active_record", subscriber) - yield - assert_equal logs, subscriber.logged - ensure - ActiveSupport::Notifications.unsubscribe(subscription) - end + def assert_logged logs + subscriber = SQLSubscriber.new + subscription = ActiveSupport::Notifications.subscribe("sql.active_record", subscriber) + yield + assert_equal logs, subscriber.logged + ensure + ActiveSupport::Notifications.unsubscribe(subscription) + end - def with_example_table(definition = nil, table_name = "ex", &block) - definition ||= <<-SQL + def with_example_table(definition = nil, table_name = "ex", &block) + definition ||= <<-SQL id integer PRIMARY KEY AUTOINCREMENT, number integer SQL - super(@conn, table_name, definition, &block) - end + super(@conn, table_name, definition, &block) + end end end end diff --git a/activerecord/test/cases/associations/eager_singularization_test.rb b/activerecord/test/cases/associations/eager_singularization_test.rb index df238b4859..373b17483c 100644 --- a/activerecord/test/cases/associations/eager_singularization_test.rb +++ b/activerecord/test/cases/associations/eager_singularization_test.rb @@ -2,147 +2,147 @@ require "cases/helper" if ActiveRecord::Base.connection.supports_migrations? -class EagerSingularizationTest < ActiveRecord::TestCase - class Virus < ActiveRecord::Base - belongs_to :octopus - end - - class Octopus < ActiveRecord::Base - has_one :virus - end - - class Pass < ActiveRecord::Base - belongs_to :bus - end - - class Bus < ActiveRecord::Base - has_many :passes - end - - class Mess < ActiveRecord::Base - has_and_belongs_to_many :crises - end - - class Crisis < ActiveRecord::Base - has_and_belongs_to_many :messes - has_many :analyses, dependent: :destroy - has_many :successes, through: :analyses - has_many :dresses, dependent: :destroy - has_many :compresses, through: :dresses - end - - class Analysis < ActiveRecord::Base - belongs_to :crisis - belongs_to :success - end - - class Success < ActiveRecord::Base - has_many :analyses, dependent: :destroy - has_many :crises, through: :analyses - end - - class Dress < ActiveRecord::Base - belongs_to :crisis - has_many :compresses - end + class EagerSingularizationTest < ActiveRecord::TestCase + class Virus < ActiveRecord::Base + belongs_to :octopus + end + + class Octopus < ActiveRecord::Base + has_one :virus + end + + class Pass < ActiveRecord::Base + belongs_to :bus + end - class Compress < ActiveRecord::Base - belongs_to :dress - end + class Bus < ActiveRecord::Base + has_many :passes + end - def setup - connection.create_table :viri do |t| - t.column :octopus_id, :integer - t.column :species, :string - end - connection.create_table :octopi do |t| - t.column :species, :string - end - connection.create_table :passes do |t| - t.column :bus_id, :integer - t.column :rides, :integer + class Mess < ActiveRecord::Base + has_and_belongs_to_many :crises end - connection.create_table :buses do |t| - t.column :name, :string - end - connection.create_table :crises_messes, id: false do |t| - t.column :crisis_id, :integer - t.column :mess_id, :integer - end - connection.create_table :messes do |t| - t.column :name, :string - end - connection.create_table :crises do |t| - t.column :name, :string - end - connection.create_table :successes do |t| - t.column :name, :string - end - connection.create_table :analyses do |t| - t.column :crisis_id, :integer - t.column :success_id, :integer - end - connection.create_table :dresses do |t| - t.column :crisis_id, :integer + + class Crisis < ActiveRecord::Base + has_and_belongs_to_many :messes + has_many :analyses, dependent: :destroy + has_many :successes, through: :analyses + has_many :dresses, dependent: :destroy + has_many :compresses, through: :dresses end - connection.create_table :compresses do |t| - t.column :dress_id, :integer + + class Analysis < ActiveRecord::Base + belongs_to :crisis + belongs_to :success end - end - teardown do - connection.drop_table :viri - connection.drop_table :octopi - connection.drop_table :passes - connection.drop_table :buses - connection.drop_table :crises_messes - connection.drop_table :messes - connection.drop_table :crises - connection.drop_table :successes - connection.drop_table :analyses - connection.drop_table :dresses - connection.drop_table :compresses - end + class Success < ActiveRecord::Base + has_many :analyses, dependent: :destroy + has_many :crises, through: :analyses + end - def connection - ActiveRecord::Base.connection - end + class Dress < ActiveRecord::Base + belongs_to :crisis + has_many :compresses + end - def test_eager_no_extra_singularization_belongs_to - assert_nothing_raised do - Virus.all.merge!(includes: :octopus).to_a + class Compress < ActiveRecord::Base + belongs_to :dress end - end - def test_eager_no_extra_singularization_has_one - assert_nothing_raised do - Octopus.all.merge!(includes: :virus).to_a + def setup + connection.create_table :viri do |t| + t.column :octopus_id, :integer + t.column :species, :string + end + connection.create_table :octopi do |t| + t.column :species, :string + end + connection.create_table :passes do |t| + t.column :bus_id, :integer + t.column :rides, :integer + end + connection.create_table :buses do |t| + t.column :name, :string + end + connection.create_table :crises_messes, id: false do |t| + t.column :crisis_id, :integer + t.column :mess_id, :integer + end + connection.create_table :messes do |t| + t.column :name, :string + end + connection.create_table :crises do |t| + t.column :name, :string + end + connection.create_table :successes do |t| + t.column :name, :string + end + connection.create_table :analyses do |t| + t.column :crisis_id, :integer + t.column :success_id, :integer + end + connection.create_table :dresses do |t| + t.column :crisis_id, :integer + end + connection.create_table :compresses do |t| + t.column :dress_id, :integer + end end - end - def test_eager_no_extra_singularization_has_many - assert_nothing_raised do - Bus.all.merge!(includes: :passes).to_a + teardown do + connection.drop_table :viri + connection.drop_table :octopi + connection.drop_table :passes + connection.drop_table :buses + connection.drop_table :crises_messes + connection.drop_table :messes + connection.drop_table :crises + connection.drop_table :successes + connection.drop_table :analyses + connection.drop_table :dresses + connection.drop_table :compresses end - end - def test_eager_no_extra_singularization_has_and_belongs_to_many - assert_nothing_raised do - Crisis.all.merge!(includes: :messes).to_a - Mess.all.merge!(includes: :crises).to_a + def connection + ActiveRecord::Base.connection end - end - def test_eager_no_extra_singularization_has_many_through_belongs_to - assert_nothing_raised do - Crisis.all.merge!(includes: :successes).to_a + def test_eager_no_extra_singularization_belongs_to + assert_nothing_raised do + Virus.all.merge!(includes: :octopus).to_a + end end - end - def test_eager_no_extra_singularization_has_many_through_has_many - assert_nothing_raised do - Crisis.all.merge!(includes: :compresses).to_a + def test_eager_no_extra_singularization_has_one + assert_nothing_raised do + Octopus.all.merge!(includes: :virus).to_a + end + end + + def test_eager_no_extra_singularization_has_many + assert_nothing_raised do + Bus.all.merge!(includes: :passes).to_a + end + end + + def test_eager_no_extra_singularization_has_and_belongs_to_many + assert_nothing_raised do + Crisis.all.merge!(includes: :messes).to_a + Mess.all.merge!(includes: :crises).to_a + end + end + + def test_eager_no_extra_singularization_has_many_through_belongs_to + assert_nothing_raised do + Crisis.all.merge!(includes: :successes).to_a + end + end + + def test_eager_no_extra_singularization_has_many_through_has_many + assert_nothing_raised do + Crisis.all.merge!(includes: :compresses).to_a + end end end end -end diff --git a/activerecord/test/cases/associations/required_test.rb b/activerecord/test/cases/associations/required_test.rb index 7d7da44629..f8b686721e 100644 --- a/activerecord/test/cases/associations/required_test.rb +++ b/activerecord/test/cases/associations/required_test.rb @@ -92,11 +92,11 @@ class RequiredAssociationsTest < ActiveRecord::TestCase private - def subclass_of(klass, &block) - subclass = Class.new(klass, &block) - def subclass.name - superclass.name + def subclass_of(klass, &block) + subclass = Class.new(klass, &block) + def subclass.name + superclass.name + end + subclass end - subclass - end end diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb index 8aad272bfd..7a2041937d 100644 --- a/activerecord/test/cases/attribute_methods_test.rb +++ b/activerecord/test/cases/attribute_methods_test.rb @@ -975,38 +975,38 @@ class AttributeMethodsTest < ActiveRecord::TestCase private - def new_topic_like_ar_class(&block) - klass = Class.new(ActiveRecord::Base) do - self.table_name = "topics" - class_eval(&block) - end + def new_topic_like_ar_class(&block) + klass = Class.new(ActiveRecord::Base) do + self.table_name = "topics" + class_eval(&block) + end - assert_empty klass.generated_attribute_methods.instance_methods(false) - klass - end + assert_empty klass.generated_attribute_methods.instance_methods(false) + klass + end - def with_time_zone_aware_types(*types) - old_types = ActiveRecord::Base.time_zone_aware_types - ActiveRecord::Base.time_zone_aware_types = types - yield - ensure - ActiveRecord::Base.time_zone_aware_types = old_types - end + def with_time_zone_aware_types(*types) + old_types = ActiveRecord::Base.time_zone_aware_types + ActiveRecord::Base.time_zone_aware_types = types + yield + ensure + ActiveRecord::Base.time_zone_aware_types = old_types + end - def cached_columns - Topic.columns.map(&:name) - end + def cached_columns + Topic.columns.map(&:name) + end - def time_related_columns_on_topic - Topic.columns.select { |c| [:time, :date, :datetime, :timestamp].include?(c.type) } - end + def time_related_columns_on_topic + Topic.columns.select { |c| [:time, :date, :datetime, :timestamp].include?(c.type) } + end - def privatize(method_signature) - @target.class_eval(<<-private_method, __FILE__, __LINE__ + 1) + def privatize(method_signature) + @target.class_eval(<<-private_method, __FILE__, __LINE__ + 1) private def #{method_signature} "I'm private" end private_method - end + end end diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index d09e4cae3b..ae5127cc56 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -79,18 +79,18 @@ class TestAutosaveAssociationsInGeneral < ActiveRecord::TestCase private - def assert_no_difference_when_adding_callbacks_twice_for(model, association_name) - reflection = model.reflect_on_association(association_name) - assert_no_difference "callbacks_for_model(#{model.name}).length" do - model.send(:add_autosave_association_callbacks, reflection) + def assert_no_difference_when_adding_callbacks_twice_for(model, association_name) + reflection = model.reflect_on_association(association_name) + assert_no_difference "callbacks_for_model(#{model.name}).length" do + model.send(:add_autosave_association_callbacks, reflection) + end end - end - def callbacks_for_model(model) - model.instance_variables.grep(/_callbacks$/).flat_map do |ivar| - model.instance_variable_get(ivar) + def callbacks_for_model(model) + model.instance_variables.grep(/_callbacks$/).flat_map do |ivar| + model.instance_variable_get(ivar) + end end - end end class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase diff --git a/activerecord/test/cases/column_alias_test.rb b/activerecord/test/cases/column_alias_test.rb index 85d65b074c..ae64c99f33 100644 --- a/activerecord/test/cases/column_alias_test.rb +++ b/activerecord/test/cases/column_alias_test.rb @@ -5,7 +5,7 @@ class TestColumnAlias < ActiveRecord::TestCase fixtures :topics QUERY = if "Oracle" == ActiveRecord::Base.connection.adapter_name - "SELECT id AS pk FROM topics WHERE ROWNUM < 2" + "SELECT id AS pk FROM topics WHERE ROWNUM < 2" else "SELECT id AS pk FROM topics" end diff --git a/activerecord/test/cases/column_definition_test.rb b/activerecord/test/cases/column_definition_test.rb index 9b38eda004..c5fe103efd 100644 --- a/activerecord/test/cases/column_definition_test.rb +++ b/activerecord/test/cases/column_definition_test.rb @@ -18,7 +18,7 @@ module ActiveRecord column_def = ColumnDefinition.new( column.name, "string", column.limit, column.precision, column.scale, column.default, column.null) - assert_equal "title varchar(20)", @viz.accept(column_def) + assert_equal "title varchar(20)", @viz.accept(column_def) end def test_should_include_default_clause_when_default_is_present @@ -26,7 +26,7 @@ module ActiveRecord column_def = ColumnDefinition.new( column.name, "string", column.limit, column.precision, column.scale, column.default, column.null) - assert_equal %Q{title varchar(20) DEFAULT 'Hello'}, @viz.accept(column_def) + assert_equal %Q{title varchar(20) DEFAULT 'Hello'}, @viz.accept(column_def) end def test_should_specify_not_null_if_null_option_is_false @@ -35,7 +35,7 @@ module ActiveRecord column_def = ColumnDefinition.new( column.name, "string", column.limit, column.precision, column.scale, column.default, column.null) - assert_equal %Q{title varchar(20) DEFAULT 'Hello' NOT NULL}, @viz.accept(column_def) + assert_equal %Q{title varchar(20) DEFAULT 'Hello' NOT NULL}, @viz.accept(column_def) end if current_adapter?(:Mysql2Adapter) diff --git a/activerecord/test/cases/comment_test.rb b/activerecord/test/cases/comment_test.rb index 87cc30f0d7..262ad319be 100644 --- a/activerecord/test/cases/comment_test.rb +++ b/activerecord/test/cases/comment_test.rb @@ -3,137 +3,137 @@ require "support/schema_dumping_helper" if ActiveRecord::Base.connection.supports_comments? -class CommentTest < ActiveRecord::TestCase - include SchemaDumpingHelper + class CommentTest < ActiveRecord::TestCase + include SchemaDumpingHelper - class Commented < ActiveRecord::Base - self.table_name = "commenteds" - end - - class BlankComment < ActiveRecord::Base - end - - setup do - @connection = ActiveRecord::Base.connection - - @connection.create_table("commenteds", comment: "A table with comment", force: true) do |t| - t.string "name", comment: "Comment should help clarify the column purpose" - t.boolean "obvious", comment: "Question is: should you comment obviously named objects?" - t.string "content" - t.index "name", comment: %Q["Very important" index that powers all the performance.\nAnd it's fun!] + class Commented < ActiveRecord::Base + self.table_name = "commenteds" end - @connection.create_table("blank_comments", comment: " ", force: true) do |t| - t.string :space_comment, comment: " " - t.string :empty_comment, comment: "" - t.string :nil_comment, comment: nil - t.string :absent_comment - t.index :space_comment, comment: " " - t.index :empty_comment, comment: "" - t.index :nil_comment, comment: nil - t.index :absent_comment + class BlankComment < ActiveRecord::Base end - Commented.reset_column_information - BlankComment.reset_column_information - end - - teardown do - @connection.drop_table "commenteds", if_exists: true - @connection.drop_table "blank_comments", if_exists: true - end + setup do + @connection = ActiveRecord::Base.connection + + @connection.create_table("commenteds", comment: "A table with comment", force: true) do |t| + t.string "name", comment: "Comment should help clarify the column purpose" + t.boolean "obvious", comment: "Question is: should you comment obviously named objects?" + t.string "content" + t.index "name", comment: %Q["Very important" index that powers all the performance.\nAnd it's fun!] + end + + @connection.create_table("blank_comments", comment: " ", force: true) do |t| + t.string :space_comment, comment: " " + t.string :empty_comment, comment: "" + t.string :nil_comment, comment: nil + t.string :absent_comment + t.index :space_comment, comment: " " + t.index :empty_comment, comment: "" + t.index :nil_comment, comment: nil + t.index :absent_comment + end + + Commented.reset_column_information + BlankComment.reset_column_information + end - def test_column_created_in_block - column = Commented.columns_hash["name"] - assert_equal :string, column.type - assert_equal "Comment should help clarify the column purpose", column.comment - end + teardown do + @connection.drop_table "commenteds", if_exists: true + @connection.drop_table "blank_comments", if_exists: true + end - def test_blank_columns_created_in_block - %w[ space_comment empty_comment nil_comment absent_comment ].each do |field| - column = BlankComment.columns_hash[field] + def test_column_created_in_block + column = Commented.columns_hash["name"] assert_equal :string, column.type - assert_nil column.comment + assert_equal "Comment should help clarify the column purpose", column.comment end - end - def test_blank_indexes_created_in_block - @connection.indexes("blank_comments").each do |index| - assert_nil index.comment + def test_blank_columns_created_in_block + %w[ space_comment empty_comment nil_comment absent_comment ].each do |field| + column = BlankComment.columns_hash[field] + assert_equal :string, column.type + assert_nil column.comment + end end - end - def test_add_column_with_comment_later - @connection.add_column :commenteds, :rating, :integer, comment: "I am running out of imagination" - Commented.reset_column_information - column = Commented.columns_hash["rating"] + def test_blank_indexes_created_in_block + @connection.indexes("blank_comments").each do |index| + assert_nil index.comment + end + end - assert_equal :integer, column.type - assert_equal "I am running out of imagination", column.comment - end + def test_add_column_with_comment_later + @connection.add_column :commenteds, :rating, :integer, comment: "I am running out of imagination" + Commented.reset_column_information + column = Commented.columns_hash["rating"] - def test_add_index_with_comment_later - @connection.add_index :commenteds, :obvious, name: "idx_obvious", comment: "We need to see obvious comments" - index = @connection.indexes("commenteds").find { |idef| idef.name == "idx_obvious" } - assert_equal "We need to see obvious comments", index.comment - end + assert_equal :integer, column.type + assert_equal "I am running out of imagination", column.comment + end - def test_add_comment_to_column - @connection.change_column :commenteds, :content, :string, comment: "Whoa, content describes itself!" + def test_add_index_with_comment_later + @connection.add_index :commenteds, :obvious, name: "idx_obvious", comment: "We need to see obvious comments" + index = @connection.indexes("commenteds").find { |idef| idef.name == "idx_obvious" } + assert_equal "We need to see obvious comments", index.comment + end - Commented.reset_column_information - column = Commented.columns_hash["content"] + def test_add_comment_to_column + @connection.change_column :commenteds, :content, :string, comment: "Whoa, content describes itself!" - assert_equal :string, column.type - assert_equal "Whoa, content describes itself!", column.comment - end + Commented.reset_column_information + column = Commented.columns_hash["content"] - def test_remove_comment_from_column - @connection.change_column :commenteds, :obvious, :string, comment: nil + assert_equal :string, column.type + assert_equal "Whoa, content describes itself!", column.comment + end - Commented.reset_column_information - column = Commented.columns_hash["obvious"] + def test_remove_comment_from_column + @connection.change_column :commenteds, :obvious, :string, comment: nil - assert_equal :string, column.type - assert_nil column.comment - end + Commented.reset_column_information + column = Commented.columns_hash["obvious"] - def test_schema_dump_with_comments - # Do all the stuff from other tests - @connection.add_column :commenteds, :rating, :integer, comment: "I am running out of imagination" - @connection.change_column :commenteds, :content, :string, comment: "Whoa, content describes itself!" - @connection.change_column :commenteds, :obvious, :string, comment: nil - @connection.add_index :commenteds, :obvious, name: "idx_obvious", comment: "We need to see obvious comments" - - # And check that these changes are reflected in dump - output = dump_table_schema "commenteds" - assert_match %r[create_table "commenteds",.+\s+comment: "A table with comment"], output - assert_match %r[t\.string\s+"name",\s+comment: "Comment should help clarify the column purpose"], output - assert_match %r[t\.string\s+"obvious"\n], output - assert_match %r[t\.string\s+"content",\s+comment: "Whoa, content describes itself!"], output - assert_match %r[t\.integer\s+"rating",\s+comment: "I am running out of imagination"], output - assert_match %r[t\.index\s+.+\s+comment: "\\\"Very important\\\" index that powers all the performance.\\nAnd it's fun!"], output - assert_match %r[t\.index\s+.+\s+name: "idx_obvious",.+\s+comment: "We need to see obvious comments"], output - end + assert_equal :string, column.type + assert_nil column.comment + end - def test_schema_dump_omits_blank_comments - output = dump_table_schema "blank_comments" + def test_schema_dump_with_comments + # Do all the stuff from other tests + @connection.add_column :commenteds, :rating, :integer, comment: "I am running out of imagination" + @connection.change_column :commenteds, :content, :string, comment: "Whoa, content describes itself!" + @connection.change_column :commenteds, :obvious, :string, comment: nil + @connection.add_index :commenteds, :obvious, name: "idx_obvious", comment: "We need to see obvious comments" + + # And check that these changes are reflected in dump + output = dump_table_schema "commenteds" + assert_match %r[create_table "commenteds",.+\s+comment: "A table with comment"], output + assert_match %r[t\.string\s+"name",\s+comment: "Comment should help clarify the column purpose"], output + assert_match %r[t\.string\s+"obvious"\n], output + assert_match %r[t\.string\s+"content",\s+comment: "Whoa, content describes itself!"], output + assert_match %r[t\.integer\s+"rating",\s+comment: "I am running out of imagination"], output + assert_match %r[t\.index\s+.+\s+comment: "\\\"Very important\\\" index that powers all the performance.\\nAnd it's fun!"], output + assert_match %r[t\.index\s+.+\s+name: "idx_obvious",.+\s+comment: "We need to see obvious comments"], output + end - assert_match %r[create_table "blank_comments"], output - assert_no_match %r[create_table "blank_comments",.+comment:], output + def test_schema_dump_omits_blank_comments + output = dump_table_schema "blank_comments" - assert_match %r[t\.string\s+"space_comment"\n], output - assert_no_match %r[t\.string\s+"space_comment", comment:\n], output + assert_match %r[create_table "blank_comments"], output + assert_no_match %r[create_table "blank_comments",.+comment:], output - assert_match %r[t\.string\s+"empty_comment"\n], output - assert_no_match %r[t\.string\s+"empty_comment", comment:\n], output + assert_match %r[t\.string\s+"space_comment"\n], output + assert_no_match %r[t\.string\s+"space_comment", comment:\n], output - assert_match %r[t\.string\s+"nil_comment"\n], output - assert_no_match %r[t\.string\s+"nil_comment", comment:\n], output + assert_match %r[t\.string\s+"empty_comment"\n], output + assert_no_match %r[t\.string\s+"empty_comment", comment:\n], output - assert_match %r[t\.string\s+"absent_comment"\n], output - assert_no_match %r[t\.string\s+"absent_comment", comment:\n], output + assert_match %r[t\.string\s+"nil_comment"\n], output + assert_no_match %r[t\.string\s+"nil_comment", comment:\n], output + + assert_match %r[t\.string\s+"absent_comment"\n], output + assert_no_match %r[t\.string\s+"absent_comment", comment:\n], output + end end -end end diff --git a/activerecord/test/cases/connection_adapters/mysql_type_lookup_test.rb b/activerecord/test/cases/connection_adapters/mysql_type_lookup_test.rb index 209802d34f..3657b8340d 100644 --- a/activerecord/test/cases/connection_adapters/mysql_type_lookup_test.rb +++ b/activerecord/test/cases/connection_adapters/mysql_type_lookup_test.rb @@ -1,69 +1,69 @@ require "cases/helper" if current_adapter?(:Mysql2Adapter) -module ActiveRecord - module ConnectionAdapters - class MysqlTypeLookupTest < ActiveRecord::TestCase - setup do - @connection = ActiveRecord::Base.connection - end + module ActiveRecord + module ConnectionAdapters + class MysqlTypeLookupTest < ActiveRecord::TestCase + setup do + @connection = ActiveRecord::Base.connection + end - def test_boolean_types - emulate_booleans(true) do - assert_lookup_type :boolean, "tinyint(1)" - assert_lookup_type :boolean, "TINYINT(1)" + def test_boolean_types + emulate_booleans(true) do + assert_lookup_type :boolean, "tinyint(1)" + assert_lookup_type :boolean, "TINYINT(1)" + end end - end - def test_string_types - assert_lookup_type :string, "enum('one', 'two', 'three')" - assert_lookup_type :string, "ENUM('one', 'two', 'three')" - assert_lookup_type :string, "set('one', 'two', 'three')" - assert_lookup_type :string, "SET('one', 'two', 'three')" - end + def test_string_types + assert_lookup_type :string, "enum('one', 'two', 'three')" + assert_lookup_type :string, "ENUM('one', 'two', 'three')" + assert_lookup_type :string, "set('one', 'two', 'three')" + assert_lookup_type :string, "SET('one', 'two', 'three')" + end - def test_set_type_with_value_matching_other_type - assert_lookup_type :string, "SET('unicode', '8bit', 'none', 'time')" - end + def test_set_type_with_value_matching_other_type + assert_lookup_type :string, "SET('unicode', '8bit', 'none', 'time')" + end - def test_enum_type_with_value_matching_other_type - assert_lookup_type :string, "ENUM('unicode', '8bit', 'none')" - end + def test_enum_type_with_value_matching_other_type + assert_lookup_type :string, "ENUM('unicode', '8bit', 'none')" + end - def test_binary_types - assert_lookup_type :binary, "bit" - assert_lookup_type :binary, "BIT" - end + def test_binary_types + assert_lookup_type :binary, "bit" + assert_lookup_type :binary, "BIT" + end - def test_integer_types - emulate_booleans(false) do - assert_lookup_type :integer, "tinyint(1)" - assert_lookup_type :integer, "TINYINT(1)" - assert_lookup_type :integer, "year" - assert_lookup_type :integer, "YEAR" + def test_integer_types + emulate_booleans(false) do + assert_lookup_type :integer, "tinyint(1)" + assert_lookup_type :integer, "TINYINT(1)" + assert_lookup_type :integer, "year" + assert_lookup_type :integer, "YEAR" + end end - end - private + private - def assert_lookup_type(type, lookup) - cast_type = @connection.type_map.lookup(lookup) - assert_equal type, cast_type.type - end + def assert_lookup_type(type, lookup) + cast_type = @connection.type_map.lookup(lookup) + assert_equal type, cast_type.type + end - def emulate_booleans(value) - old_emulate_booleans = @connection.emulate_booleans - change_emulate_booleans(value) - yield - ensure - change_emulate_booleans(old_emulate_booleans) - end + def emulate_booleans(value) + old_emulate_booleans = @connection.emulate_booleans + change_emulate_booleans(value) + yield + ensure + change_emulate_booleans(old_emulate_booleans) + end - def change_emulate_booleans(value) - @connection.emulate_booleans = value - @connection.clear_cache! + def change_emulate_booleans(value) + @connection.emulate_booleans = value + @connection.clear_cache! + end end end end end -end diff --git a/activerecord/test/cases/connection_adapters/type_lookup_test.rb b/activerecord/test/cases/connection_adapters/type_lookup_test.rb index c01464ed68..e2e5445a4e 100644 --- a/activerecord/test/cases/connection_adapters/type_lookup_test.rb +++ b/activerecord/test/cases/connection_adapters/type_lookup_test.rb @@ -1,110 +1,110 @@ require "cases/helper" unless current_adapter?(:PostgreSQLAdapter) # PostgreSQL does not use type strings for lookup -module ActiveRecord - module ConnectionAdapters - class TypeLookupTest < ActiveRecord::TestCase - setup do - @connection = ActiveRecord::Base.connection - end + module ActiveRecord + module ConnectionAdapters + class TypeLookupTest < ActiveRecord::TestCase + setup do + @connection = ActiveRecord::Base.connection + end - def test_boolean_types - assert_lookup_type :boolean, "boolean" - assert_lookup_type :boolean, "BOOLEAN" - end + def test_boolean_types + assert_lookup_type :boolean, "boolean" + assert_lookup_type :boolean, "BOOLEAN" + end - def test_string_types - assert_lookup_type :string, "char" - assert_lookup_type :string, "varchar" - assert_lookup_type :string, "VARCHAR" - assert_lookup_type :string, "varchar(255)" - assert_lookup_type :string, "character varying" - end + def test_string_types + assert_lookup_type :string, "char" + assert_lookup_type :string, "varchar" + assert_lookup_type :string, "VARCHAR" + assert_lookup_type :string, "varchar(255)" + assert_lookup_type :string, "character varying" + end - def test_binary_types - assert_lookup_type :binary, "binary" - assert_lookup_type :binary, "BINARY" - assert_lookup_type :binary, "blob" - assert_lookup_type :binary, "BLOB" - end + def test_binary_types + assert_lookup_type :binary, "binary" + assert_lookup_type :binary, "BINARY" + assert_lookup_type :binary, "blob" + assert_lookup_type :binary, "BLOB" + end - def test_text_types - assert_lookup_type :text, "text" - assert_lookup_type :text, "TEXT" - assert_lookup_type :text, "clob" - assert_lookup_type :text, "CLOB" - end + def test_text_types + assert_lookup_type :text, "text" + assert_lookup_type :text, "TEXT" + assert_lookup_type :text, "clob" + assert_lookup_type :text, "CLOB" + end - def test_date_types - assert_lookup_type :date, "date" - assert_lookup_type :date, "DATE" - end + def test_date_types + assert_lookup_type :date, "date" + assert_lookup_type :date, "DATE" + end - def test_time_types - assert_lookup_type :time, "time" - assert_lookup_type :time, "TIME" - end + def test_time_types + assert_lookup_type :time, "time" + assert_lookup_type :time, "TIME" + end - def test_datetime_types - assert_lookup_type :datetime, "datetime" - assert_lookup_type :datetime, "DATETIME" - assert_lookup_type :datetime, "timestamp" - assert_lookup_type :datetime, "TIMESTAMP" - end + def test_datetime_types + assert_lookup_type :datetime, "datetime" + assert_lookup_type :datetime, "DATETIME" + assert_lookup_type :datetime, "timestamp" + assert_lookup_type :datetime, "TIMESTAMP" + end - def test_decimal_types - assert_lookup_type :decimal, "decimal" - assert_lookup_type :decimal, "decimal(2,8)" - assert_lookup_type :decimal, "DECIMAL" - assert_lookup_type :decimal, "numeric" - assert_lookup_type :decimal, "numeric(2,8)" - assert_lookup_type :decimal, "NUMERIC" - assert_lookup_type :decimal, "number" - assert_lookup_type :decimal, "number(2,8)" - assert_lookup_type :decimal, "NUMBER" - end + def test_decimal_types + assert_lookup_type :decimal, "decimal" + assert_lookup_type :decimal, "decimal(2,8)" + assert_lookup_type :decimal, "DECIMAL" + assert_lookup_type :decimal, "numeric" + assert_lookup_type :decimal, "numeric(2,8)" + assert_lookup_type :decimal, "NUMERIC" + assert_lookup_type :decimal, "number" + assert_lookup_type :decimal, "number(2,8)" + assert_lookup_type :decimal, "NUMBER" + end - def test_float_types - assert_lookup_type :float, "float" - assert_lookup_type :float, "FLOAT" - assert_lookup_type :float, "double" - assert_lookup_type :float, "DOUBLE" - end + def test_float_types + assert_lookup_type :float, "float" + assert_lookup_type :float, "FLOAT" + assert_lookup_type :float, "double" + assert_lookup_type :float, "DOUBLE" + end - def test_integer_types - assert_lookup_type :integer, "integer" - assert_lookup_type :integer, "INTEGER" - assert_lookup_type :integer, "tinyint" - assert_lookup_type :integer, "smallint" - assert_lookup_type :integer, "bigint" - end + def test_integer_types + assert_lookup_type :integer, "integer" + assert_lookup_type :integer, "INTEGER" + assert_lookup_type :integer, "tinyint" + assert_lookup_type :integer, "smallint" + assert_lookup_type :integer, "bigint" + end - def test_bigint_limit - cast_type = @connection.type_map.lookup("bigint") - if current_adapter?(:OracleAdapter) - assert_equal 19, cast_type.limit - else - assert_equal 8, cast_type.limit + def test_bigint_limit + cast_type = @connection.type_map.lookup("bigint") + if current_adapter?(:OracleAdapter) + assert_equal 19, cast_type.limit + else + assert_equal 8, cast_type.limit + end end - end - def test_decimal_without_scale - types = %w{decimal(2) decimal(2,0) numeric(2) numeric(2,0) number(2) number(2,0)} - types.each do |type| - cast_type = @connection.type_map.lookup(type) + def test_decimal_without_scale + types = %w{decimal(2) decimal(2,0) numeric(2) numeric(2,0) number(2) number(2,0)} + types.each do |type| + cast_type = @connection.type_map.lookup(type) - assert_equal :decimal, cast_type.type - assert_equal 2, cast_type.cast(2.1) + assert_equal :decimal, cast_type.type + assert_equal 2, cast_type.cast(2.1) + end end - end - private + private - def assert_lookup_type(type, lookup) - cast_type = @connection.type_map.lookup(lookup) - assert_equal type, cast_type.type + def assert_lookup_type(type, lookup) + cast_type = @connection.type_map.lookup(lookup) + assert_equal type, cast_type.type + end end end end end -end diff --git a/activerecord/test/cases/connection_pool_test.rb b/activerecord/test/cases/connection_pool_test.rb index 8324fecd3a..d7ff9d6880 100644 --- a/activerecord/test/cases/connection_pool_test.rb +++ b/activerecord/test/cases/connection_pool_test.rb @@ -527,13 +527,13 @@ module ActiveRecord end private - def with_single_connection_pool - one_conn_spec = ActiveRecord::Base.connection_pool.spec.dup - one_conn_spec.config[:pool] = 1 # this is safe to do, because .dupped ConnectionSpecification also auto-dups its config - yield(pool = ConnectionPool.new(one_conn_spec)) - ensure - pool.disconnect! if pool - end + def with_single_connection_pool + one_conn_spec = ActiveRecord::Base.connection_pool.spec.dup + one_conn_spec.config[:pool] = 1 # this is safe to do, because .dupped ConnectionSpecification also auto-dups its config + yield(pool = ConnectionPool.new(one_conn_spec)) + ensure + pool.disconnect! if pool + end end end end diff --git a/activerecord/test/cases/database_statements_test.rb b/activerecord/test/cases/database_statements_test.rb index 3169408ac0..ac9912d4d1 100644 --- a/activerecord/test/cases/database_statements_test.rb +++ b/activerecord/test/cases/database_statements_test.rb @@ -21,14 +21,14 @@ class DatabaseStatementsTest < ActiveRecord::TestCase private - def return_the_inserted_id(method:) - # Oracle adapter uses prefetched primary key values from sequence and passes them to connection adapter insert method - if current_adapter?(:OracleAdapter) - sequence_name = "accounts_seq" - id_value = @connection.next_sequence_value(sequence_name) - @connection.send(method, "INSERT INTO accounts (id, firm_id,credit_limit) VALUES (accounts_seq.nextval,42,5000)", nil, :id, id_value, sequence_name) - else - @connection.send(method, "INSERT INTO accounts (firm_id,credit_limit) VALUES (42,5000)") + def return_the_inserted_id(method:) + # Oracle adapter uses prefetched primary key values from sequence and passes them to connection adapter insert method + if current_adapter?(:OracleAdapter) + sequence_name = "accounts_seq" + id_value = @connection.next_sequence_value(sequence_name) + @connection.send(method, "INSERT INTO accounts (id, firm_id,credit_limit) VALUES (accounts_seq.nextval,42,5000)", nil, :id, id_value, sequence_name) + else + @connection.send(method, "INSERT INTO accounts (firm_id,credit_limit) VALUES (42,5000)") + end end - end end diff --git a/activerecord/test/cases/date_time_precision_test.rb b/activerecord/test/cases/date_time_precision_test.rb index 40c68f9dc8..7876542379 100644 --- a/activerecord/test/cases/date_time_precision_test.rb +++ b/activerecord/test/cases/date_time_precision_test.rb @@ -2,87 +2,87 @@ require "cases/helper" require "support/schema_dumping_helper" if subsecond_precision_supported? -class DateTimePrecisionTest < ActiveRecord::TestCase - include SchemaDumpingHelper - self.use_transactional_tests = false + class DateTimePrecisionTest < ActiveRecord::TestCase + include SchemaDumpingHelper + self.use_transactional_tests = false - class Foo < ActiveRecord::Base; end + class Foo < ActiveRecord::Base; end - setup do - @connection = ActiveRecord::Base.connection - Foo.reset_column_information - end - - teardown do - @connection.drop_table :foos, if_exists: true - end + setup do + @connection = ActiveRecord::Base.connection + Foo.reset_column_information + end - def test_datetime_data_type_with_precision - @connection.create_table(:foos, force: true) - @connection.add_column :foos, :created_at, :datetime, precision: 0 - @connection.add_column :foos, :updated_at, :datetime, precision: 5 - assert_equal 0, Foo.columns_hash["created_at"].precision - assert_equal 5, Foo.columns_hash["updated_at"].precision - end + teardown do + @connection.drop_table :foos, if_exists: true + end - def test_timestamps_helper_with_custom_precision - @connection.create_table(:foos, force: true) do |t| - t.timestamps precision: 4 + def test_datetime_data_type_with_precision + @connection.create_table(:foos, force: true) + @connection.add_column :foos, :created_at, :datetime, precision: 0 + @connection.add_column :foos, :updated_at, :datetime, precision: 5 + assert_equal 0, Foo.columns_hash["created_at"].precision + assert_equal 5, Foo.columns_hash["updated_at"].precision end - assert_equal 4, Foo.columns_hash["created_at"].precision - assert_equal 4, Foo.columns_hash["updated_at"].precision - end - def test_passing_precision_to_datetime_does_not_set_limit - @connection.create_table(:foos, force: true) do |t| - t.timestamps precision: 4 + def test_timestamps_helper_with_custom_precision + @connection.create_table(:foos, force: true) do |t| + t.timestamps precision: 4 + end + assert_equal 4, Foo.columns_hash["created_at"].precision + assert_equal 4, Foo.columns_hash["updated_at"].precision end - assert_nil Foo.columns_hash["created_at"].limit - assert_nil Foo.columns_hash["updated_at"].limit - end - def test_invalid_datetime_precision_raises_error - assert_raises ActiveRecord::ActiveRecordError do + def test_passing_precision_to_datetime_does_not_set_limit @connection.create_table(:foos, force: true) do |t| - t.timestamps precision: 7 + t.timestamps precision: 4 end + assert_nil Foo.columns_hash["created_at"].limit + assert_nil Foo.columns_hash["updated_at"].limit end - end - def test_formatting_datetime_according_to_precision - @connection.create_table(:foos, force: true) do |t| - t.datetime :created_at, precision: 0 - t.datetime :updated_at, precision: 4 + def test_invalid_datetime_precision_raises_error + assert_raises ActiveRecord::ActiveRecordError do + @connection.create_table(:foos, force: true) do |t| + t.timestamps precision: 7 + end + end end - date = ::Time.utc(2014, 8, 17, 12, 30, 0, 999999) - Foo.create!(created_at: date, updated_at: date) - assert foo = Foo.find_by(created_at: date) - assert_equal 1, Foo.where(updated_at: date).count - assert_equal date.to_s, foo.created_at.to_s - assert_equal date.to_s, foo.updated_at.to_s - assert_equal 000000, foo.created_at.usec - assert_equal 999900, foo.updated_at.usec - end - def test_schema_dump_includes_datetime_precision - @connection.create_table(:foos, force: true) do |t| - t.timestamps precision: 6 + def test_formatting_datetime_according_to_precision + @connection.create_table(:foos, force: true) do |t| + t.datetime :created_at, precision: 0 + t.datetime :updated_at, precision: 4 + end + date = ::Time.utc(2014, 8, 17, 12, 30, 0, 999999) + Foo.create!(created_at: date, updated_at: date) + assert foo = Foo.find_by(created_at: date) + assert_equal 1, Foo.where(updated_at: date).count + assert_equal date.to_s, foo.created_at.to_s + assert_equal date.to_s, foo.updated_at.to_s + assert_equal 000000, foo.created_at.usec + assert_equal 999900, foo.updated_at.usec end - output = dump_table_schema("foos") - assert_match %r{t\.datetime\s+"created_at",\s+precision: 6,\s+null: false$}, output - assert_match %r{t\.datetime\s+"updated_at",\s+precision: 6,\s+null: false$}, output - end - if current_adapter?(:PostgreSQLAdapter) - def test_datetime_precision_with_zero_should_be_dumped + def test_schema_dump_includes_datetime_precision @connection.create_table(:foos, force: true) do |t| - t.timestamps precision: 0 + t.timestamps precision: 6 end output = dump_table_schema("foos") - assert_match %r{t\.datetime\s+"created_at",\s+precision: 0,\s+null: false$}, output - assert_match %r{t\.datetime\s+"updated_at",\s+precision: 0,\s+null: false$}, output + assert_match %r{t\.datetime\s+"created_at",\s+precision: 6,\s+null: false$}, output + assert_match %r{t\.datetime\s+"updated_at",\s+precision: 6,\s+null: false$}, output end - end -end + if current_adapter?(:PostgreSQLAdapter) + def test_datetime_precision_with_zero_should_be_dumped + @connection.create_table(:foos, force: true) do |t| + t.timestamps precision: 0 + end + output = dump_table_schema("foos") + assert_match %r{t\.datetime\s+"created_at",\s+precision: 0,\s+null: false$}, output + assert_match %r{t\.datetime\s+"updated_at",\s+precision: 0,\s+null: false$}, output + end + end + + end end diff --git a/activerecord/test/cases/finder_respond_to_test.rb b/activerecord/test/cases/finder_respond_to_test.rb index 1b3d6a71b2..6e772c9d8a 100644 --- a/activerecord/test/cases/finder_respond_to_test.rb +++ b/activerecord/test/cases/finder_respond_to_test.rb @@ -54,7 +54,7 @@ class FinderRespondToTest < ActiveRecord::TestCase private - def ensure_topic_method_is_not_cached(method_id) - class << Topic; self; end.send(:remove_method, method_id) if Topic.public_methods.include? method_id - end + def ensure_topic_method_is_not_cached(method_id) + class << Topic; self; end.send(:remove_method, method_id) if Topic.public_methods.include? method_id + end end diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index b3745d9dec..3855bf4420 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -853,7 +853,7 @@ class FinderTest < ActiveRecord::TestCase Company.where(["id=? AND name = ?", 2]).first } assert_raise(ActiveRecord::PreparedStatementInvalid) { - Company.where(["id=?", 2, 3, 4]).first + Company.where(["id=?", 2, 3, 4]).first } end diff --git a/activerecord/test/cases/fixture_set/file_test.rb b/activerecord/test/cases/fixture_set/file_test.rb index 45b770ab8c..e69c9f303a 100644 --- a/activerecord/test/cases/fixture_set/file_test.rb +++ b/activerecord/test/cases/fixture_set/file_test.rb @@ -142,15 +142,15 @@ END end private - def tmp_yaml(name, contents) - t = Tempfile.new name - t.binmode - t.write contents - t.close - yield t - ensure - t.close true - end + def tmp_yaml(name, contents) + t = Tempfile.new name + t.binmode + t.write contents + t.close + yield t + ensure + t.close true + end end end end diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index 16b8a19dc4..ebd4437a87 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -188,17 +188,17 @@ end module InTimeZone private - def in_time_zone(zone) - old_zone = Time.zone - old_tz = ActiveRecord::Base.time_zone_aware_attributes - - Time.zone = zone ? ActiveSupport::TimeZone[zone] : nil - ActiveRecord::Base.time_zone_aware_attributes = !zone.nil? - yield - ensure - Time.zone = old_zone - ActiveRecord::Base.time_zone_aware_attributes = old_tz - end + def in_time_zone(zone) + old_zone = Time.zone + old_tz = ActiveRecord::Base.time_zone_aware_attributes + + Time.zone = zone ? ActiveSupport::TimeZone[zone] : nil + ActiveRecord::Base.time_zone_aware_attributes = !zone.nil? + yield + ensure + Time.zone = old_zone + ActiveRecord::Base.time_zone_aware_attributes = old_tz + end end require "mocha/setup" # FIXME: stop using mocha diff --git a/activerecord/test/cases/hot_compatibility_test.rb b/activerecord/test/cases/hot_compatibility_test.rb index 42e7235fba..e0946544ef 100644 --- a/activerecord/test/cases/hot_compatibility_test.rb +++ b/activerecord/test/cases/hot_compatibility_test.rb @@ -114,29 +114,29 @@ class HotCompatibilityTest < ActiveRecord::TestCase private - def get_prepared_statement_cache(connection) - connection.instance_variable_get(:@statements) - .instance_variable_get(:@cache)[Process.pid] - end + def get_prepared_statement_cache(connection) + connection.instance_variable_get(:@statements) + .instance_variable_get(:@cache)[Process.pid] + end # Rails will automatically clear the prepared statements on the connection # that runs the migration, so we use two connections to simulate what would # actually happen on a production system; we'd have one connection running the # migration from the rake task ("ddl_connection" here), and we'd have another # connection in a web worker. - def with_two_connections - run_without_connection do |original_connection| - ActiveRecord::Base.establish_connection(original_connection.merge(pool_size: 2)) - begin - ddl_connection = ActiveRecord::Base.connection_pool.checkout + def with_two_connections + run_without_connection do |original_connection| + ActiveRecord::Base.establish_connection(original_connection.merge(pool_size: 2)) begin - yield original_connection, ddl_connection + ddl_connection = ActiveRecord::Base.connection_pool.checkout + begin + yield original_connection, ddl_connection + ensure + ActiveRecord::Base.connection_pool.checkin ddl_connection + end ensure - ActiveRecord::Base.connection_pool.checkin ddl_connection + ActiveRecord::Base.clear_all_connections! end - ensure - ActiveRecord::Base.clear_all_connections! end end - end end diff --git a/activerecord/test/cases/invalid_connection_test.rb b/activerecord/test/cases/invalid_connection_test.rb index 04fb4ed24e..1367af2859 100644 --- a/activerecord/test/cases/invalid_connection_test.rb +++ b/activerecord/test/cases/invalid_connection_test.rb @@ -1,24 +1,24 @@ require "cases/helper" if current_adapter?(:Mysql2Adapter) -class TestAdapterWithInvalidConnection < ActiveRecord::TestCase - self.use_transactional_tests = false + class TestAdapterWithInvalidConnection < ActiveRecord::TestCase + self.use_transactional_tests = false - class Bird < ActiveRecord::Base - end + class Bird < ActiveRecord::Base + end - def setup - # Can't just use current adapter; sqlite3 will create a database - # file on the fly. - Bird.establish_connection adapter: "mysql2", database: "i_do_not_exist" - end + def setup + # Can't just use current adapter; sqlite3 will create a database + # file on the fly. + Bird.establish_connection adapter: "mysql2", database: "i_do_not_exist" + end - teardown do - Bird.remove_connection - end + teardown do + Bird.remove_connection + end - test "inspect on Model class does not raise" do - assert_equal "#{Bird.name} (call '#{Bird.name}.connection' to establish a connection)", Bird.inspect + test "inspect on Model class does not raise" do + assert_equal "#{Bird.name} (call '#{Bird.name}.connection' to establish a connection)", Bird.inspect + end end end -end diff --git a/activerecord/test/cases/json_serialization_test.rb b/activerecord/test/cases/json_serialization_test.rb index 7f407f84da..814d3b63b2 100644 --- a/activerecord/test/cases/json_serialization_test.rb +++ b/activerecord/test/cases/json_serialization_test.rb @@ -9,13 +9,13 @@ require "models/comment" module JsonSerializationHelpers private - def set_include_root_in_json(value) - original_root_in_json = ActiveRecord::Base.include_root_in_json - ActiveRecord::Base.include_root_in_json = value - yield - ensure - ActiveRecord::Base.include_root_in_json = original_root_in_json - end + def set_include_root_in_json(value) + original_root_in_json = ActiveRecord::Base.include_root_in_json + ActiveRecord::Base.include_root_in_json = value + yield + ensure + ActiveRecord::Base.include_root_in_json = original_root_in_json + end end class JsonSerializationTest < ActiveRecord::TestCase @@ -275,7 +275,7 @@ class DatabaseConnectedJsonEncodingTest < ActiveRecord::TestCase ['"name":"David"', '"posts":[', '{"id":1}', '{"id":2}', '{"id":4}', '{"id":5}', '{"id":6}', '"name":"Mary"', '"posts":[', '{"id":7}', '{"id":9}'].each do |fragment| - assert json.include?(fragment), json + assert json.include?(fragment), json end end diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb index f5c9945b37..84f252d5d1 100644 --- a/activerecord/test/cases/locking_test.rb +++ b/activerecord/test/cases/locking_test.rb @@ -461,33 +461,33 @@ unless in_memory_db? end protected - def duel(zzz = 5) - t0, t1, t2, t3 = nil, nil, nil, nil - - a = Thread.new do - t0 = Time.now - Person.transaction do - yield - sleep zzz # block thread 2 for zzz seconds - end - t1 = Time.now - end + def duel(zzz = 5) + t0, t1, t2, t3 = nil, nil, nil, nil - b = Thread.new do - sleep zzz / 2.0 # ensure thread 1 tx starts first - t2 = Time.now - Person.transaction { yield } - t3 = Time.now + a = Thread.new do + t0 = Time.now + Person.transaction do + yield + sleep zzz # block thread 2 for zzz seconds end + t1 = Time.now + end - a.join - b.join - - assert t1 > t0 + zzz - assert t2 > t0 - assert t3 > t2 - [t0.to_f..t1.to_f, t2.to_f..t3.to_f] + b = Thread.new do + sleep zzz / 2.0 # ensure thread 1 tx starts first + t2 = Time.now + Person.transaction { yield } + t3 = Time.now end + + a.join + b.join + + assert t1 > t0 + zzz + assert t2 > t0 + assert t3 > t2 + [t0.to_f..t1.to_f, t2.to_f..t3.to_f] + end end end end diff --git a/activerecord/test/cases/migration/change_schema_test.rb b/activerecord/test/cases/migration/change_schema_test.rb index 7f6364bc57..0191c9d03b 100644 --- a/activerecord/test/cases/migration/change_schema_test.rb +++ b/activerecord/test/cases/migration/change_schema_test.rb @@ -415,13 +415,13 @@ module ActiveRecord end private - def testing_table_with_only_foo_attribute - connection.create_table :testings, id: false do |t| - t.column :foo, :string - end + def testing_table_with_only_foo_attribute + connection.create_table :testings, id: false do |t| + t.column :foo, :string + end - yield - end + yield + end end if ActiveRecord::Base.connection.supports_foreign_keys? diff --git a/activerecord/test/cases/migration/columns_test.rb b/activerecord/test/cases/migration/columns_test.rb index 95c3f51539..baf0a0eb9f 100644 --- a/activerecord/test/cases/migration/columns_test.rb +++ b/activerecord/test/cases/migration/columns_test.rb @@ -74,7 +74,7 @@ module ActiveRecord def test_rename_nonexistent_column exception = if current_adapter?(:PostgreSQLAdapter, :OracleAdapter) - ActiveRecord::StatementInvalid + ActiveRecord::StatementInvalid else ActiveRecord::ActiveRecordError end diff --git a/activerecord/test/cases/migration/foreign_key_test.rb b/activerecord/test/cases/migration/foreign_key_test.rb index b47df24b13..a9a3885e32 100644 --- a/activerecord/test/cases/migration/foreign_key_test.rb +++ b/activerecord/test/cases/migration/foreign_key_test.rb @@ -3,315 +3,315 @@ require "support/ddl_helper" require "support/schema_dumping_helper" if ActiveRecord::Base.connection.supports_foreign_keys? -module ActiveRecord - class Migration - class ForeignKeyTest < ActiveRecord::TestCase - include DdlHelper - include SchemaDumpingHelper - include ActiveSupport::Testing::Stream - - class Rocket < ActiveRecord::Base - end - - class Astronaut < ActiveRecord::Base - end - - setup do - @connection = ActiveRecord::Base.connection - @connection.create_table "rockets", force: true do |t| - t.string :name + module ActiveRecord + class Migration + class ForeignKeyTest < ActiveRecord::TestCase + include DdlHelper + include SchemaDumpingHelper + include ActiveSupport::Testing::Stream + + class Rocket < ActiveRecord::Base end - @connection.create_table "astronauts", force: true do |t| - t.string :name - t.references :rocket + class Astronaut < ActiveRecord::Base end - end - teardown do - if defined?(@connection) - @connection.drop_table "astronauts", if_exists: true - @connection.drop_table "rockets", if_exists: true - end - end - - def test_foreign_keys - foreign_keys = @connection.foreign_keys("fk_test_has_fk") - assert_equal 1, foreign_keys.size + setup do + @connection = ActiveRecord::Base.connection + @connection.create_table "rockets", force: true do |t| + t.string :name + end - fk = foreign_keys.first - assert_equal "fk_test_has_fk", fk.from_table - assert_equal "fk_test_has_pk", fk.to_table - assert_equal "fk_id", fk.column - assert_equal "pk_id", fk.primary_key - assert_equal "fk_name", fk.name - end + @connection.create_table "astronauts", force: true do |t| + t.string :name + t.references :rocket + end + end - def test_add_foreign_key_inferes_column - @connection.add_foreign_key :astronauts, :rockets + teardown do + if defined?(@connection) + @connection.drop_table "astronauts", if_exists: true + @connection.drop_table "rockets", if_exists: true + end + end - foreign_keys = @connection.foreign_keys("astronauts") - assert_equal 1, foreign_keys.size + def test_foreign_keys + foreign_keys = @connection.foreign_keys("fk_test_has_fk") + assert_equal 1, foreign_keys.size - fk = foreign_keys.first - assert_equal "astronauts", fk.from_table - assert_equal "rockets", fk.to_table - assert_equal "rocket_id", fk.column - assert_equal "id", fk.primary_key - assert_equal("fk_rails_78146ddd2e", fk.name) - end + fk = foreign_keys.first + assert_equal "fk_test_has_fk", fk.from_table + assert_equal "fk_test_has_pk", fk.to_table + assert_equal "fk_id", fk.column + assert_equal "pk_id", fk.primary_key + assert_equal "fk_name", fk.name + end - def test_add_foreign_key_with_column - @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id" + def test_add_foreign_key_inferes_column + @connection.add_foreign_key :astronauts, :rockets - foreign_keys = @connection.foreign_keys("astronauts") - assert_equal 1, foreign_keys.size + foreign_keys = @connection.foreign_keys("astronauts") + assert_equal 1, foreign_keys.size - fk = foreign_keys.first - assert_equal "astronauts", fk.from_table - assert_equal "rockets", fk.to_table - assert_equal "rocket_id", fk.column - assert_equal "id", fk.primary_key - assert_equal("fk_rails_78146ddd2e", fk.name) - end + fk = foreign_keys.first + assert_equal "astronauts", fk.from_table + assert_equal "rockets", fk.to_table + assert_equal "rocket_id", fk.column + assert_equal "id", fk.primary_key + assert_equal("fk_rails_78146ddd2e", fk.name) + end - def test_add_foreign_key_with_non_standard_primary_key - with_example_table @connection, "space_shuttles", "pk integer PRIMARY KEY" do - @connection.add_foreign_key(:astronauts, :space_shuttles, - column: "rocket_id", primary_key: "pk", name: "custom_pk") + def test_add_foreign_key_with_column + @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id" foreign_keys = @connection.foreign_keys("astronauts") assert_equal 1, foreign_keys.size fk = foreign_keys.first assert_equal "astronauts", fk.from_table - assert_equal "space_shuttles", fk.to_table - assert_equal "pk", fk.primary_key - - @connection.remove_foreign_key :astronauts, name: "custom_pk" + assert_equal "rockets", fk.to_table + assert_equal "rocket_id", fk.column + assert_equal "id", fk.primary_key + assert_equal("fk_rails_78146ddd2e", fk.name) end - end - def test_add_on_delete_restrict_foreign_key - @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :restrict + def test_add_foreign_key_with_non_standard_primary_key + with_example_table @connection, "space_shuttles", "pk integer PRIMARY KEY" do + @connection.add_foreign_key(:astronauts, :space_shuttles, + column: "rocket_id", primary_key: "pk", name: "custom_pk") + + foreign_keys = @connection.foreign_keys("astronauts") + assert_equal 1, foreign_keys.size - foreign_keys = @connection.foreign_keys("astronauts") - assert_equal 1, foreign_keys.size + fk = foreign_keys.first + assert_equal "astronauts", fk.from_table + assert_equal "space_shuttles", fk.to_table + assert_equal "pk", fk.primary_key - fk = foreign_keys.first - if current_adapter?(:Mysql2Adapter) - # ON DELETE RESTRICT is the default on MySQL - assert_equal nil, fk.on_delete - else - assert_equal :restrict, fk.on_delete + @connection.remove_foreign_key :astronauts, name: "custom_pk" + end end - end - def test_add_on_delete_cascade_foreign_key - @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :cascade + def test_add_on_delete_restrict_foreign_key + @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :restrict - foreign_keys = @connection.foreign_keys("astronauts") - assert_equal 1, foreign_keys.size + foreign_keys = @connection.foreign_keys("astronauts") + assert_equal 1, foreign_keys.size - fk = foreign_keys.first - assert_equal :cascade, fk.on_delete - end + fk = foreign_keys.first + if current_adapter?(:Mysql2Adapter) + # ON DELETE RESTRICT is the default on MySQL + assert_equal nil, fk.on_delete + else + assert_equal :restrict, fk.on_delete + end + end - def test_add_on_delete_nullify_foreign_key - @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :nullify + def test_add_on_delete_cascade_foreign_key + @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :cascade - foreign_keys = @connection.foreign_keys("astronauts") - assert_equal 1, foreign_keys.size + foreign_keys = @connection.foreign_keys("astronauts") + assert_equal 1, foreign_keys.size - fk = foreign_keys.first - assert_equal :nullify, fk.on_delete - end + fk = foreign_keys.first + assert_equal :cascade, fk.on_delete + end + + def test_add_on_delete_nullify_foreign_key + @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :nullify + + foreign_keys = @connection.foreign_keys("astronauts") + assert_equal 1, foreign_keys.size - def test_on_update_and_on_delete_raises_with_invalid_values - assert_raises ArgumentError do - @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :invalid + fk = foreign_keys.first + assert_equal :nullify, fk.on_delete end - assert_raises ArgumentError do - @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_update: :invalid + def test_on_update_and_on_delete_raises_with_invalid_values + assert_raises ArgumentError do + @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :invalid + end + + assert_raises ArgumentError do + @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_update: :invalid + end end - end - def test_add_foreign_key_with_on_update - @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_update: :nullify + def test_add_foreign_key_with_on_update + @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_update: :nullify + + foreign_keys = @connection.foreign_keys("astronauts") + assert_equal 1, foreign_keys.size - foreign_keys = @connection.foreign_keys("astronauts") - assert_equal 1, foreign_keys.size + fk = foreign_keys.first + assert_equal :nullify, fk.on_update + end - fk = foreign_keys.first - assert_equal :nullify, fk.on_update - end + def test_foreign_key_exists + @connection.add_foreign_key :astronauts, :rockets - def test_foreign_key_exists - @connection.add_foreign_key :astronauts, :rockets + assert @connection.foreign_key_exists?(:astronauts, :rockets) + assert_not @connection.foreign_key_exists?(:astronauts, :stars) + end - assert @connection.foreign_key_exists?(:astronauts, :rockets) - assert_not @connection.foreign_key_exists?(:astronauts, :stars) - end + def test_foreign_key_exists_by_column + @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id" - def test_foreign_key_exists_by_column - @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id" + assert @connection.foreign_key_exists?(:astronauts, column: "rocket_id") + assert_not @connection.foreign_key_exists?(:astronauts, column: "star_id") + end - assert @connection.foreign_key_exists?(:astronauts, column: "rocket_id") - assert_not @connection.foreign_key_exists?(:astronauts, column: "star_id") - end + def test_foreign_key_exists_by_name + @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", name: "fancy_named_fk" - def test_foreign_key_exists_by_name - @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", name: "fancy_named_fk" + assert @connection.foreign_key_exists?(:astronauts, name: "fancy_named_fk") + assert_not @connection.foreign_key_exists?(:astronauts, name: "other_fancy_named_fk") + end - assert @connection.foreign_key_exists?(:astronauts, name: "fancy_named_fk") - assert_not @connection.foreign_key_exists?(:astronauts, name: "other_fancy_named_fk") - end + def test_remove_foreign_key_inferes_column + @connection.add_foreign_key :astronauts, :rockets - def test_remove_foreign_key_inferes_column - @connection.add_foreign_key :astronauts, :rockets + assert_equal 1, @connection.foreign_keys("astronauts").size + @connection.remove_foreign_key :astronauts, :rockets + assert_equal [], @connection.foreign_keys("astronauts") + end - assert_equal 1, @connection.foreign_keys("astronauts").size - @connection.remove_foreign_key :astronauts, :rockets - assert_equal [], @connection.foreign_keys("astronauts") - end + def test_remove_foreign_key_by_column + @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id" - def test_remove_foreign_key_by_column - @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id" + assert_equal 1, @connection.foreign_keys("astronauts").size + @connection.remove_foreign_key :astronauts, column: "rocket_id" + assert_equal [], @connection.foreign_keys("astronauts") + end - assert_equal 1, @connection.foreign_keys("astronauts").size - @connection.remove_foreign_key :astronauts, column: "rocket_id" - assert_equal [], @connection.foreign_keys("astronauts") - end + def test_remove_foreign_key_by_symbol_column + @connection.add_foreign_key :astronauts, :rockets, column: :rocket_id - def test_remove_foreign_key_by_symbol_column - @connection.add_foreign_key :astronauts, :rockets, column: :rocket_id + assert_equal 1, @connection.foreign_keys("astronauts").size + @connection.remove_foreign_key :astronauts, column: :rocket_id + assert_equal [], @connection.foreign_keys("astronauts") + end - assert_equal 1, @connection.foreign_keys("astronauts").size - @connection.remove_foreign_key :astronauts, column: :rocket_id - assert_equal [], @connection.foreign_keys("astronauts") - end + def test_remove_foreign_key_by_name + @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", name: "fancy_named_fk" - def test_remove_foreign_key_by_name - @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", name: "fancy_named_fk" + assert_equal 1, @connection.foreign_keys("astronauts").size + @connection.remove_foreign_key :astronauts, name: "fancy_named_fk" + assert_equal [], @connection.foreign_keys("astronauts") + end - assert_equal 1, @connection.foreign_keys("astronauts").size - @connection.remove_foreign_key :astronauts, name: "fancy_named_fk" - assert_equal [], @connection.foreign_keys("astronauts") - end + def test_remove_foreign_non_existing_foreign_key_raises + assert_raises ArgumentError do + @connection.remove_foreign_key :astronauts, :rockets + end + end - def test_remove_foreign_non_existing_foreign_key_raises - assert_raises ArgumentError do - @connection.remove_foreign_key :astronauts, :rockets + def test_schema_dumping + @connection.add_foreign_key :astronauts, :rockets + output = dump_table_schema "astronauts" + assert_match %r{\s+add_foreign_key "astronauts", "rockets"$}, output end - end - def test_schema_dumping - @connection.add_foreign_key :astronauts, :rockets - output = dump_table_schema "astronauts" - assert_match %r{\s+add_foreign_key "astronauts", "rockets"$}, output - end + def test_schema_dumping_with_options + output = dump_table_schema "fk_test_has_fk" + assert_match %r{\s+add_foreign_key "fk_test_has_fk", "fk_test_has_pk", column: "fk_id", primary_key: "pk_id", name: "fk_name"$}, output + end - def test_schema_dumping_with_options - output = dump_table_schema "fk_test_has_fk" - assert_match %r{\s+add_foreign_key "fk_test_has_fk", "fk_test_has_pk", column: "fk_id", primary_key: "pk_id", name: "fk_name"$}, output - end + def test_schema_dumping_on_delete_and_on_update_options + @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :nullify, on_update: :cascade - def test_schema_dumping_on_delete_and_on_update_options - @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", on_delete: :nullify, on_update: :cascade + output = dump_table_schema "astronauts" + assert_match %r{\s+add_foreign_key "astronauts",.+on_update: :cascade,.+on_delete: :nullify$}, output + end - output = dump_table_schema "astronauts" - assert_match %r{\s+add_foreign_key "astronauts",.+on_update: :cascade,.+on_delete: :nullify$}, output - end + class CreateCitiesAndHousesMigration < ActiveRecord::Migration::Current + def change + create_table("cities") { |t| } - class CreateCitiesAndHousesMigration < ActiveRecord::Migration::Current - def change - create_table("cities") { |t| } + create_table("houses") do |t| + t.column :city_id, :integer + end + add_foreign_key :houses, :cities, column: "city_id" - create_table("houses") do |t| - t.column :city_id, :integer + # remove and re-add to test that schema is updated and not accidentally cached + remove_foreign_key :houses, :cities + add_foreign_key :houses, :cities, column: "city_id", on_delete: :cascade end - add_foreign_key :houses, :cities, column: "city_id" - - # remove and re-add to test that schema is updated and not accidentally cached - remove_foreign_key :houses, :cities - add_foreign_key :houses, :cities, column: "city_id", on_delete: :cascade end - end - def test_add_foreign_key_is_reversible - migration = CreateCitiesAndHousesMigration.new - silence_stream($stdout) { migration.migrate(:up) } - assert_equal 1, @connection.foreign_keys("houses").size - ensure - silence_stream($stdout) { migration.migrate(:down) } - end + def test_add_foreign_key_is_reversible + migration = CreateCitiesAndHousesMigration.new + silence_stream($stdout) { migration.migrate(:up) } + assert_equal 1, @connection.foreign_keys("houses").size + ensure + silence_stream($stdout) { migration.migrate(:down) } + end - def test_foreign_key_constraint_is_not_cached_incorrectly - migration = CreateCitiesAndHousesMigration.new - silence_stream($stdout) { migration.migrate(:up) } - output = dump_table_schema "houses" - assert_match %r{\s+add_foreign_key "houses",.+on_delete: :cascade$}, output - ensure - silence_stream($stdout) { migration.migrate(:down) } - end + def test_foreign_key_constraint_is_not_cached_incorrectly + migration = CreateCitiesAndHousesMigration.new + silence_stream($stdout) { migration.migrate(:up) } + output = dump_table_schema "houses" + assert_match %r{\s+add_foreign_key "houses",.+on_delete: :cascade$}, output + ensure + silence_stream($stdout) { migration.migrate(:down) } + end - class CreateSchoolsAndClassesMigration < ActiveRecord::Migration::Current - def change - create_table(:schools) + class CreateSchoolsAndClassesMigration < ActiveRecord::Migration::Current + def change + create_table(:schools) - create_table(:classes) do |t| - t.column :school_id, :integer + create_table(:classes) do |t| + t.column :school_id, :integer + end + add_foreign_key :classes, :schools end - add_foreign_key :classes, :schools end - end - def test_add_foreign_key_with_prefix - ActiveRecord::Base.table_name_prefix = "p_" - migration = CreateSchoolsAndClassesMigration.new - silence_stream($stdout) { migration.migrate(:up) } - assert_equal 1, @connection.foreign_keys("p_classes").size - ensure - silence_stream($stdout) { migration.migrate(:down) } - ActiveRecord::Base.table_name_prefix = nil - end + def test_add_foreign_key_with_prefix + ActiveRecord::Base.table_name_prefix = "p_" + migration = CreateSchoolsAndClassesMigration.new + silence_stream($stdout) { migration.migrate(:up) } + assert_equal 1, @connection.foreign_keys("p_classes").size + ensure + silence_stream($stdout) { migration.migrate(:down) } + ActiveRecord::Base.table_name_prefix = nil + end - def test_add_foreign_key_with_suffix - ActiveRecord::Base.table_name_suffix = "_s" - migration = CreateSchoolsAndClassesMigration.new - silence_stream($stdout) { migration.migrate(:up) } - assert_equal 1, @connection.foreign_keys("classes_s").size - ensure - silence_stream($stdout) { migration.migrate(:down) } - ActiveRecord::Base.table_name_suffix = nil - end + def test_add_foreign_key_with_suffix + ActiveRecord::Base.table_name_suffix = "_s" + migration = CreateSchoolsAndClassesMigration.new + silence_stream($stdout) { migration.migrate(:up) } + assert_equal 1, @connection.foreign_keys("classes_s").size + ensure + silence_stream($stdout) { migration.migrate(:down) } + ActiveRecord::Base.table_name_suffix = nil + end + end end end -end else -module ActiveRecord - class Migration - class NoForeignKeySupportTest < ActiveRecord::TestCase - setup do - @connection = ActiveRecord::Base.connection - end + module ActiveRecord + class Migration + class NoForeignKeySupportTest < ActiveRecord::TestCase + setup do + @connection = ActiveRecord::Base.connection + end - def test_add_foreign_key_should_be_noop - @connection.add_foreign_key :clubs, :categories - end + def test_add_foreign_key_should_be_noop + @connection.add_foreign_key :clubs, :categories + end - def test_remove_foreign_key_should_be_noop - @connection.remove_foreign_key :clubs, :categories - end + def test_remove_foreign_key_should_be_noop + @connection.remove_foreign_key :clubs, :categories + end - def test_foreign_keys_should_raise_not_implemented - assert_raises NotImplementedError do - @connection.foreign_keys("clubs") + def test_foreign_keys_should_raise_not_implemented + assert_raises NotImplementedError do + @connection.foreign_keys("clubs") + end end end end end end -end diff --git a/activerecord/test/cases/migration/helper.rb b/activerecord/test/cases/migration/helper.rb index ad85684c0b..9c0fa7339d 100644 --- a/activerecord/test/cases/migration/helper.rb +++ b/activerecord/test/cases/migration/helper.rb @@ -33,7 +33,7 @@ module ActiveRecord private - delegate(*CONNECTION_METHODS, to: :connection) + delegate(*CONNECTION_METHODS, to: :connection) end end end diff --git a/activerecord/test/cases/migration/references_foreign_key_test.rb b/activerecord/test/cases/migration/references_foreign_key_test.rb index 992d003e7e..8436435170 100644 --- a/activerecord/test/cases/migration/references_foreign_key_test.rb +++ b/activerecord/test/cases/migration/references_foreign_key_test.rb @@ -1,216 +1,216 @@ require "cases/helper" if ActiveRecord::Base.connection.supports_foreign_keys? -module ActiveRecord - class Migration - class ReferencesForeignKeyTest < ActiveRecord::TestCase - setup do - @connection = ActiveRecord::Base.connection - @connection.create_table(:testing_parents, force: true) - end - - teardown do - @connection.drop_table "testings", if_exists: true - @connection.drop_table "testing_parents", if_exists: true - end + module ActiveRecord + class Migration + class ReferencesForeignKeyTest < ActiveRecord::TestCase + setup do + @connection = ActiveRecord::Base.connection + @connection.create_table(:testing_parents, force: true) + end - test "foreign keys can be created with the table" do - @connection.create_table :testings do |t| - t.references :testing_parent, foreign_key: true + teardown do + @connection.drop_table "testings", if_exists: true + @connection.drop_table "testing_parents", if_exists: true end - fk = @connection.foreign_keys("testings").first - assert_equal "testings", fk.from_table - assert_equal "testing_parents", fk.to_table - end + test "foreign keys can be created with the table" do + @connection.create_table :testings do |t| + t.references :testing_parent, foreign_key: true + end - test "no foreign key is created by default" do - @connection.create_table :testings do |t| - t.references :testing_parent + fk = @connection.foreign_keys("testings").first + assert_equal "testings", fk.from_table + assert_equal "testing_parents", fk.to_table end - assert_equal [], @connection.foreign_keys("testings") - end - - test "foreign keys can be created in one query when index is not added" do - assert_queries(1) do + test "no foreign key is created by default" do @connection.create_table :testings do |t| - t.references :testing_parent, foreign_key: true, index: false + t.references :testing_parent end - end - end - test "options hash can be passed" do - @connection.change_table :testing_parents do |t| - t.integer :other_id - t.index :other_id, unique: true + assert_equal [], @connection.foreign_keys("testings") end - @connection.create_table :testings do |t| - t.references :testing_parent, foreign_key: { primary_key: :other_id } + + test "foreign keys can be created in one query when index is not added" do + assert_queries(1) do + @connection.create_table :testings do |t| + t.references :testing_parent, foreign_key: true, index: false + end + end end - fk = @connection.foreign_keys("testings").find { |k| k.to_table == "testing_parents" } - assert_equal "other_id", fk.primary_key - end + test "options hash can be passed" do + @connection.change_table :testing_parents do |t| + t.integer :other_id + t.index :other_id, unique: true + end + @connection.create_table :testings do |t| + t.references :testing_parent, foreign_key: { primary_key: :other_id } + end - test "to_table option can be passed" do - @connection.create_table :testings do |t| - t.references :parent, foreign_key: { to_table: :testing_parents } + fk = @connection.foreign_keys("testings").find { |k| k.to_table == "testing_parents" } + assert_equal "other_id", fk.primary_key end - fks = @connection.foreign_keys("testings") - assert_equal([["testings", "testing_parents", "parent_id"]], - 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 - @connection.create_table :testings do |t| - assert_raises(ArgumentError) do - t.references :testing_parent, polymorphic: true, foreign_key: true + test "to_table option can be passed" do + @connection.create_table :testings do |t| + t.references :parent, foreign_key: { to_table: :testing_parents } end + fks = @connection.foreign_keys("testings") + assert_equal([["testings", "testing_parents", "parent_id"]], + fks.map {|fk| [fk.from_table, fk.to_table, fk.column] }) end - end - test "foreign keys can be created while changing the table" do - @connection.create_table :testings - @connection.change_table :testings do |t| - t.references :testing_parent, foreign_key: true + test "foreign keys cannot be added to polymorphic relations when creating the table" do + @connection.create_table :testings do |t| + assert_raises(ArgumentError) do + t.references :testing_parent, polymorphic: true, foreign_key: true + end + end end - fk = @connection.foreign_keys("testings").first - assert_equal "testings", fk.from_table - assert_equal "testing_parents", fk.to_table - end + test "foreign keys can be created while changing the table" do + @connection.create_table :testings + @connection.change_table :testings do |t| + t.references :testing_parent, foreign_key: true + end - test "foreign keys are not added by default when changing the table" do - @connection.create_table :testings - @connection.change_table :testings do |t| - t.references :testing_parent + fk = @connection.foreign_keys("testings").first + assert_equal "testings", fk.from_table + assert_equal "testing_parents", fk.to_table end - assert_equal [], @connection.foreign_keys("testings") - end + test "foreign keys are not added by default when changing the table" do + @connection.create_table :testings + @connection.change_table :testings do |t| + t.references :testing_parent + end - test "foreign keys accept options when changing the table" do - @connection.change_table :testing_parents do |t| - t.integer :other_id - t.index :other_id, unique: true - end - @connection.create_table :testings - @connection.change_table :testings do |t| - t.references :testing_parent, foreign_key: { primary_key: :other_id } + assert_equal [], @connection.foreign_keys("testings") end - fk = @connection.foreign_keys("testings").find { |k| k.to_table == "testing_parents" } - assert_equal "other_id", fk.primary_key - end - - test "foreign keys cannot be added to polymorphic relations when changing the table" do - @connection.create_table :testings - @connection.change_table :testings do |t| - assert_raises(ArgumentError) do - t.references :testing_parent, polymorphic: true, foreign_key: true + test "foreign keys accept options when changing the table" do + @connection.change_table :testing_parents do |t| + t.integer :other_id + t.index :other_id, unique: true + end + @connection.create_table :testings + @connection.change_table :testings do |t| + t.references :testing_parent, foreign_key: { primary_key: :other_id } end - end - end - test "foreign key column can be removed" do - @connection.create_table :testings do |t| - t.references :testing_parent, index: true, foreign_key: true + fk = @connection.foreign_keys("testings").find { |k| k.to_table == "testing_parents" } + assert_equal "other_id", fk.primary_key end - assert_difference "@connection.foreign_keys('testings').size", -1 do - @connection.remove_reference :testings, :testing_parent, foreign_key: true + test "foreign keys cannot be added to polymorphic relations when changing the table" do + @connection.create_table :testings + @connection.change_table :testings do |t| + assert_raises(ArgumentError) do + t.references :testing_parent, polymorphic: true, foreign_key: true + end + end end - end - test "foreign key methods respect pluralize_table_names" do - begin - original_pluralize_table_names = ActiveRecord::Base.pluralize_table_names - ActiveRecord::Base.pluralize_table_names = false - @connection.create_table :testing - @connection.change_table :testing_parents do |t| - t.references :testing, foreign_key: true + test "foreign key column can be removed" do + @connection.create_table :testings do |t| + t.references :testing_parent, index: true, foreign_key: true end - fk = @connection.foreign_keys("testing_parents").first - assert_equal "testing_parents", fk.from_table - assert_equal "testing", fk.to_table + assert_difference "@connection.foreign_keys('testings').size", -1 do + @connection.remove_reference :testings, :testing_parent, foreign_key: true + end + end - assert_difference "@connection.foreign_keys('testing_parents').size", -1 do - @connection.remove_reference :testing_parents, :testing, foreign_key: true + test "foreign key methods respect pluralize_table_names" do + begin + original_pluralize_table_names = ActiveRecord::Base.pluralize_table_names + ActiveRecord::Base.pluralize_table_names = false + @connection.create_table :testing + @connection.change_table :testing_parents do |t| + t.references :testing, foreign_key: true + end + + fk = @connection.foreign_keys("testing_parents").first + assert_equal "testing_parents", fk.from_table + assert_equal "testing", fk.to_table + + assert_difference "@connection.foreign_keys('testing_parents').size", -1 do + @connection.remove_reference :testing_parents, :testing, foreign_key: true + end + ensure + ActiveRecord::Base.pluralize_table_names = original_pluralize_table_names + @connection.drop_table "testing", if_exists: true end - ensure - ActiveRecord::Base.pluralize_table_names = original_pluralize_table_names - @connection.drop_table "testing", if_exists: true end - end - class CreateDogsMigration < ActiveRecord::Migration::Current - def change - create_table :dog_owners + class CreateDogsMigration < ActiveRecord::Migration::Current + def change + create_table :dog_owners - create_table :dogs do |t| - t.references :dog_owner, foreign_key: true + create_table :dogs do |t| + t.references :dog_owner, foreign_key: true + end end end - end - def test_references_foreign_key_with_prefix - ActiveRecord::Base.table_name_prefix = "p_" - migration = CreateDogsMigration.new - silence_stream($stdout) { migration.migrate(:up) } - assert_equal 1, @connection.foreign_keys("p_dogs").size - ensure - silence_stream($stdout) { migration.migrate(:down) } - ActiveRecord::Base.table_name_prefix = nil - end + def test_references_foreign_key_with_prefix + ActiveRecord::Base.table_name_prefix = "p_" + migration = CreateDogsMigration.new + silence_stream($stdout) { migration.migrate(:up) } + assert_equal 1, @connection.foreign_keys("p_dogs").size + ensure + silence_stream($stdout) { migration.migrate(:down) } + ActiveRecord::Base.table_name_prefix = nil + end - def test_references_foreign_key_with_suffix - ActiveRecord::Base.table_name_suffix = "_s" - migration = CreateDogsMigration.new - silence_stream($stdout) { migration.migrate(:up) } - assert_equal 1, @connection.foreign_keys("dogs_s").size - ensure - silence_stream($stdout) { migration.migrate(:down) } - ActiveRecord::Base.table_name_suffix = nil - end + def test_references_foreign_key_with_suffix + ActiveRecord::Base.table_name_suffix = "_s" + migration = CreateDogsMigration.new + silence_stream($stdout) { migration.migrate(:up) } + assert_equal 1, @connection.foreign_keys("dogs_s").size + ensure + silence_stream($stdout) { migration.migrate(:down) } + ActiveRecord::Base.table_name_suffix = nil + end - test "multiple foreign keys can be added to the same table" do - @connection.create_table :testings do |t| - t.integer :col_1 - t.integer :col_2 + test "multiple foreign keys can be added to the same table" do + @connection.create_table :testings do |t| + t.integer :col_1 + t.integer :col_2 - t.foreign_key :testing_parents, column: :col_1 - t.foreign_key :testing_parents, column: :col_2 - end + t.foreign_key :testing_parents, column: :col_1 + t.foreign_key :testing_parents, column: :col_2 + end - fks = @connection.foreign_keys("testings") + fks = @connection.foreign_keys("testings") - 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) + 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 end end end -end else -class ReferencesWithoutForeignKeySupportTest < ActiveRecord::TestCase - setup do - @connection = ActiveRecord::Base.connection - @connection.create_table(:testing_parents, force: true) - end - - teardown do - @connection.drop_table("testings", if_exists: true) - @connection.drop_table("testing_parents", if_exists: true) - end + class ReferencesWithoutForeignKeySupportTest < ActiveRecord::TestCase + setup do + @connection = ActiveRecord::Base.connection + @connection.create_table(:testing_parents, force: true) + end - test "ignores foreign keys defined with the table" do - @connection.create_table :testings do |t| - t.references :testing_parent, foreign_key: true + teardown do + @connection.drop_table("testings", if_exists: true) + @connection.drop_table("testing_parents", if_exists: true) end - assert_includes @connection.data_sources, "testings" + test "ignores foreign keys defined with the table" do + @connection.create_table :testings do |t| + t.references :testing_parent, foreign_key: true + end + + assert_includes @connection.data_sources, "testings" + end end end -end diff --git a/activerecord/test/cases/migration/references_statements_test.rb b/activerecord/test/cases/migration/references_statements_test.rb index 8d0acaaa6e..8fbe60f24e 100644 --- a/activerecord/test/cases/migration/references_statements_test.rb +++ b/activerecord/test/cases/migration/references_statements_test.rb @@ -110,12 +110,12 @@ module ActiveRecord private - def with_polymorphic_column - add_column table_name, :supplier_type, :string - add_index table_name, [:supplier_id, :supplier_type] + def with_polymorphic_column + add_column table_name, :supplier_type, :string + add_index table_name, [:supplier_id, :supplier_type] - yield - end + yield + end end end end diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb index d3d6931ea4..b8ffc8a154 100644 --- a/activerecord/test/cases/migration_test.rb +++ b/activerecord/test/cases/migration_test.rb @@ -873,30 +873,30 @@ if ActiveRecord::Base.connection.supports_bulk_alter? protected - def with_bulk_change_table - # Reset columns/indexes cache as we're changing the table - @columns = @indexes = nil + def with_bulk_change_table + # Reset columns/indexes cache as we're changing the table + @columns = @indexes = nil - Person.connection.change_table(:delete_me, bulk: true) do |t| - yield t + Person.connection.change_table(:delete_me, bulk: true) do |t| + yield t + end end - end - def column(name) - columns.detect {|c| c.name == name.to_s } - end + def column(name) + columns.detect {|c| c.name == name.to_s } + end - def columns - @columns ||= Person.connection.columns("delete_me") - end + def columns + @columns ||= Person.connection.columns("delete_me") + end - def index(name) - indexes.detect {|i| i.name == name.to_s } - end + def index(name) + indexes.detect {|i| i.name == name.to_s } + end - def indexes - @indexes ||= Person.connection.indexes("delete_me") - end + def indexes + @indexes ||= Person.connection.indexes("delete_me") + end end # AlterTableMigrationsTest end diff --git a/activerecord/test/cases/migrator_test.rb b/activerecord/test/cases/migrator_test.rb index 67af04e2e8..a44bf08095 100644 --- a/activerecord/test/cases/migrator_test.rb +++ b/activerecord/test/cases/migrator_test.rb @@ -92,8 +92,8 @@ class MigratorTest < ActiveRecord::TestCase [20100101010101, "ValidWithTimestampsPeopleHaveLastNames"], [20100201010101, "ValidWithTimestampsWeNeedReminders"], [20100301010101, "ValidWithTimestampsInnocentJointable"]].each_with_index do |pair, i| - assert_equal pair.first, migrations[i].version - assert_equal pair.last, migrations[i].name + assert_equal pair.first, migrations[i].version + assert_equal pair.last, migrations[i].name end end @@ -357,32 +357,32 @@ class MigratorTest < ActiveRecord::TestCase end private - def m(name, version) - x = Sensor.new name, version - x.extend(Module.new { - define_method(:up) { yield(:up, x); super() } - define_method(:down) { yield(:down, x); super() } - }) if block_given? - end + def m(name, version) + x = Sensor.new name, version + x.extend(Module.new { + define_method(:up) { yield(:up, x); super() } + define_method(:down) { yield(:down, x); super() } + }) if block_given? + end - def sensors(count) - calls = [] - migrations = count.times.map { |i| - m(nil, i + 1) { |c,migration| - calls << [c, migration.version] + def sensors(count) + calls = [] + migrations = count.times.map { |i| + m(nil, i + 1) { |c,migration| + calls << [c, migration.version] + } } - } - [calls, migrations] - end + [calls, migrations] + end - def migrator_class(count) - calls, migrations = sensors(count) + def migrator_class(count) + calls, migrations = sensors(count) - migrator = Class.new(ActiveRecord::Migrator).extend(Module.new { - define_method(:migrations) { |paths| - migrations - } - }) - [calls, migrator] - end + migrator = Class.new(ActiveRecord::Migrator).extend(Module.new { + define_method(:migrations) { |paths| + migrations + } + }) + [calls, migrator] + end end diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb index d3923173a7..fc47c42ed1 100644 --- a/activerecord/test/cases/nested_attributes_test.rb +++ b/activerecord/test/cases/nested_attributes_test.rb @@ -839,13 +839,13 @@ module NestedAttributesOnACollectionAssociationTests private - def association_setter - @association_setter ||= "#{@association_name}_attributes=".to_sym - end + def association_setter + @association_setter ||= "#{@association_name}_attributes=".to_sym + end - def association_getter - @association_getter ||= "#{@association_name}_attributes".to_sym - end + def association_getter + @association_getter ||= "#{@association_name}_attributes".to_sym + end end class TestNestedAttributesOnAHasManyAssociation < ActiveRecord::TestCase diff --git a/activerecord/test/cases/nested_attributes_with_callbacks_test.rb b/activerecord/test/cases/nested_attributes_with_callbacks_test.rb index d41b7c2213..d606a6c12d 100644 --- a/activerecord/test/cases/nested_attributes_with_callbacks_test.rb +++ b/activerecord/test/cases/nested_attributes_with_callbacks_test.rb @@ -46,7 +46,7 @@ class NestedAttributesWithCallbacksTest < ActiveRecord::TestCase end def new_bird_attributes - [{"name" => "New Bird"}] + [{"name" => "New Bird"}] end def destroy_bird_attributes diff --git a/activerecord/test/cases/pooled_connections_test.rb b/activerecord/test/cases/pooled_connections_test.rb index f200770562..f1b0d08765 100644 --- a/activerecord/test/cases/pooled_connections_test.rb +++ b/activerecord/test/cases/pooled_connections_test.rb @@ -75,7 +75,7 @@ class PooledConnectionsTest < ActiveRecord::TestCase private - def add_record(name) - ActiveRecord::Base.connection_pool.with_connection { Project.create! name: name } - end + def add_record(name) + ActiveRecord::Base.connection_pool.with_connection { Project.create! name: name } + end end unless in_memory_db? diff --git a/activerecord/test/cases/relation/delegation_test.rb b/activerecord/test/cases/relation/delegation_test.rb index fbae212e65..d2382b9bb2 100644 --- a/activerecord/test/cases/relation/delegation_test.rb +++ b/activerecord/test/cases/relation/delegation_test.rb @@ -18,7 +18,7 @@ module ActiveRecord target.public_send(method, 1) end elsif method_arity == 1 - target.public_send(method, 1) + target.public_send(method, 1) else raise NotImplementedError end diff --git a/activerecord/test/cases/relation/where_clause_test.rb b/activerecord/test/cases/relation/where_clause_test.rb index 2e2bb9fe36..d8e4c304f0 100644 --- a/activerecord/test/cases/relation/where_clause_test.rb +++ b/activerecord/test/cases/relation/where_clause_test.rb @@ -167,16 +167,16 @@ class ActiveRecord::Relation private - def table - Arel::Table.new("table") - end + def table + Arel::Table.new("table") + end - def bind_param - Arel::Nodes::BindParam.new - end + def bind_param + Arel::Nodes::BindParam.new + end - def attribute(name, value) - ActiveRecord::Attribute.with_cast_value(name, value, ActiveRecord::Type::Value.new) - end + def attribute(name, value) + ActiveRecord::Attribute.with_cast_value(name, value, ActiveRecord::Type::Value.new) + end end end diff --git a/activerecord/test/cases/relation_test.rb b/activerecord/test/cases/relation_test.rb index 99f739c6c9..0802afac5a 100644 --- a/activerecord/test/cases/relation_test.rb +++ b/activerecord/test/cases/relation_test.rb @@ -306,23 +306,23 @@ module ActiveRecord private - def skip_if_sqlite3_version_includes_quoting_bug - if sqlite3_version_includes_quoting_bug? - skip <<-ERROR.squish + def skip_if_sqlite3_version_includes_quoting_bug + if sqlite3_version_includes_quoting_bug? + skip <<-ERROR.squish You are using an outdated version of SQLite3 which has a bug in quoted column names. Please update SQLite3 and rebuild the sqlite3 ruby gem ERROR + end end - end - def sqlite3_version_includes_quoting_bug? - if current_adapter?(:SQLite3Adapter) - selected_quoted_column_names = ActiveRecord::Base.connection.exec_query( - 'SELECT "join" FROM (SELECT id AS "join" FROM posts) subquery' - ).columns - ["join"] != selected_quoted_column_names + def sqlite3_version_includes_quoting_bug? + if current_adapter?(:SQLite3Adapter) + selected_quoted_column_names = ActiveRecord::Base.connection.exec_query( + 'SELECT "join" FROM (SELECT id AS "join" FROM posts) subquery' + ).columns + ["join"] != selected_quoted_column_names + end end - end end end diff --git a/activerecord/test/cases/tasks/mysql_rake_test.rb b/activerecord/test/cases/tasks/mysql_rake_test.rb index be2f2e5939..dbe935808e 100644 --- a/activerecord/test/cases/tasks/mysql_rake_test.rb +++ b/activerecord/test/cases/tasks/mysql_rake_test.rb @@ -2,344 +2,344 @@ require "cases/helper" require "active_record/tasks/database_tasks" if current_adapter?(:Mysql2Adapter) -module ActiveRecord - class MysqlDBCreateTest < ActiveRecord::TestCase - def setup - @connection = stub(create_database: true) - @configuration = { - "adapter" => "mysql2", - "database" => "my-app-db" - } - - ActiveRecord::Base.stubs(:connection).returns(@connection) - ActiveRecord::Base.stubs(:establish_connection).returns(true) - - $stdout, @original_stdout = StringIO.new, $stdout - $stderr, @original_stderr = StringIO.new, $stderr - end - - def teardown - $stdout, $stderr = @original_stdout, @original_stderr - end - - def test_establishes_connection_without_database - ActiveRecord::Base.expects(:establish_connection). - with("adapter" => "mysql2", "database" => nil) - - ActiveRecord::Tasks::DatabaseTasks.create @configuration - end - - def test_creates_database_with_no_default_options - @connection.expects(:create_database). - with("my-app-db", {}) + module ActiveRecord + class MysqlDBCreateTest < ActiveRecord::TestCase + def setup + @connection = stub(create_database: true) + @configuration = { + "adapter" => "mysql2", + "database" => "my-app-db" + } - ActiveRecord::Tasks::DatabaseTasks.create @configuration - end + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) - def test_creates_database_with_given_encoding - @connection.expects(:create_database). - with("my-app-db", charset: "latin1") + $stdout, @original_stdout = StringIO.new, $stdout + $stderr, @original_stderr = StringIO.new, $stderr + end - ActiveRecord::Tasks::DatabaseTasks.create @configuration.merge("encoding" => "latin1") - end + def teardown + $stdout, $stderr = @original_stdout, @original_stderr + end - def test_creates_database_with_given_collation - @connection.expects(:create_database). - with("my-app-db", collation: "latin1_swedish_ci") + def test_establishes_connection_without_database + ActiveRecord::Base.expects(:establish_connection). + with("adapter" => "mysql2", "database" => nil) - ActiveRecord::Tasks::DatabaseTasks.create @configuration.merge("collation" => "latin1_swedish_ci") - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end - def test_establishes_connection_to_database - ActiveRecord::Base.expects(:establish_connection).with(@configuration) + def test_creates_database_with_no_default_options + @connection.expects(:create_database). + with("my-app-db", {}) - ActiveRecord::Tasks::DatabaseTasks.create @configuration - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end - def test_when_database_created_successfully_outputs_info_to_stdout - ActiveRecord::Tasks::DatabaseTasks.create @configuration + def test_creates_database_with_given_encoding + @connection.expects(:create_database). + with("my-app-db", charset: "latin1") - assert_equal $stdout.string, "Created database 'my-app-db'\n" - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration.merge("encoding" => "latin1") + end - def test_create_when_database_exists_outputs_info_to_stderr - ActiveRecord::Base.connection.stubs(:create_database).raises( - ActiveRecord::Tasks::DatabaseAlreadyExists - ) + def test_creates_database_with_given_collation + @connection.expects(:create_database). + with("my-app-db", collation: "latin1_swedish_ci") - ActiveRecord::Tasks::DatabaseTasks.create @configuration + ActiveRecord::Tasks::DatabaseTasks.create @configuration.merge("collation" => "latin1_swedish_ci") + end - assert_equal $stderr.string, "Database 'my-app-db' already exists\n" - end - end + def test_establishes_connection_to_database + ActiveRecord::Base.expects(:establish_connection).with(@configuration) - class MysqlDBCreateAsRootTest < ActiveRecord::TestCase - def setup - @connection = stub("Connection", create_database: true) - @error = Mysql2::Error.new("Invalid permissions") - @configuration = { - "adapter" => "mysql2", - "database" => "my-app-db", - "username" => "pat", - "password" => "wossname" - } - - $stdin.stubs(:gets).returns("secret\n") - $stdout.stubs(:print).returns(nil) - @error.stubs(:errno).returns(1045) - ActiveRecord::Base.stubs(:connection).returns(@connection) - ActiveRecord::Base.stubs(:establish_connection). - raises(@error). - then.returns(true) - - $stdout, @original_stdout = StringIO.new, $stdout - $stderr, @original_stderr = StringIO.new, $stderr - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end - def teardown - $stdout, $stderr = @original_stdout, @original_stderr - end + def test_when_database_created_successfully_outputs_info_to_stdout + ActiveRecord::Tasks::DatabaseTasks.create @configuration - def test_root_password_is_requested - assert_permissions_granted_for("pat") - $stdin.expects(:gets).returns("secret\n") + assert_equal $stdout.string, "Created database 'my-app-db'\n" + end - ActiveRecord::Tasks::DatabaseTasks.create @configuration - end + def test_create_when_database_exists_outputs_info_to_stderr + ActiveRecord::Base.connection.stubs(:create_database).raises( + ActiveRecord::Tasks::DatabaseAlreadyExists + ) - def test_connection_established_as_root - assert_permissions_granted_for("pat") - ActiveRecord::Base.expects(:establish_connection).with( - "adapter" => "mysql2", - "database" => nil, - "username" => "root", - "password" => "secret" - ) + ActiveRecord::Tasks::DatabaseTasks.create @configuration - ActiveRecord::Tasks::DatabaseTasks.create @configuration + assert_equal $stderr.string, "Database 'my-app-db' already exists\n" + end end - def test_database_created_by_root - assert_permissions_granted_for("pat") - @connection.expects(:create_database). - with("my-app-db", {}) + class MysqlDBCreateAsRootTest < ActiveRecord::TestCase + def setup + @connection = stub("Connection", create_database: true) + @error = Mysql2::Error.new("Invalid permissions") + @configuration = { + "adapter" => "mysql2", + "database" => "my-app-db", + "username" => "pat", + "password" => "wossname" + } + + $stdin.stubs(:gets).returns("secret\n") + $stdout.stubs(:print).returns(nil) + @error.stubs(:errno).returns(1045) + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection). + raises(@error). + then.returns(true) + + $stdout, @original_stdout = StringIO.new, $stdout + $stderr, @original_stderr = StringIO.new, $stderr + end - ActiveRecord::Tasks::DatabaseTasks.create @configuration - end + def teardown + $stdout, $stderr = @original_stdout, @original_stderr + end - def test_grant_privileges_for_normal_user - assert_permissions_granted_for("pat") - ActiveRecord::Tasks::DatabaseTasks.create @configuration - end + def test_root_password_is_requested + assert_permissions_granted_for("pat") + $stdin.expects(:gets).returns("secret\n") - def test_do_not_grant_privileges_for_root_user - @configuration["username"] = "root" - @configuration["password"] = "" - ActiveRecord::Tasks::DatabaseTasks.create @configuration - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end - def test_connection_established_as_normal_user - assert_permissions_granted_for("pat") - ActiveRecord::Base.expects(:establish_connection).returns do + def test_connection_established_as_root + assert_permissions_granted_for("pat") ActiveRecord::Base.expects(:establish_connection).with( "adapter" => "mysql2", - "database" => "my-app-db", - "username" => "pat", + "database" => nil, + "username" => "root", "password" => "secret" ) - raise @error + ActiveRecord::Tasks::DatabaseTasks.create @configuration end - ActiveRecord::Tasks::DatabaseTasks.create @configuration - end + def test_database_created_by_root + assert_permissions_granted_for("pat") + @connection.expects(:create_database). + with("my-app-db", {}) - def test_sends_output_to_stderr_when_other_errors - @error.stubs(:errno).returns(42) + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end - $stderr.expects(:puts).at_least_once.returns(nil) + def test_grant_privileges_for_normal_user + assert_permissions_granted_for("pat") + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end - ActiveRecord::Tasks::DatabaseTasks.create @configuration - end + def test_do_not_grant_privileges_for_root_user + @configuration["username"] = "root" + @configuration["password"] = "" + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end - private + def test_connection_established_as_normal_user + assert_permissions_granted_for("pat") + ActiveRecord::Base.expects(:establish_connection).returns do + ActiveRecord::Base.expects(:establish_connection).with( + "adapter" => "mysql2", + "database" => "my-app-db", + "username" => "pat", + "password" => "secret" + ) - def assert_permissions_granted_for(db_user) - db_name = @configuration["database"] - db_password = @configuration["password"] - @connection.expects(:execute).with("GRANT ALL PRIVILEGES ON #{db_name}.* TO '#{db_user}'@'localhost' IDENTIFIED BY '#{db_password}' WITH GRANT OPTION;") - end - end + raise @error + end - class MySQLDBDropTest < ActiveRecord::TestCase - def setup - @connection = stub(drop_database: true) - @configuration = { - "adapter" => "mysql2", - "database" => "my-app-db" - } + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end - ActiveRecord::Base.stubs(:connection).returns(@connection) - ActiveRecord::Base.stubs(:establish_connection).returns(true) + def test_sends_output_to_stderr_when_other_errors + @error.stubs(:errno).returns(42) - $stdout, @original_stdout = StringIO.new, $stdout - $stderr, @original_stderr = StringIO.new, $stderr - end + $stderr.expects(:puts).at_least_once.returns(nil) - def teardown - $stdout, $stderr = @original_stdout, @original_stderr - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end - def test_establishes_connection_to_mysql_database - ActiveRecord::Base.expects(:establish_connection).with @configuration + private - ActiveRecord::Tasks::DatabaseTasks.drop @configuration + def assert_permissions_granted_for(db_user) + db_name = @configuration["database"] + db_password = @configuration["password"] + @connection.expects(:execute).with("GRANT ALL PRIVILEGES ON #{db_name}.* TO '#{db_user}'@'localhost' IDENTIFIED BY '#{db_password}' WITH GRANT OPTION;") + end end - def test_drops_database - @connection.expects(:drop_database).with("my-app-db") + class MySQLDBDropTest < ActiveRecord::TestCase + def setup + @connection = stub(drop_database: true) + @configuration = { + "adapter" => "mysql2", + "database" => "my-app-db" + } - ActiveRecord::Tasks::DatabaseTasks.drop @configuration - end + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) - def test_when_database_dropped_successfully_outputs_info_to_stdout - ActiveRecord::Tasks::DatabaseTasks.drop @configuration + $stdout, @original_stdout = StringIO.new, $stdout + $stderr, @original_stderr = StringIO.new, $stderr + end - assert_equal $stdout.string, "Dropped database 'my-app-db'\n" - end - end + def teardown + $stdout, $stderr = @original_stdout, @original_stderr + end - class MySQLPurgeTest < ActiveRecord::TestCase - def setup - @connection = stub(recreate_database: true) - @configuration = { - "adapter" => "mysql2", - "database" => "test-db" - } + def test_establishes_connection_to_mysql_database + ActiveRecord::Base.expects(:establish_connection).with @configuration - ActiveRecord::Base.stubs(:connection).returns(@connection) - ActiveRecord::Base.stubs(:establish_connection).returns(true) - end + ActiveRecord::Tasks::DatabaseTasks.drop @configuration + end - def test_establishes_connection_to_the_appropriate_database - ActiveRecord::Base.expects(:establish_connection).with(@configuration) + def test_drops_database + @connection.expects(:drop_database).with("my-app-db") - ActiveRecord::Tasks::DatabaseTasks.purge @configuration - end + ActiveRecord::Tasks::DatabaseTasks.drop @configuration + end - def test_recreates_database_with_no_default_options - @connection.expects(:recreate_database). - with("test-db", {}) + def test_when_database_dropped_successfully_outputs_info_to_stdout + ActiveRecord::Tasks::DatabaseTasks.drop @configuration - ActiveRecord::Tasks::DatabaseTasks.purge @configuration + assert_equal $stdout.string, "Dropped database 'my-app-db'\n" + end end - def test_recreates_database_with_the_given_options - @connection.expects(:recreate_database). - with("test-db", charset: "latin", collation: "latin1_swedish_ci") + class MySQLPurgeTest < ActiveRecord::TestCase + def setup + @connection = stub(recreate_database: true) + @configuration = { + "adapter" => "mysql2", + "database" => "test-db" + } - ActiveRecord::Tasks::DatabaseTasks.purge @configuration.merge( - "encoding" => "latin", "collation" => "latin1_swedish_ci") - end - end + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + end - class MysqlDBCharsetTest < ActiveRecord::TestCase - def setup - @connection = stub(create_database: true) - @configuration = { - "adapter" => "mysql2", - "database" => "my-app-db" - } + def test_establishes_connection_to_the_appropriate_database + ActiveRecord::Base.expects(:establish_connection).with(@configuration) - ActiveRecord::Base.stubs(:connection).returns(@connection) - ActiveRecord::Base.stubs(:establish_connection).returns(true) - end + ActiveRecord::Tasks::DatabaseTasks.purge @configuration + end - def test_db_retrieves_charset - @connection.expects(:charset) - ActiveRecord::Tasks::DatabaseTasks.charset @configuration - end - end + def test_recreates_database_with_no_default_options + @connection.expects(:recreate_database). + with("test-db", {}) - class MysqlDBCollationTest < ActiveRecord::TestCase - def setup - @connection = stub(create_database: true) - @configuration = { - "adapter" => "mysql2", - "database" => "my-app-db" - } + ActiveRecord::Tasks::DatabaseTasks.purge @configuration + end - ActiveRecord::Base.stubs(:connection).returns(@connection) - ActiveRecord::Base.stubs(:establish_connection).returns(true) - end + def test_recreates_database_with_the_given_options + @connection.expects(:recreate_database). + with("test-db", charset: "latin", collation: "latin1_swedish_ci") - def test_db_retrieves_collation - @connection.expects(:collation) - ActiveRecord::Tasks::DatabaseTasks.collation @configuration + ActiveRecord::Tasks::DatabaseTasks.purge @configuration.merge( + "encoding" => "latin", "collation" => "latin1_swedish_ci") + end end - end - class MySQLStructureDumpTest < ActiveRecord::TestCase - def setup - @configuration = { - "adapter" => "mysql2", - "database" => "test-db" - } + class MysqlDBCharsetTest < ActiveRecord::TestCase + def setup + @connection = stub(create_database: true) + @configuration = { + "adapter" => "mysql2", + "database" => "my-app-db" + } + + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + end + + def test_db_retrieves_charset + @connection.expects(:charset) + ActiveRecord::Tasks::DatabaseTasks.charset @configuration + end end - def test_structure_dump - filename = "awesome-file.sql" - Kernel.expects(:system).with("mysqldump", "--result-file", filename, "--no-data", "--routines", "--skip-comments", "test-db").returns(true) + class MysqlDBCollationTest < ActiveRecord::TestCase + def setup + @connection = stub(create_database: true) + @configuration = { + "adapter" => "mysql2", + "database" => "my-app-db" + } + + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + end - ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, filename) + def test_db_retrieves_collation + @connection.expects(:collation) + ActiveRecord::Tasks::DatabaseTasks.collation @configuration + end end - def test_warn_when_external_structure_dump_command_execution_fails - filename = "awesome-file.sql" - Kernel.expects(:system) - .with("mysqldump", "--result-file", filename, "--no-data", "--routines", "--skip-comments", "test-db") - .returns(false) + class MySQLStructureDumpTest < ActiveRecord::TestCase + def setup + @configuration = { + "adapter" => "mysql2", + "database" => "test-db" + } + end + + def test_structure_dump + filename = "awesome-file.sql" + Kernel.expects(:system).with("mysqldump", "--result-file", filename, "--no-data", "--routines", "--skip-comments", "test-db").returns(true) - e = assert_raise(RuntimeError) { ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, filename) - } - assert_match(/^failed to execute: `mysqldump`$/, e.message) - end + end - def test_structure_dump_with_port_number - filename = "awesome-file.sql" - Kernel.expects(:system).with("mysqldump", "--port=10000", "--result-file", filename, "--no-data", "--routines", "--skip-comments", "test-db").returns(true) + def test_warn_when_external_structure_dump_command_execution_fails + filename = "awesome-file.sql" + Kernel.expects(:system) + .with("mysqldump", "--result-file", filename, "--no-data", "--routines", "--skip-comments", "test-db") + .returns(false) - ActiveRecord::Tasks::DatabaseTasks.structure_dump( - @configuration.merge("port" => 10000), - filename) - end + e = assert_raise(RuntimeError) { + ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, filename) + } + assert_match(/^failed to execute: `mysqldump`$/, e.message) + end - def test_structure_dump_with_ssl - filename = "awesome-file.sql" - Kernel.expects(:system).with("mysqldump", "--ssl-ca=ca.crt", "--result-file", filename, "--no-data", "--routines", "--skip-comments", "test-db").returns(true) + def test_structure_dump_with_port_number + filename = "awesome-file.sql" + Kernel.expects(:system).with("mysqldump", "--port=10000", "--result-file", filename, "--no-data", "--routines", "--skip-comments", "test-db").returns(true) - ActiveRecord::Tasks::DatabaseTasks.structure_dump( - @configuration.merge("sslca" => "ca.crt"), - filename) - end - end + ActiveRecord::Tasks::DatabaseTasks.structure_dump( + @configuration.merge("port" => 10000), + filename) + end + + def test_structure_dump_with_ssl + filename = "awesome-file.sql" + Kernel.expects(:system).with("mysqldump", "--ssl-ca=ca.crt", "--result-file", filename, "--no-data", "--routines", "--skip-comments", "test-db").returns(true) - class MySQLStructureLoadTest < ActiveRecord::TestCase - def setup - @configuration = { - "adapter" => "mysql2", - "database" => "test-db" - } + ActiveRecord::Tasks::DatabaseTasks.structure_dump( + @configuration.merge("sslca" => "ca.crt"), + filename) + end end - def test_structure_load - filename = "awesome-file.sql" - Kernel.expects(:system).with("mysql", "--execute", %{SET FOREIGN_KEY_CHECKS = 0; SOURCE #{filename}; SET FOREIGN_KEY_CHECKS = 1}, "--database", "test-db") - .returns(true) + class MySQLStructureLoadTest < ActiveRecord::TestCase + def setup + @configuration = { + "adapter" => "mysql2", + "database" => "test-db" + } + end + + def test_structure_load + filename = "awesome-file.sql" + Kernel.expects(:system).with("mysql", "--execute", %{SET FOREIGN_KEY_CHECKS = 0; SOURCE #{filename}; SET FOREIGN_KEY_CHECKS = 1}, "--database", "test-db") + .returns(true) - ActiveRecord::Tasks::DatabaseTasks.structure_load(@configuration, filename) + ActiveRecord::Tasks::DatabaseTasks.structure_load(@configuration, filename) + end end end end -end diff --git a/activerecord/test/cases/tasks/postgresql_rake_test.rb b/activerecord/test/cases/tasks/postgresql_rake_test.rb index fdfe4e979f..b8c8ec88f0 100644 --- a/activerecord/test/cases/tasks/postgresql_rake_test.rb +++ b/activerecord/test/cases/tasks/postgresql_rake_test.rb @@ -2,303 +2,303 @@ require "cases/helper" require "active_record/tasks/database_tasks" if current_adapter?(:PostgreSQLAdapter) -module ActiveRecord - class PostgreSQLDBCreateTest < ActiveRecord::TestCase - def setup - @connection = stub(create_database: true) - @configuration = { - "adapter" => "postgresql", - "database" => "my-app-db" - } - - ActiveRecord::Base.stubs(:connection).returns(@connection) - ActiveRecord::Base.stubs(:establish_connection).returns(true) - - $stdout, @original_stdout = StringIO.new, $stdout - $stderr, @original_stderr = StringIO.new, $stderr - end + module ActiveRecord + class PostgreSQLDBCreateTest < ActiveRecord::TestCase + def setup + @connection = stub(create_database: true) + @configuration = { + "adapter" => "postgresql", + "database" => "my-app-db" + } + + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + + $stdout, @original_stdout = StringIO.new, $stdout + $stderr, @original_stderr = StringIO.new, $stderr + end - def teardown - $stdout, $stderr = @original_stdout, @original_stderr - end + def teardown + $stdout, $stderr = @original_stdout, @original_stderr + end - def test_establishes_connection_to_postgresql_database - ActiveRecord::Base.expects(:establish_connection).with( - "adapter" => "postgresql", - "database" => "postgres", - "schema_search_path" => "public" - ) + def test_establishes_connection_to_postgresql_database + ActiveRecord::Base.expects(:establish_connection).with( + "adapter" => "postgresql", + "database" => "postgres", + "schema_search_path" => "public" + ) - ActiveRecord::Tasks::DatabaseTasks.create @configuration - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end - def test_creates_database_with_default_encoding - @connection.expects(:create_database). - with("my-app-db", @configuration.merge("encoding" => "utf8")) + def test_creates_database_with_default_encoding + @connection.expects(:create_database). + with("my-app-db", @configuration.merge("encoding" => "utf8")) - ActiveRecord::Tasks::DatabaseTasks.create @configuration - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end - def test_creates_database_with_given_encoding - @connection.expects(:create_database). - with("my-app-db", @configuration.merge("encoding" => "latin")) + def test_creates_database_with_given_encoding + @connection.expects(:create_database). + with("my-app-db", @configuration.merge("encoding" => "latin")) - ActiveRecord::Tasks::DatabaseTasks.create @configuration. - merge("encoding" => "latin") - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration. + merge("encoding" => "latin") + end - def test_creates_database_with_given_collation_and_ctype - @connection.expects(:create_database). - with("my-app-db", @configuration.merge("encoding" => "utf8", "collation" => "ja_JP.UTF8", "ctype" => "ja_JP.UTF8")) + def test_creates_database_with_given_collation_and_ctype + @connection.expects(:create_database). + with("my-app-db", @configuration.merge("encoding" => "utf8", "collation" => "ja_JP.UTF8", "ctype" => "ja_JP.UTF8")) - ActiveRecord::Tasks::DatabaseTasks.create @configuration. - merge("collation" => "ja_JP.UTF8", "ctype" => "ja_JP.UTF8") - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration. + merge("collation" => "ja_JP.UTF8", "ctype" => "ja_JP.UTF8") + end - def test_establishes_connection_to_new_database - ActiveRecord::Base.expects(:establish_connection).with(@configuration) + def test_establishes_connection_to_new_database + ActiveRecord::Base.expects(:establish_connection).with(@configuration) - ActiveRecord::Tasks::DatabaseTasks.create @configuration - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration + end - def test_db_create_with_error_prints_message - ActiveRecord::Base.stubs(:establish_connection).raises(Exception) + def test_db_create_with_error_prints_message + ActiveRecord::Base.stubs(:establish_connection).raises(Exception) - $stderr.stubs(:puts).returns(true) - $stderr.expects(:puts). - with("Couldn't create database for #{@configuration.inspect}") + $stderr.stubs(:puts).returns(true) + $stderr.expects(:puts). + with("Couldn't create database for #{@configuration.inspect}") - assert_raises(Exception) { ActiveRecord::Tasks::DatabaseTasks.create @configuration } - end + assert_raises(Exception) { ActiveRecord::Tasks::DatabaseTasks.create @configuration } + end - def test_when_database_created_successfully_outputs_info_to_stdout - ActiveRecord::Tasks::DatabaseTasks.create @configuration + def test_when_database_created_successfully_outputs_info_to_stdout + ActiveRecord::Tasks::DatabaseTasks.create @configuration - assert_equal $stdout.string, "Created database 'my-app-db'\n" - end + assert_equal $stdout.string, "Created database 'my-app-db'\n" + end - def test_create_when_database_exists_outputs_info_to_stderr - ActiveRecord::Base.connection.stubs(:create_database).raises( - ActiveRecord::Tasks::DatabaseAlreadyExists - ) + def test_create_when_database_exists_outputs_info_to_stderr + ActiveRecord::Base.connection.stubs(:create_database).raises( + ActiveRecord::Tasks::DatabaseAlreadyExists + ) - ActiveRecord::Tasks::DatabaseTasks.create @configuration + ActiveRecord::Tasks::DatabaseTasks.create @configuration - assert_equal $stderr.string, "Database 'my-app-db' already exists\n" + assert_equal $stderr.string, "Database 'my-app-db' already exists\n" + end end - end - class PostgreSQLDBDropTest < ActiveRecord::TestCase - def setup - @connection = stub(drop_database: true) - @configuration = { - "adapter" => "postgresql", - "database" => "my-app-db" - } + class PostgreSQLDBDropTest < ActiveRecord::TestCase + def setup + @connection = stub(drop_database: true) + @configuration = { + "adapter" => "postgresql", + "database" => "my-app-db" + } - ActiveRecord::Base.stubs(:connection).returns(@connection) - ActiveRecord::Base.stubs(:establish_connection).returns(true) + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) - $stdout, @original_stdout = StringIO.new, $stdout - $stderr, @original_stderr = StringIO.new, $stderr - end + $stdout, @original_stdout = StringIO.new, $stdout + $stderr, @original_stderr = StringIO.new, $stderr + end - def teardown - $stdout, $stderr = @original_stdout, @original_stderr - end + def teardown + $stdout, $stderr = @original_stdout, @original_stderr + end - def test_establishes_connection_to_postgresql_database - ActiveRecord::Base.expects(:establish_connection).with( - "adapter" => "postgresql", - "database" => "postgres", - "schema_search_path" => "public" - ) + def test_establishes_connection_to_postgresql_database + ActiveRecord::Base.expects(:establish_connection).with( + "adapter" => "postgresql", + "database" => "postgres", + "schema_search_path" => "public" + ) - ActiveRecord::Tasks::DatabaseTasks.drop @configuration - end + ActiveRecord::Tasks::DatabaseTasks.drop @configuration + end - def test_drops_database - @connection.expects(:drop_database).with("my-app-db") + def test_drops_database + @connection.expects(:drop_database).with("my-app-db") - ActiveRecord::Tasks::DatabaseTasks.drop @configuration - end + ActiveRecord::Tasks::DatabaseTasks.drop @configuration + end - def test_when_database_dropped_successfully_outputs_info_to_stdout - ActiveRecord::Tasks::DatabaseTasks.drop @configuration + def test_when_database_dropped_successfully_outputs_info_to_stdout + ActiveRecord::Tasks::DatabaseTasks.drop @configuration - assert_equal $stdout.string, "Dropped database 'my-app-db'\n" + assert_equal $stdout.string, "Dropped database 'my-app-db'\n" + end end - end - class PostgreSQLPurgeTest < ActiveRecord::TestCase - def setup - @connection = stub(create_database: true, drop_database: true) - @configuration = { - "adapter" => "postgresql", - "database" => "my-app-db" - } - - ActiveRecord::Base.stubs(:connection).returns(@connection) - ActiveRecord::Base.stubs(:clear_active_connections!).returns(true) - ActiveRecord::Base.stubs(:establish_connection).returns(true) - end + class PostgreSQLPurgeTest < ActiveRecord::TestCase + def setup + @connection = stub(create_database: true, drop_database: true) + @configuration = { + "adapter" => "postgresql", + "database" => "my-app-db" + } - def test_clears_active_connections - ActiveRecord::Base.expects(:clear_active_connections!) + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:clear_active_connections!).returns(true) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + end - ActiveRecord::Tasks::DatabaseTasks.purge @configuration - end + def test_clears_active_connections + ActiveRecord::Base.expects(:clear_active_connections!) + + ActiveRecord::Tasks::DatabaseTasks.purge @configuration + end - def test_establishes_connection_to_postgresql_database - ActiveRecord::Base.expects(:establish_connection).with( - "adapter" => "postgresql", - "database" => "postgres", - "schema_search_path" => "public" - ) + def test_establishes_connection_to_postgresql_database + ActiveRecord::Base.expects(:establish_connection).with( + "adapter" => "postgresql", + "database" => "postgres", + "schema_search_path" => "public" + ) - ActiveRecord::Tasks::DatabaseTasks.purge @configuration - end + ActiveRecord::Tasks::DatabaseTasks.purge @configuration + end - def test_drops_database - @connection.expects(:drop_database).with("my-app-db") + def test_drops_database + @connection.expects(:drop_database).with("my-app-db") - ActiveRecord::Tasks::DatabaseTasks.purge @configuration - end + ActiveRecord::Tasks::DatabaseTasks.purge @configuration + end - def test_creates_database - @connection.expects(:create_database). - with("my-app-db", @configuration.merge("encoding" => "utf8")) + def test_creates_database + @connection.expects(:create_database). + with("my-app-db", @configuration.merge("encoding" => "utf8")) - ActiveRecord::Tasks::DatabaseTasks.purge @configuration - end + ActiveRecord::Tasks::DatabaseTasks.purge @configuration + end - def test_establishes_connection - ActiveRecord::Base.expects(:establish_connection).with(@configuration) + def test_establishes_connection + ActiveRecord::Base.expects(:establish_connection).with(@configuration) - ActiveRecord::Tasks::DatabaseTasks.purge @configuration + ActiveRecord::Tasks::DatabaseTasks.purge @configuration + end end - end - class PostgreSQLDBCharsetTest < ActiveRecord::TestCase - def setup - @connection = stub(create_database: true) - @configuration = { - "adapter" => "postgresql", - "database" => "my-app-db" - } + class PostgreSQLDBCharsetTest < ActiveRecord::TestCase + def setup + @connection = stub(create_database: true) + @configuration = { + "adapter" => "postgresql", + "database" => "my-app-db" + } - ActiveRecord::Base.stubs(:connection).returns(@connection) - ActiveRecord::Base.stubs(:establish_connection).returns(true) - end + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + end - def test_db_retrieves_charset - @connection.expects(:encoding) - ActiveRecord::Tasks::DatabaseTasks.charset @configuration + def test_db_retrieves_charset + @connection.expects(:encoding) + ActiveRecord::Tasks::DatabaseTasks.charset @configuration + end end - end - class PostgreSQLDBCollationTest < ActiveRecord::TestCase - def setup - @connection = stub(create_database: true) - @configuration = { - "adapter" => "postgresql", - "database" => "my-app-db" - } + class PostgreSQLDBCollationTest < ActiveRecord::TestCase + def setup + @connection = stub(create_database: true) + @configuration = { + "adapter" => "postgresql", + "database" => "my-app-db" + } - ActiveRecord::Base.stubs(:connection).returns(@connection) - ActiveRecord::Base.stubs(:establish_connection).returns(true) - end + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + end - def test_db_retrieves_collation - @connection.expects(:collation) - ActiveRecord::Tasks::DatabaseTasks.collation @configuration + def test_db_retrieves_collation + @connection.expects(:collation) + ActiveRecord::Tasks::DatabaseTasks.collation @configuration + end end - end - class PostgreSQLStructureDumpTest < ActiveRecord::TestCase - def setup - @connection = stub(structure_dump: true) - @configuration = { - "adapter" => "postgresql", - "database" => "my-app-db" - } - @filename = "awesome-file.sql" - - ActiveRecord::Base.stubs(:connection).returns(@connection) - ActiveRecord::Base.stubs(:establish_connection).returns(true) - Kernel.stubs(:system) - File.stubs(:open) - end + class PostgreSQLStructureDumpTest < ActiveRecord::TestCase + def setup + @connection = stub(structure_dump: true) + @configuration = { + "adapter" => "postgresql", + "database" => "my-app-db" + } + @filename = "awesome-file.sql" - def test_structure_dump - Kernel.expects(:system).with("pg_dump", "-s", "-x", "-O", "-f", @filename, "my-app-db").returns(true) + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + Kernel.stubs(:system) + File.stubs(:open) + end - ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, @filename) - end + def test_structure_dump + Kernel.expects(:system).with("pg_dump", "-s", "-x", "-O", "-f", @filename, "my-app-db").returns(true) - def test_structure_dump_with_schema_search_path - @configuration["schema_search_path"] = "foo,bar" + ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, @filename) + end - Kernel.expects(:system).with("pg_dump", "-s", "-x", "-O", "-f", @filename, "--schema=foo", "--schema=bar", "my-app-db").returns(true) + def test_structure_dump_with_schema_search_path + @configuration["schema_search_path"] = "foo,bar" - ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, @filename) - end + Kernel.expects(:system).with("pg_dump", "-s", "-x", "-O", "-f", @filename, "--schema=foo", "--schema=bar", "my-app-db").returns(true) - def test_structure_dump_with_schema_search_path_and_dump_schemas_all - @configuration["schema_search_path"] = "foo,bar" + ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, @filename) + end - Kernel.expects(:system).with("pg_dump", "-s", "-x", "-O", "-f", @filename, "my-app-db").returns(true) + def test_structure_dump_with_schema_search_path_and_dump_schemas_all + @configuration["schema_search_path"] = "foo,bar" - with_dump_schemas(:all) do - ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, @filename) + Kernel.expects(:system).with("pg_dump", "-s", "-x", "-O", "-f", @filename, "my-app-db").returns(true) + + with_dump_schemas(:all) do + ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, @filename) + end end - end - def test_structure_dump_with_dump_schemas_string - Kernel.expects(:system).with("pg_dump", "-s", "-x", "-O", "-f", @filename, "--schema=foo", "--schema=bar", "my-app-db").returns(true) + def test_structure_dump_with_dump_schemas_string + Kernel.expects(:system).with("pg_dump", "-s", "-x", "-O", "-f", @filename, "--schema=foo", "--schema=bar", "my-app-db").returns(true) - with_dump_schemas("foo,bar") do - ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, @filename) + with_dump_schemas("foo,bar") do + ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, @filename) + end end - end - private + private - def with_dump_schemas(value, &block) - old_dump_schemas = ActiveRecord::Base.dump_schemas - ActiveRecord::Base.dump_schemas = value - yield - ensure - ActiveRecord::Base.dump_schemas = old_dump_schemas + def with_dump_schemas(value, &block) + old_dump_schemas = ActiveRecord::Base.dump_schemas + ActiveRecord::Base.dump_schemas = value + yield + ensure + ActiveRecord::Base.dump_schemas = old_dump_schemas + end end - end - class PostgreSQLStructureLoadTest < ActiveRecord::TestCase - def setup - @connection = stub - @configuration = { - "adapter" => "postgresql", - "database" => "my-app-db" - } - - ActiveRecord::Base.stubs(:connection).returns(@connection) - ActiveRecord::Base.stubs(:establish_connection).returns(true) - Kernel.stubs(:system) - end + class PostgreSQLStructureLoadTest < ActiveRecord::TestCase + def setup + @connection = stub + @configuration = { + "adapter" => "postgresql", + "database" => "my-app-db" + } - def test_structure_load - filename = "awesome-file.sql" - Kernel.expects(:system).with("psql", "-v", "ON_ERROR_STOP=1", "-q", "-f", filename, @configuration["database"]).returns(true) + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + Kernel.stubs(:system) + end - ActiveRecord::Tasks::DatabaseTasks.structure_load(@configuration, filename) - end + def test_structure_load + filename = "awesome-file.sql" + Kernel.expects(:system).with("psql", "-v", "ON_ERROR_STOP=1", "-q", "-f", filename, @configuration["database"]).returns(true) - def test_structure_load_accepts_path_with_spaces - filename = "awesome file.sql" - Kernel.expects(:system).with("psql", "-v", "ON_ERROR_STOP=1", "-q", "-f", filename, @configuration["database"]).returns(true) + ActiveRecord::Tasks::DatabaseTasks.structure_load(@configuration, filename) + end + + def test_structure_load_accepts_path_with_spaces + filename = "awesome file.sql" + Kernel.expects(:system).with("psql", "-v", "ON_ERROR_STOP=1", "-q", "-f", filename, @configuration["database"]).returns(true) - ActiveRecord::Tasks::DatabaseTasks.structure_load(@configuration, filename) + ActiveRecord::Tasks::DatabaseTasks.structure_load(@configuration, filename) + end end end end -end diff --git a/activerecord/test/cases/tasks/sqlite_rake_test.rb b/activerecord/test/cases/tasks/sqlite_rake_test.rb index 9aeeef1aee..141048bfe7 100644 --- a/activerecord/test/cases/tasks/sqlite_rake_test.rb +++ b/activerecord/test/cases/tasks/sqlite_rake_test.rb @@ -3,218 +3,218 @@ require "active_record/tasks/database_tasks" require "pathname" if current_adapter?(:SQLite3Adapter) -module ActiveRecord - class SqliteDBCreateTest < ActiveRecord::TestCase - def setup - @database = "db_create.sqlite3" - @connection = stub :connection - @configuration = { - "adapter" => "sqlite3", - "database" => @database - } - - File.stubs(:exist?).returns(false) - ActiveRecord::Base.stubs(:connection).returns(@connection) - ActiveRecord::Base.stubs(:establish_connection).returns(true) - - $stdout, @original_stdout = StringIO.new, $stdout - $stderr, @original_stderr = StringIO.new, $stderr - end + module ActiveRecord + class SqliteDBCreateTest < ActiveRecord::TestCase + def setup + @database = "db_create.sqlite3" + @connection = stub :connection + @configuration = { + "adapter" => "sqlite3", + "database" => @database + } + + File.stubs(:exist?).returns(false) + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + + $stdout, @original_stdout = StringIO.new, $stdout + $stderr, @original_stderr = StringIO.new, $stderr + end - def teardown - $stdout, $stderr = @original_stdout, @original_stderr - end + def teardown + $stdout, $stderr = @original_stdout, @original_stderr + end - def test_db_checks_database_exists - File.expects(:exist?).with(@database).returns(false) + def test_db_checks_database_exists + File.expects(:exist?).with(@database).returns(false) - ActiveRecord::Tasks::DatabaseTasks.create @configuration, "/rails/root" - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration, "/rails/root" + end - def test_when_db_created_successfully_outputs_info_to_stdout - ActiveRecord::Tasks::DatabaseTasks.create @configuration, "/rails/root" + def test_when_db_created_successfully_outputs_info_to_stdout + ActiveRecord::Tasks::DatabaseTasks.create @configuration, "/rails/root" - assert_equal $stdout.string, "Created database '#{@database}'\n" - end + assert_equal $stdout.string, "Created database '#{@database}'\n" + end - def test_db_create_when_file_exists - File.stubs(:exist?).returns(true) + def test_db_create_when_file_exists + File.stubs(:exist?).returns(true) - ActiveRecord::Tasks::DatabaseTasks.create @configuration, "/rails/root" + ActiveRecord::Tasks::DatabaseTasks.create @configuration, "/rails/root" - assert_equal $stderr.string, "Database '#{@database}' already exists\n" - end + assert_equal $stderr.string, "Database '#{@database}' already exists\n" + end - def test_db_create_with_file_does_nothing - File.stubs(:exist?).returns(true) - $stderr.stubs(:puts).returns(nil) + def test_db_create_with_file_does_nothing + File.stubs(:exist?).returns(true) + $stderr.stubs(:puts).returns(nil) - ActiveRecord::Base.expects(:establish_connection).never + ActiveRecord::Base.expects(:establish_connection).never - ActiveRecord::Tasks::DatabaseTasks.create @configuration, "/rails/root" - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration, "/rails/root" + end - def test_db_create_establishes_a_connection - ActiveRecord::Base.expects(:establish_connection).with(@configuration) + def test_db_create_establishes_a_connection + ActiveRecord::Base.expects(:establish_connection).with(@configuration) - ActiveRecord::Tasks::DatabaseTasks.create @configuration, "/rails/root" - end + ActiveRecord::Tasks::DatabaseTasks.create @configuration, "/rails/root" + end - def test_db_create_with_error_prints_message - ActiveRecord::Base.stubs(:establish_connection).raises(Exception) + def test_db_create_with_error_prints_message + ActiveRecord::Base.stubs(:establish_connection).raises(Exception) - $stderr.stubs(:puts).returns(true) - $stderr.expects(:puts). - with("Couldn't create database for #{@configuration.inspect}") + $stderr.stubs(:puts).returns(true) + $stderr.expects(:puts). + with("Couldn't create database for #{@configuration.inspect}") - assert_raises(Exception) { ActiveRecord::Tasks::DatabaseTasks.create @configuration, "/rails/root" } + assert_raises(Exception) { ActiveRecord::Tasks::DatabaseTasks.create @configuration, "/rails/root" } + end end - end - class SqliteDBDropTest < ActiveRecord::TestCase - def setup - @database = "db_create.sqlite3" - @path = stub(to_s: "/absolute/path", absolute?: true) - @configuration = { - "adapter" => "sqlite3", - "database" => @database - } - - Pathname.stubs(:new).returns(@path) - File.stubs(:join).returns("/former/relative/path") - FileUtils.stubs(:rm).returns(true) - - $stdout, @original_stdout = StringIO.new, $stdout - $stderr, @original_stderr = StringIO.new, $stderr - end + class SqliteDBDropTest < ActiveRecord::TestCase + def setup + @database = "db_create.sqlite3" + @path = stub(to_s: "/absolute/path", absolute?: true) + @configuration = { + "adapter" => "sqlite3", + "database" => @database + } - def teardown - $stdout, $stderr = @original_stdout, @original_stderr - end + Pathname.stubs(:new).returns(@path) + File.stubs(:join).returns("/former/relative/path") + FileUtils.stubs(:rm).returns(true) - def test_creates_path_from_database - Pathname.expects(:new).with(@database).returns(@path) + $stdout, @original_stdout = StringIO.new, $stdout + $stderr, @original_stderr = StringIO.new, $stderr + end - ActiveRecord::Tasks::DatabaseTasks.drop @configuration, "/rails/root" - end + def teardown + $stdout, $stderr = @original_stdout, @original_stderr + end - def test_removes_file_with_absolute_path - File.stubs(:exist?).returns(true) - @path.stubs(:absolute?).returns(true) + def test_creates_path_from_database + Pathname.expects(:new).with(@database).returns(@path) - FileUtils.expects(:rm).with("/absolute/path") + ActiveRecord::Tasks::DatabaseTasks.drop @configuration, "/rails/root" + end - ActiveRecord::Tasks::DatabaseTasks.drop @configuration, "/rails/root" - end + def test_removes_file_with_absolute_path + File.stubs(:exist?).returns(true) + @path.stubs(:absolute?).returns(true) - def test_generates_absolute_path_with_given_root - @path.stubs(:absolute?).returns(false) + FileUtils.expects(:rm).with("/absolute/path") - File.expects(:join).with("/rails/root", @path). - returns("/former/relative/path") + ActiveRecord::Tasks::DatabaseTasks.drop @configuration, "/rails/root" + end - ActiveRecord::Tasks::DatabaseTasks.drop @configuration, "/rails/root" - end + def test_generates_absolute_path_with_given_root + @path.stubs(:absolute?).returns(false) - def test_removes_file_with_relative_path - File.stubs(:exist?).returns(true) - @path.stubs(:absolute?).returns(false) + File.expects(:join).with("/rails/root", @path). + returns("/former/relative/path") - FileUtils.expects(:rm).with("/former/relative/path") + ActiveRecord::Tasks::DatabaseTasks.drop @configuration, "/rails/root" + end - ActiveRecord::Tasks::DatabaseTasks.drop @configuration, "/rails/root" - end + def test_removes_file_with_relative_path + File.stubs(:exist?).returns(true) + @path.stubs(:absolute?).returns(false) - def test_when_db_dropped_successfully_outputs_info_to_stdout - ActiveRecord::Tasks::DatabaseTasks.drop @configuration, "/rails/root" + FileUtils.expects(:rm).with("/former/relative/path") - assert_equal $stdout.string, "Dropped database '#{@database}'\n" - end - end + ActiveRecord::Tasks::DatabaseTasks.drop @configuration, "/rails/root" + end - class SqliteDBCharsetTest < ActiveRecord::TestCase - def setup - @database = "db_create.sqlite3" - @connection = stub :connection - @configuration = { - "adapter" => "sqlite3", - "database" => @database - } - - File.stubs(:exist?).returns(false) - ActiveRecord::Base.stubs(:connection).returns(@connection) - ActiveRecord::Base.stubs(:establish_connection).returns(true) - end + def test_when_db_dropped_successfully_outputs_info_to_stdout + ActiveRecord::Tasks::DatabaseTasks.drop @configuration, "/rails/root" - def test_db_retrieves_charset - @connection.expects(:encoding) - ActiveRecord::Tasks::DatabaseTasks.charset @configuration, "/rails/root" + assert_equal $stdout.string, "Dropped database '#{@database}'\n" + end end - end - class SqliteDBCollationTest < ActiveRecord::TestCase - def setup - @database = "db_create.sqlite3" - @connection = stub :connection - @configuration = { - "adapter" => "sqlite3", - "database" => @database - } - - File.stubs(:exist?).returns(false) - ActiveRecord::Base.stubs(:connection).returns(@connection) - ActiveRecord::Base.stubs(:establish_connection).returns(true) - end + class SqliteDBCharsetTest < ActiveRecord::TestCase + def setup + @database = "db_create.sqlite3" + @connection = stub :connection + @configuration = { + "adapter" => "sqlite3", + "database" => @database + } - def test_db_retrieves_collation - assert_raise NoMethodError do - ActiveRecord::Tasks::DatabaseTasks.collation @configuration, "/rails/root" + File.stubs(:exist?).returns(false) + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) end - end - end - class SqliteStructureDumpTest < ActiveRecord::TestCase - def setup - @database = "db_create.sqlite3" - @configuration = { - "adapter" => "sqlite3", - "database" => @database - } + def test_db_retrieves_charset + @connection.expects(:encoding) + ActiveRecord::Tasks::DatabaseTasks.charset @configuration, "/rails/root" + end end - def test_structure_dump - dbfile = @database - filename = "awesome-file.sql" + class SqliteDBCollationTest < ActiveRecord::TestCase + def setup + @database = "db_create.sqlite3" + @connection = stub :connection + @configuration = { + "adapter" => "sqlite3", + "database" => @database + } - ActiveRecord::Tasks::DatabaseTasks.structure_dump @configuration, filename, "/rails/root" - assert File.exist?(dbfile) - assert File.exist?(filename) - ensure - FileUtils.rm_f(filename) - FileUtils.rm_f(dbfile) + File.stubs(:exist?).returns(false) + ActiveRecord::Base.stubs(:connection).returns(@connection) + ActiveRecord::Base.stubs(:establish_connection).returns(true) + end + + def test_db_retrieves_collation + assert_raise NoMethodError do + ActiveRecord::Tasks::DatabaseTasks.collation @configuration, "/rails/root" + end + end end - end - class SqliteStructureLoadTest < ActiveRecord::TestCase - def setup - @database = "db_create.sqlite3" - @configuration = { - "adapter" => "sqlite3", - "database" => @database - } + class SqliteStructureDumpTest < ActiveRecord::TestCase + def setup + @database = "db_create.sqlite3" + @configuration = { + "adapter" => "sqlite3", + "database" => @database + } + end + + def test_structure_dump + dbfile = @database + filename = "awesome-file.sql" + + ActiveRecord::Tasks::DatabaseTasks.structure_dump @configuration, filename, "/rails/root" + assert File.exist?(dbfile) + assert File.exist?(filename) + ensure + FileUtils.rm_f(filename) + FileUtils.rm_f(dbfile) + end end - def test_structure_load - dbfile = @database - filename = "awesome-file.sql" + class SqliteStructureLoadTest < ActiveRecord::TestCase + def setup + @database = "db_create.sqlite3" + @configuration = { + "adapter" => "sqlite3", + "database" => @database + } + end + + def test_structure_load + dbfile = @database + filename = "awesome-file.sql" - open(filename, "w") { |f| f.puts("select datetime('now', 'localtime');") } - ActiveRecord::Tasks::DatabaseTasks.structure_load @configuration, filename, "/rails/root" - assert File.exist?(dbfile) - ensure - FileUtils.rm_f(filename) - FileUtils.rm_f(dbfile) + open(filename, "w") { |f| f.puts("select datetime('now', 'localtime');") } + ActiveRecord::Tasks::DatabaseTasks.structure_load @configuration, filename, "/rails/root" + assert File.exist?(dbfile) + ensure + FileUtils.rm_f(filename) + FileUtils.rm_f(dbfile) + end end end end -end diff --git a/activerecord/test/cases/time_precision_test.rb b/activerecord/test/cases/time_precision_test.rb index c7f6e9c698..4668dc1890 100644 --- a/activerecord/test/cases/time_precision_test.rb +++ b/activerecord/test/cases/time_precision_test.rb @@ -2,83 +2,83 @@ require "cases/helper" require "support/schema_dumping_helper" if subsecond_precision_supported? -class TimePrecisionTest < ActiveRecord::TestCase - include SchemaDumpingHelper - self.use_transactional_tests = false + class TimePrecisionTest < ActiveRecord::TestCase + include SchemaDumpingHelper + self.use_transactional_tests = false - class Foo < ActiveRecord::Base; end + class Foo < ActiveRecord::Base; end - setup do - @connection = ActiveRecord::Base.connection - Foo.reset_column_information - end - - teardown do - @connection.drop_table :foos, if_exists: true - end + setup do + @connection = ActiveRecord::Base.connection + Foo.reset_column_information + end - def test_time_data_type_with_precision - @connection.create_table(:foos, force: true) - @connection.add_column :foos, :start, :time, precision: 3 - @connection.add_column :foos, :finish, :time, precision: 6 - assert_equal 3, Foo.columns_hash["start"].precision - assert_equal 6, Foo.columns_hash["finish"].precision - end + teardown do + @connection.drop_table :foos, if_exists: true + end - def test_passing_precision_to_time_does_not_set_limit - @connection.create_table(:foos, force: true) do |t| - t.time :start, precision: 3 - t.time :finish, precision: 6 + def test_time_data_type_with_precision + @connection.create_table(:foos, force: true) + @connection.add_column :foos, :start, :time, precision: 3 + @connection.add_column :foos, :finish, :time, precision: 6 + assert_equal 3, Foo.columns_hash["start"].precision + assert_equal 6, Foo.columns_hash["finish"].precision end - assert_nil Foo.columns_hash["start"].limit - assert_nil Foo.columns_hash["finish"].limit - end - def test_invalid_time_precision_raises_error - assert_raises ActiveRecord::ActiveRecordError do + def test_passing_precision_to_time_does_not_set_limit @connection.create_table(:foos, force: true) do |t| - t.time :start, precision: 7 - t.time :finish, precision: 7 + t.time :start, precision: 3 + t.time :finish, precision: 6 end + assert_nil Foo.columns_hash["start"].limit + assert_nil Foo.columns_hash["finish"].limit end - end - def test_formatting_time_according_to_precision - @connection.create_table(:foos, force: true) do |t| - t.time :start, precision: 0 - t.time :finish, precision: 4 + def test_invalid_time_precision_raises_error + assert_raises ActiveRecord::ActiveRecordError do + @connection.create_table(:foos, force: true) do |t| + t.time :start, precision: 7 + t.time :finish, precision: 7 + end + end end - time = ::Time.utc(2000, 1, 1, 12, 30, 0, 999999) - Foo.create!(start: time, finish: time) - assert foo = Foo.find_by(start: time) - assert_equal 1, Foo.where(finish: time).count - assert_equal time.to_s, foo.start.to_s - assert_equal time.to_s, foo.finish.to_s - assert_equal 000000, foo.start.usec - assert_equal 999900, foo.finish.usec - end - def test_schema_dump_includes_time_precision - @connection.create_table(:foos, force: true) do |t| - t.time :start, precision: 4 - t.time :finish, precision: 6 + def test_formatting_time_according_to_precision + @connection.create_table(:foos, force: true) do |t| + t.time :start, precision: 0 + t.time :finish, precision: 4 + end + time = ::Time.utc(2000, 1, 1, 12, 30, 0, 999999) + Foo.create!(start: time, finish: time) + assert foo = Foo.find_by(start: time) + assert_equal 1, Foo.where(finish: time).count + assert_equal time.to_s, foo.start.to_s + assert_equal time.to_s, foo.finish.to_s + assert_equal 000000, foo.start.usec + assert_equal 999900, foo.finish.usec end - output = dump_table_schema("foos") - assert_match %r{t\.time\s+"start",\s+precision: 4$}, output - assert_match %r{t\.time\s+"finish",\s+precision: 6$}, output - end - if current_adapter?(:PostgreSQLAdapter) - def test_time_precision_with_zero_should_be_dumped + def test_schema_dump_includes_time_precision @connection.create_table(:foos, force: true) do |t| - t.time :start, precision: 0 - t.time :finish, precision: 0 + t.time :start, precision: 4 + t.time :finish, precision: 6 end output = dump_table_schema("foos") - assert_match %r{t\.time\s+"start",\s+precision: 0$}, output - assert_match %r{t\.time\s+"finish",\s+precision: 0$}, output + assert_match %r{t\.time\s+"start",\s+precision: 4$}, output + assert_match %r{t\.time\s+"finish",\s+precision: 6$}, output end - end -end + if current_adapter?(:PostgreSQLAdapter) + def test_time_precision_with_zero_should_be_dumped + @connection.create_table(:foos, force: true) do |t| + t.time :start, precision: 0 + t.time :finish, precision: 0 + end + output = dump_table_schema("foos") + assert_match %r{t\.time\s+"start",\s+precision: 0$}, output + assert_match %r{t\.time\s+"finish",\s+precision: 0$}, output + end + end + + end end diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb index c77cc1a4a6..519d9db601 100644 --- a/activerecord/test/cases/timestamp_test.rb +++ b/activerecord/test/cases/timestamp_test.rb @@ -74,12 +74,12 @@ class TimestampTest < ActiveRecord::TestCase end def test_touching_updates_timestamp_with_given_time - previously_updated_at = @developer.updated_at - new_time = Time.utc(2015, 2, 16, 0, 0, 0) - @developer.touch(time: new_time) + previously_updated_at = @developer.updated_at + new_time = Time.utc(2015, 2, 16, 0, 0, 0) + @developer.touch(time: new_time) - assert_not_equal previously_updated_at, @developer.updated_at - assert_equal new_time, @developer.updated_at + assert_not_equal previously_updated_at, @developer.updated_at + assert_equal new_time, @developer.updated_at end def test_touching_an_attribute_updates_timestamp @@ -106,9 +106,9 @@ class TimestampTest < ActiveRecord::TestCase end def test_touching_an_attribute_updates_timestamp_with_given_time - previously_updated_at = @developer.updated_at + previously_updated_at = @developer.updated_at previously_created_at = @developer.created_at - new_time = Time.utc(2015, 2, 16, 4, 54, 0) + new_time = Time.utc(2015, 2, 16, 4, 54, 0) @developer.touch(:created_at, time: new_time) assert_not_equal previously_created_at, @developer.created_at diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb index 6dcbc9559c..c8963ada63 100644 --- a/activerecord/test/cases/transactions_test.rb +++ b/activerecord/test/cases/transactions_test.rb @@ -687,7 +687,7 @@ class TransactionTest < ActiveRecord::TestCase def test_transaction_rollback_with_primarykeyless_tables connection = ActiveRecord::Base.connection connection.create_table(:transaction_without_primary_keys, force: true, id: false) do |t| - t.integer :thing_id + t.integer :thing_id end klass = Class.new(ActiveRecord::Base) do @@ -707,15 +707,15 @@ class TransactionTest < ActiveRecord::TestCase private - %w(validation save destroy).each do |filter| - define_method("add_cancelling_before_#{filter}_with_db_side_effect_to_topic") do |topic| - meta = class << topic; self; end - meta.send("define_method", "before_#{filter}_for_transaction") do - Book.create - throw(:abort) + %w(validation save destroy).each do |filter| + define_method("add_cancelling_before_#{filter}_with_db_side_effect_to_topic") do |topic| + meta = class << topic; self; end + meta.send("define_method", "before_#{filter}_for_transaction") do + Book.create + throw(:abort) + end end end - end end class TransactionsWithTransactionalFixturesTest < ActiveRecord::TestCase diff --git a/activerecord/test/cases/type/type_map_test.rb b/activerecord/test/cases/type/type_map_test.rb index 0be173b87d..2959d36466 100644 --- a/activerecord/test/cases/type/type_map_test.rb +++ b/activerecord/test/cases/type/type_map_test.rb @@ -174,4 +174,3 @@ module ActiveRecord end end end - diff --git a/activerecord/test/cases/view_test.rb b/activerecord/test/cases/view_test.rb index f3c2d2f30e..5f85c5ff8b 100644 --- a/activerecord/test/cases/view_test.rb +++ b/activerecord/test/cases/view_test.rb @@ -78,139 +78,139 @@ module ViewBehavior end if ActiveRecord::Base.connection.supports_views? -class ViewWithPrimaryKeyTest < ActiveRecord::TestCase - include ViewBehavior + class ViewWithPrimaryKeyTest < ActiveRecord::TestCase + include ViewBehavior - private - def create_view(name, query) - @connection.execute "CREATE VIEW #{name} AS #{query}" - end + private + def create_view(name, query) + @connection.execute "CREATE VIEW #{name} AS #{query}" + end - def drop_view(name) - @connection.execute "DROP VIEW #{name}" if @connection.view_exists? name + def drop_view(name) + @connection.execute "DROP VIEW #{name}" if @connection.view_exists? name + end end -end -class ViewWithoutPrimaryKeyTest < ActiveRecord::TestCase - include SchemaDumpingHelper - fixtures :books + class ViewWithoutPrimaryKeyTest < ActiveRecord::TestCase + include SchemaDumpingHelper + fixtures :books - class Paperback < ActiveRecord::Base; end + class Paperback < ActiveRecord::Base; end - setup do - @connection = ActiveRecord::Base.connection - @connection.execute <<-SQL + setup do + @connection = ActiveRecord::Base.connection + @connection.execute <<-SQL CREATE VIEW paperbacks AS SELECT name, status FROM books WHERE format = 'paperback' SQL - end + end - teardown do - @connection.execute "DROP VIEW paperbacks" if @connection.view_exists? "paperbacks" - end + teardown do + @connection.execute "DROP VIEW paperbacks" if @connection.view_exists? "paperbacks" + end - def test_reading - books = Paperback.all - assert_equal ["Agile Web Development with Rails"], books.map(&:name) - end + def test_reading + books = Paperback.all + assert_equal ["Agile Web Development with Rails"], books.map(&:name) + end - def test_views - assert_equal [Paperback.table_name], @connection.views - end + def test_views + assert_equal [Paperback.table_name], @connection.views + end - def test_view_exists - view_name = Paperback.table_name - assert @connection.view_exists?(view_name), "'#{view_name}' view should exist" - end + def test_view_exists + view_name = Paperback.table_name + assert @connection.view_exists?(view_name), "'#{view_name}' view should exist" + end - def test_table_exists - view_name = Paperback.table_name - # TODO: switch this assertion around once we changed #tables to not return views. - ActiveSupport::Deprecation.silence { assert @connection.table_exists?(view_name), "'#{view_name}' table should exist" } - end + def test_table_exists + view_name = Paperback.table_name + # TODO: switch this assertion around once we changed #tables to not return views. + ActiveSupport::Deprecation.silence { assert @connection.table_exists?(view_name), "'#{view_name}' table should exist" } + end - def test_column_definitions - assert_equal([["name", :string], - ["status", :integer]], Paperback.columns.map { |c| [c.name, c.type] }) - end + def test_column_definitions + assert_equal([["name", :string], + ["status", :integer]], Paperback.columns.map { |c| [c.name, c.type] }) + end - def test_attributes - assert_equal({"name" => "Agile Web Development with Rails", "status" => 2}, - Paperback.first.attributes) - end + def test_attributes + assert_equal({"name" => "Agile Web Development with Rails", "status" => 2}, + Paperback.first.attributes) + end - def test_does_not_have_a_primary_key - assert_nil Paperback.primary_key - end + def test_does_not_have_a_primary_key + assert_nil Paperback.primary_key + end - def test_does_not_dump_view_as_table - schema = dump_table_schema "paperbacks" - assert_no_match %r{create_table "paperbacks"}, schema + def test_does_not_dump_view_as_table + schema = dump_table_schema "paperbacks" + assert_no_match %r{create_table "paperbacks"}, schema + end end -end # sqlite dose not support CREATE, INSERT, and DELETE for VIEW -if current_adapter?(:Mysql2Adapter, :PostgreSQLAdapter) -class UpdateableViewTest < ActiveRecord::TestCase - self.use_transactional_tests = false - fixtures :books - - class PrintedBook < ActiveRecord::Base - self.primary_key = "id" - end - - setup do - @connection = ActiveRecord::Base.connection - @connection.execute <<-SQL + if current_adapter?(:Mysql2Adapter, :PostgreSQLAdapter) + class UpdateableViewTest < ActiveRecord::TestCase + self.use_transactional_tests = false + fixtures :books + + class PrintedBook < ActiveRecord::Base + self.primary_key = "id" + end + + setup do + @connection = ActiveRecord::Base.connection + @connection.execute <<-SQL CREATE VIEW printed_books AS SELECT id, name, status, format FROM books WHERE format = 'paperback' SQL - end - - teardown do - @connection.execute "DROP VIEW printed_books" if @connection.view_exists? "printed_books" - end - - def test_update_record - book = PrintedBook.first - book.name = "AWDwR" - book.save! - book.reload - assert_equal "AWDwR", book.name - end - - def test_insert_record - PrintedBook.create! name: "Rails in Action", status: 0, format: "paperback" - - new_book = PrintedBook.last - assert_equal "Rails in Action", new_book.name - end - - def test_update_record_to_fail_view_conditions - book = PrintedBook.first - book.format = "ebook" - book.save! - - assert_raises ActiveRecord::RecordNotFound do - book.reload + end + + teardown do + @connection.execute "DROP VIEW printed_books" if @connection.view_exists? "printed_books" + end + + def test_update_record + book = PrintedBook.first + book.name = "AWDwR" + book.save! + book.reload + assert_equal "AWDwR", book.name + end + + def test_insert_record + PrintedBook.create! name: "Rails in Action", status: 0, format: "paperback" + + new_book = PrintedBook.last + assert_equal "Rails in Action", new_book.name + end + + def test_update_record_to_fail_view_conditions + book = PrintedBook.first + book.format = "ebook" + book.save! + + assert_raises ActiveRecord::RecordNotFound do + book.reload + end + end end - end -end -end # end fo `if current_adapter?(:Mysql2Adapter, :PostgreSQLAdapter)` + end # end fo `if current_adapter?(:Mysql2Adapter, :PostgreSQLAdapter)` end # end fo `if ActiveRecord::Base.connection.supports_views?` if ActiveRecord::Base.connection.respond_to?(:supports_materialized_views?) && ActiveRecord::Base.connection.supports_materialized_views? -class MaterializedViewTest < ActiveRecord::PostgreSQLTestCase - include ViewBehavior + class MaterializedViewTest < ActiveRecord::PostgreSQLTestCase + include ViewBehavior - private - def create_view(name, query) - @connection.execute "CREATE MATERIALIZED VIEW #{name} AS #{query}" - end + private + def create_view(name, query) + @connection.execute "CREATE MATERIALIZED VIEW #{name} AS #{query}" + end - def drop_view(name) - @connection.execute "DROP MATERIALIZED VIEW #{name}" if @connection.view_exists? name + def drop_view(name) + @connection.execute "DROP MATERIALIZED VIEW #{name}" if @connection.view_exists? name + end end end -end diff --git a/activerecord/test/cases/yaml_serialization_test.rb b/activerecord/test/cases/yaml_serialization_test.rb index 6556771a9d..ade6e6095b 100644 --- a/activerecord/test/cases/yaml_serialization_test.rb +++ b/activerecord/test/cases/yaml_serialization_test.rb @@ -121,11 +121,11 @@ class YamlSerializationTest < ActiveRecord::TestCase private - def yaml_fixture(file_name) - path = File.expand_path( - "../../support/yaml_compatibility_fixtures/#{file_name}.yml", - __FILE__ - ) - File.read(path) - end + def yaml_fixture(file_name) + path = File.expand_path( + "../../support/yaml_compatibility_fixtures/#{file_name}.yml", + __FILE__ + ) + File.read(path) + end end diff --git a/activerecord/test/models/club.rb b/activerecord/test/models/club.rb index b2986a8c58..49d7b24a3b 100644 --- a/activerecord/test/models/club.rb +++ b/activerecord/test/models/club.rb @@ -10,9 +10,9 @@ class Club < ActiveRecord::Base private - def private_method - "I'm sorry sir, this is a *private* club, not a *pirate* club" - end + def private_method + "I'm sorry sir, this is a *private* club, not a *pirate* club" + end end class SuperClub < ActiveRecord::Base diff --git a/activerecord/test/models/company.rb b/activerecord/test/models/company.rb index 921cf10f30..025630087c 100644 --- a/activerecord/test/models/company.rb +++ b/activerecord/test/models/company.rb @@ -22,12 +22,12 @@ class Company < AbstractCompany private - def private_method - "I am Jack's innermost fears and aspirations" - end + def private_method + "I am Jack's innermost fears and aspirations" + end - class SpecialCo < Company - end + class SpecialCo < Company + end end module Namespaced @@ -218,13 +218,13 @@ class Account < ActiveRecord::Base protected - def check_empty_credit_limit - errors.add("credit_limit", :blank) if credit_limit.blank? - end + def check_empty_credit_limit + errors.add("credit_limit", :blank) if credit_limit.blank? + end private - def private_method - "Sir, yes sir!" - end + def private_method + "Sir, yes sir!" + end end diff --git a/activerecord/test/models/company_in_module.rb b/activerecord/test/models/company_in_module.rb index e035a80ab8..682f99e365 100644 --- a/activerecord/test/models/company_in_module.rb +++ b/activerecord/test/models/company_in_module.rb @@ -90,9 +90,9 @@ module MyApplication protected - def check_empty_credit_limit - errors.add("credit_card", :blank) if credit_card.blank? - end + def check_empty_credit_limit + errors.add("credit_card", :blank) if credit_card.blank? + end end end end diff --git a/activerecord/test/models/engine.rb b/activerecord/test/models/engine.rb index 50c6717037..eada171f6a 100644 --- a/activerecord/test/models/engine.rb +++ b/activerecord/test/models/engine.rb @@ -1,4 +1,3 @@ class Engine < ActiveRecord::Base belongs_to :my_car, class_name: "Car", foreign_key: "car_id", counter_cache: :engines_count end - diff --git a/activerecord/test/models/eye.rb b/activerecord/test/models/eye.rb index dc8ae2b3f6..ab3b3eacf3 100644 --- a/activerecord/test/models/eye.rb +++ b/activerecord/test/models/eye.rb @@ -15,7 +15,7 @@ class Eye < ActiveRecord::Base after_create :trace_after_create2 after_update :trace_after_update2 after_save :trace_after_save2 - + def trace_after_create (@after_create_callbacks_stack ||= []) << !iris.persisted? end diff --git a/activerecord/test/models/mentor.rb b/activerecord/test/models/mentor.rb index 11f1e4bff8..66504b4e91 100644 --- a/activerecord/test/models/mentor.rb +++ b/activerecord/test/models/mentor.rb @@ -1,3 +1,3 @@ class Mentor < ActiveRecord::Base has_many :developers -end \ No newline at end of file +end diff --git a/activerecord/test/models/person.rb b/activerecord/test/models/person.rb index ea215eeb81..eb117f92e1 100644 --- a/activerecord/test/models/person.rb +++ b/activerecord/test/models/person.rb @@ -96,13 +96,13 @@ class RichPerson < ActiveRecord::Base private - def run_before_create - self.first_name = first_name.to_s + "run_before_create" - end + def run_before_create + self.first_name = first_name.to_s + "run_before_create" + end - def run_before_validation - self.first_name = first_name.to_s + "run_before_validation" - end + def run_before_validation + self.first_name = first_name.to_s + "run_before_validation" + end end class NestedPerson < ActiveRecord::Base diff --git a/activerecord/test/models/vehicle.rb b/activerecord/test/models/vehicle.rb index ef26170f1f..855bc4e325 100644 --- a/activerecord/test/models/vehicle.rb +++ b/activerecord/test/models/vehicle.rb @@ -4,4 +4,4 @@ class Vehicle < ActiveRecord::Base end class Bus < Vehicle -end \ No newline at end of file +end diff --git a/activesupport/lib/active_support/cache/mem_cache_store.rb b/activesupport/lib/active_support/cache/mem_cache_store.rb index e8b56676cb..e51c6b2f10 100644 --- a/activesupport/lib/active_support/cache/mem_cache_store.rb +++ b/activesupport/lib/active_support/cache/mem_cache_store.rb @@ -27,23 +27,23 @@ module ActiveSupport # Provide support for raw values in the local cache strategy. module LocalCacheWithRaw # :nodoc: protected - def read_entry(key, options) - entry = super - if options[:raw] && local_cache && entry - entry = deserialize_entry(entry.value) + def read_entry(key, options) + entry = super + if options[:raw] && local_cache && entry + entry = deserialize_entry(entry.value) + end + entry end - entry - end - def write_entry(key, entry, options) # :nodoc: - if options[:raw] && local_cache - raw_entry = Entry.new(entry.value.to_s) - raw_entry.expires_at = entry.expires_at - super(key, raw_entry, options) - else - super + def write_entry(key, entry, options) # :nodoc: + if options[:raw] && local_cache + raw_entry = Entry.new(entry.value.to_s) + raw_entry.expires_at = entry.expires_at + super(key, raw_entry, options) + else + super + end end - end end prepend Strategy::LocalCache diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb index 985f432c7b..a450b0e6d4 100644 --- a/activesupport/lib/active_support/callbacks.rb +++ b/activesupport/lib/active_support/callbacks.rb @@ -92,705 +92,705 @@ module ActiveSupport private - def __run_callbacks__(callbacks, &block) - if callbacks.empty? - yield if block_given? - else - runner = callbacks.compile - e = Filters::Environment.new(self, false, nil, block) - runner.call(e).value + def __run_callbacks__(callbacks, &block) + if callbacks.empty? + yield if block_given? + else + runner = callbacks.compile + e = Filters::Environment.new(self, false, nil, block) + runner.call(e).value + end end - end # A hook invoked every time a before callback is halted. # This can be overridden in ActiveSupport::Callbacks implementors in order # to provide better debugging/logging. - def halted_callback_hook(filter) - end - - module Conditionals # :nodoc: - class Value - def initialize(&block) - @block = block - end - def call(target, value); @block.call(value); end + def halted_callback_hook(filter) end - end - - module Filters - Environment = Struct.new(:target, :halted, :value, :run_block) - class End - def call(env) - block = env.run_block - env.value = !env.halted && (!block || block.call) - env + module Conditionals # :nodoc: + class Value + def initialize(&block) + @block = block + end + def call(target, value); @block.call(value); end end end - ENDING = End.new - class Before - def self.build(callback_sequence, user_callback, user_conditions, chain_config, filter) - halted_lambda = chain_config[:terminator] + module Filters + Environment = Struct.new(:target, :halted, :value, :run_block) - if user_conditions.any? - halting_and_conditional(callback_sequence, user_callback, user_conditions, halted_lambda, filter) - else - halting(callback_sequence, user_callback, halted_lambda, filter) + class End + def call(env) + block = env.run_block + env.value = !env.halted && (!block || block.call) + env end end + ENDING = End.new - def self.halting_and_conditional(callback_sequence, user_callback, user_conditions, halted_lambda, filter) - callback_sequence.before do |env| - target = env.target - value = env.value - halted = env.halted + class Before + def self.build(callback_sequence, user_callback, user_conditions, chain_config, filter) + halted_lambda = chain_config[:terminator] - if !halted && user_conditions.all? { |c| c.call(target, value) } - result_lambda = -> { user_callback.call target, value } - env.halted = halted_lambda.call(target, result_lambda) - if env.halted - target.send :halted_callback_hook, filter - end + if user_conditions.any? + halting_and_conditional(callback_sequence, user_callback, user_conditions, halted_lambda, filter) + else + halting(callback_sequence, user_callback, halted_lambda, filter) end + end - env + def self.halting_and_conditional(callback_sequence, user_callback, user_conditions, halted_lambda, filter) + callback_sequence.before do |env| + target = env.target + value = env.value + halted = env.halted + + if !halted && user_conditions.all? { |c| c.call(target, value) } + result_lambda = -> { user_callback.call target, value } + env.halted = halted_lambda.call(target, result_lambda) + if env.halted + target.send :halted_callback_hook, filter + end + end + + env + end end - end - private_class_method :halting_and_conditional + private_class_method :halting_and_conditional - def self.halting(callback_sequence, user_callback, halted_lambda, filter) - callback_sequence.before do |env| - target = env.target - value = env.value - halted = env.halted + def self.halting(callback_sequence, user_callback, halted_lambda, filter) + callback_sequence.before do |env| + target = env.target + value = env.value + halted = env.halted - unless halted - result_lambda = -> { user_callback.call target, value } - env.halted = halted_lambda.call(target, result_lambda) + unless halted + result_lambda = -> { user_callback.call target, value } + env.halted = halted_lambda.call(target, result_lambda) - if env.halted - target.send :halted_callback_hook, filter + if env.halted + target.send :halted_callback_hook, filter + end end - end - env + env + end end + private_class_method :halting end - private_class_method :halting - end - class After - def self.build(callback_sequence, user_callback, user_conditions, chain_config) - if chain_config[:skip_after_callbacks_if_terminated] - if user_conditions.any? - halting_and_conditional(callback_sequence, user_callback, user_conditions) - else - halting(callback_sequence, user_callback) - end - else - if user_conditions.any? - conditional callback_sequence, user_callback, user_conditions + class After + def self.build(callback_sequence, user_callback, user_conditions, chain_config) + if chain_config[:skip_after_callbacks_if_terminated] + if user_conditions.any? + halting_and_conditional(callback_sequence, user_callback, user_conditions) + else + halting(callback_sequence, user_callback) + end else - simple callback_sequence, user_callback + if user_conditions.any? + conditional callback_sequence, user_callback, user_conditions + else + simple callback_sequence, user_callback + end end end - end - def self.halting_and_conditional(callback_sequence, user_callback, user_conditions) - callback_sequence.after do |env| - target = env.target - value = env.value - halted = env.halted + def self.halting_and_conditional(callback_sequence, user_callback, user_conditions) + callback_sequence.after do |env| + target = env.target + value = env.value + halted = env.halted - if !halted && user_conditions.all? { |c| c.call(target, value) } - user_callback.call target, value - end + if !halted && user_conditions.all? { |c| c.call(target, value) } + user_callback.call target, value + end - env + env + end end - end - private_class_method :halting_and_conditional + private_class_method :halting_and_conditional - def self.halting(callback_sequence, user_callback) - callback_sequence.after do |env| - unless env.halted - user_callback.call env.target, env.value - end + def self.halting(callback_sequence, user_callback) + callback_sequence.after do |env| + unless env.halted + user_callback.call env.target, env.value + end - env + env + end end - end - private_class_method :halting + private_class_method :halting - def self.conditional(callback_sequence, user_callback, user_conditions) - callback_sequence.after do |env| - target = env.target - value = env.value + def self.conditional(callback_sequence, user_callback, user_conditions) + callback_sequence.after do |env| + target = env.target + value = env.value - if user_conditions.all? { |c| c.call(target, value) } - user_callback.call target, value - end + if user_conditions.all? { |c| c.call(target, value) } + user_callback.call target, value + end - env + env + end end - end - private_class_method :conditional + private_class_method :conditional - def self.simple(callback_sequence, user_callback) - callback_sequence.after do |env| - user_callback.call env.target, env.value + def self.simple(callback_sequence, user_callback) + callback_sequence.after do |env| + user_callback.call env.target, env.value - env + env + end end + private_class_method :simple end - private_class_method :simple - end - class Around - def self.build(callback_sequence, user_callback, user_conditions, chain_config) - if user_conditions.any? - halting_and_conditional(callback_sequence, user_callback, user_conditions) - else - halting(callback_sequence, user_callback) + class Around + def self.build(callback_sequence, user_callback, user_conditions, chain_config) + if user_conditions.any? + halting_and_conditional(callback_sequence, user_callback, user_conditions) + else + halting(callback_sequence, user_callback) + end end - end - def self.halting_and_conditional(callback_sequence, user_callback, user_conditions) - callback_sequence.around do |env, &run| - target = env.target - value = env.value - halted = env.halted - - if !halted && user_conditions.all? { |c| c.call(target, value) } - user_callback.call(target, value) { - run.call.value - } - env - else - run.call + def self.halting_and_conditional(callback_sequence, user_callback, user_conditions) + callback_sequence.around do |env, &run| + target = env.target + value = env.value + halted = env.halted + + if !halted && user_conditions.all? { |c| c.call(target, value) } + user_callback.call(target, value) { + run.call.value + } + env + else + run.call + end end end - end - private_class_method :halting_and_conditional + private_class_method :halting_and_conditional - def self.halting(callback_sequence, user_callback) - callback_sequence.around do |env, &run| - target = env.target - value = env.value + def self.halting(callback_sequence, user_callback) + callback_sequence.around do |env, &run| + target = env.target + value = env.value - if env.halted - run.call - else - user_callback.call(target, value) { - run.call.value - } - env + if env.halted + run.call + else + user_callback.call(target, value) { + run.call.value + } + env + end end end + private_class_method :halting end - private_class_method :halting end - end - class Callback #:nodoc:# - def self.build(chain, filter, kind, options) - if filter.is_a?(String) - ActiveSupport::Deprecation.warn(<<-MSG.squish) + class Callback #:nodoc:# + def self.build(chain, filter, kind, options) + if filter.is_a?(String) + ActiveSupport::Deprecation.warn(<<-MSG.squish) Passing string to define callback is deprecated and will be removed in Rails 5.1 without replacement. MSG - end - - new chain.name, filter, kind, options, chain.config - end + end - attr_accessor :kind, :name - attr_reader :chain_config - - def initialize(name, filter, kind, options, chain_config) - @chain_config = chain_config - @name = name - @kind = kind - @filter = filter - @key = compute_identifier filter - @if = Array(options[:if]) - @unless = Array(options[:unless]) - end + new chain.name, filter, kind, options, chain.config + end - def filter; @key; end - def raw_filter; @filter; end + attr_accessor :kind, :name + attr_reader :chain_config + + def initialize(name, filter, kind, options, chain_config) + @chain_config = chain_config + @name = name + @kind = kind + @filter = filter + @key = compute_identifier filter + @if = Array(options[:if]) + @unless = Array(options[:unless]) + end - def merge_conditional_options(chain, if_option:, unless_option:) - options = { - if: @if.dup, - unless: @unless.dup - } + def filter; @key; end + def raw_filter; @filter; end - options[:if].concat Array(unless_option) - options[:unless].concat Array(if_option) + def merge_conditional_options(chain, if_option:, unless_option:) + options = { + if: @if.dup, + unless: @unless.dup + } - self.class.build chain, @filter, @kind, options - end + options[:if].concat Array(unless_option) + options[:unless].concat Array(if_option) - def matches?(_kind, _filter) - @kind == _kind && filter == _filter - end + self.class.build chain, @filter, @kind, options + end - def duplicates?(other) - case @filter - when Symbol, String - matches?(other.kind, other.filter) - else - false + def matches?(_kind, _filter) + @kind == _kind && filter == _filter end - end - # Wraps code with filter - def apply(callback_sequence) - user_conditions = conditions_lambdas - user_callback = make_lambda @filter - - case kind - when :before - Filters::Before.build(callback_sequence, user_callback, user_conditions, chain_config, @filter) - when :after - Filters::After.build(callback_sequence, user_callback, user_conditions, chain_config) - when :around - Filters::Around.build(callback_sequence, user_callback, user_conditions, chain_config) + def duplicates?(other) + case @filter + when Symbol, String + matches?(other.kind, other.filter) + else + false + end end - end - private + # Wraps code with filter + def apply(callback_sequence) + user_conditions = conditions_lambdas + user_callback = make_lambda @filter + + case kind + when :before + Filters::Before.build(callback_sequence, user_callback, user_conditions, chain_config, @filter) + when :after + Filters::After.build(callback_sequence, user_callback, user_conditions, chain_config) + when :around + Filters::Around.build(callback_sequence, user_callback, user_conditions, chain_config) + end + end - def invert_lambda(l) - lambda { |*args, &blk| !l.call(*args, &blk) } - end + private - # Filters support: - # - # Symbols:: A method to call. - # Strings:: Some content to evaluate. - # Procs:: A proc to call with the object. - # Objects:: An object with a before_foo method on it to call. - # - # All of these objects are converted into a lambda and handled - # the same after this point. - def make_lambda(filter) - case filter - when Symbol - lambda { |target, _, &blk| target.send filter, &blk } - when String - l = eval "lambda { |value| #{filter} }" - lambda { |target, value| target.instance_exec(value, &l) } - when Conditionals::Value then filter - when ::Proc - if filter.arity > 1 - return lambda { |target, _, &block| - raise ArgumentError unless block - target.instance_exec(target, block, &filter) - } + def invert_lambda(l) + lambda { |*args, &blk| !l.call(*args, &blk) } end - if filter.arity <= 0 - lambda { |target, _| target.instance_exec(&filter) } - else - lambda { |target, _| target.instance_exec(target, &filter) } - end - else - scopes = Array(chain_config[:scope]) - method_to_call = scopes.map{ |s| public_send(s) }.join("_") + # Filters support: + # + # Symbols:: A method to call. + # Strings:: Some content to evaluate. + # Procs:: A proc to call with the object. + # Objects:: An object with a before_foo method on it to call. + # + # All of these objects are converted into a lambda and handled + # the same after this point. + def make_lambda(filter) + case filter + when Symbol + lambda { |target, _, &blk| target.send filter, &blk } + when String + l = eval "lambda { |value| #{filter} }" + lambda { |target, value| target.instance_exec(value, &l) } + when Conditionals::Value then filter + when ::Proc + if filter.arity > 1 + return lambda { |target, _, &block| + raise ArgumentError unless block + target.instance_exec(target, block, &filter) + } + end - lambda { |target, _, &blk| - filter.public_send method_to_call, target, &blk - } - end - end + if filter.arity <= 0 + lambda { |target, _| target.instance_exec(&filter) } + else + lambda { |target, _| target.instance_exec(target, &filter) } + end + else + scopes = Array(chain_config[:scope]) + method_to_call = scopes.map{ |s| public_send(s) }.join("_") - def compute_identifier(filter) - case filter - when String, ::Proc - filter.object_id - else - filter - end - end + lambda { |target, _, &blk| + filter.public_send method_to_call, target, &blk + } + end + end + + def compute_identifier(filter) + case filter + when String, ::Proc + filter.object_id + else + filter + end + end - def conditions_lambdas - @if.map { |c| make_lambda c } + - @unless.map { |c| invert_lambda make_lambda c } + def conditions_lambdas + @if.map { |c| make_lambda c } + + @unless.map { |c| invert_lambda make_lambda c } + end end - end # Execute before and after filters in a sequence instead of # chaining them with nested lambda calls, see: # https://github.com/rails/rails/issues/18011 - class CallbackSequence - def initialize(&call) - @call = call - @before = [] - @after = [] - end + class CallbackSequence + def initialize(&call) + @call = call + @before = [] + @after = [] + end - def before(&before) - @before.unshift(before) - self - end + def before(&before) + @before.unshift(before) + self + end - def after(&after) - @after.push(after) - self - end + def after(&after) + @after.push(after) + self + end - def around(&around) - CallbackSequence.new do |arg| - around.call(arg) { - self.call(arg) - } + def around(&around) + CallbackSequence.new do |arg| + around.call(arg) { + self.call(arg) + } + end end - end - def call(arg) - @before.each { |b| b.call(arg) } - value = @call.call(arg) - @after.each { |a| a.call(arg) } - value + def call(arg) + @before.each { |b| b.call(arg) } + value = @call.call(arg) + @after.each { |a| a.call(arg) } + value + end end - end # An Array with a compile method. - class CallbackChain #:nodoc:# - include Enumerable - - attr_reader :name, :config - - def initialize(name, config) - @name = name - @config = { - scope: [:kind], - terminator: default_terminator - }.merge!(config) - @chain = [] - @callbacks = nil - @mutex = Mutex.new - end + class CallbackChain #:nodoc:# + include Enumerable + + attr_reader :name, :config + + def initialize(name, config) + @name = name + @config = { + scope: [:kind], + terminator: default_terminator + }.merge!(config) + @chain = [] + @callbacks = nil + @mutex = Mutex.new + end - def each(&block); @chain.each(&block); end - def index(o); @chain.index(o); end - def empty?; @chain.empty?; end + def each(&block); @chain.each(&block); end + def index(o); @chain.index(o); end + def empty?; @chain.empty?; end - def insert(index, o) - @callbacks = nil - @chain.insert(index, o) - end + def insert(index, o) + @callbacks = nil + @chain.insert(index, o) + end - def delete(o) - @callbacks = nil - @chain.delete(o) - end + def delete(o) + @callbacks = nil + @chain.delete(o) + end - def clear - @callbacks = nil - @chain.clear - self - end + def clear + @callbacks = nil + @chain.clear + self + end - def initialize_copy(other) - @callbacks = nil - @chain = other.chain.dup - @mutex = Mutex.new - end + def initialize_copy(other) + @callbacks = nil + @chain = other.chain.dup + @mutex = Mutex.new + end - def compile - @callbacks || @mutex.synchronize do - final_sequence = CallbackSequence.new { |env| Filters::ENDING.call(env) } - @callbacks ||= @chain.reverse.inject(final_sequence) do |callback_sequence, callback| - callback.apply callback_sequence + def compile + @callbacks || @mutex.synchronize do + final_sequence = CallbackSequence.new { |env| Filters::ENDING.call(env) } + @callbacks ||= @chain.reverse.inject(final_sequence) do |callback_sequence, callback| + callback.apply callback_sequence + end end end - end - def append(*callbacks) - callbacks.each { |c| append_one(c) } - end - - def prepend(*callbacks) - callbacks.each { |c| prepend_one(c) } - end + def append(*callbacks) + callbacks.each { |c| append_one(c) } + end - protected - def chain; @chain; end + def prepend(*callbacks) + callbacks.each { |c| prepend_one(c) } + end - private + protected + def chain; @chain; end - def append_one(callback) - @callbacks = nil - remove_duplicates(callback) - @chain.push(callback) - end + private - def prepend_one(callback) - @callbacks = nil - remove_duplicates(callback) - @chain.unshift(callback) - end + def append_one(callback) + @callbacks = nil + remove_duplicates(callback) + @chain.push(callback) + end - def remove_duplicates(callback) - @callbacks = nil - @chain.delete_if { |c| callback.duplicates?(c) } - end + def prepend_one(callback) + @callbacks = nil + remove_duplicates(callback) + @chain.unshift(callback) + end - def default_terminator - Proc.new do |target, result_lambda| - terminate = true - catch(:abort) do - result_lambda.call if result_lambda.is_a?(Proc) - terminate = false + def remove_duplicates(callback) + @callbacks = nil + @chain.delete_if { |c| callback.duplicates?(c) } end - terminate - end - end - end - module ClassMethods - def normalize_callback_params(filters, block) # :nodoc: - type = CALLBACK_FILTER_TYPES.include?(filters.first) ? filters.shift : :before - options = filters.extract_options! - filters.unshift(block) if block - [type, filters, options.dup] + def default_terminator + Proc.new do |target, result_lambda| + terminate = true + catch(:abort) do + result_lambda.call if result_lambda.is_a?(Proc) + terminate = false + end + terminate + end + end end - # This is used internally to append, prepend and skip callbacks to the - # CallbackChain. - def __update_callbacks(name) #:nodoc: - ([self] + ActiveSupport::DescendantsTracker.descendants(self)).reverse_each do |target| - chain = target.get_callbacks name - yield target, chain.dup + module ClassMethods + def normalize_callback_params(filters, block) # :nodoc: + type = CALLBACK_FILTER_TYPES.include?(filters.first) ? filters.shift : :before + options = filters.extract_options! + filters.unshift(block) if block + [type, filters, options.dup] end - end - # Install a callback for the given event. - # - # set_callback :save, :before, :before_method - # set_callback :save, :after, :after_method, if: :condition - # set_callback :save, :around, ->(r, block) { stuff; result = block.call; stuff } - # - # The second argument indicates whether the callback is to be run +:before+, - # +:after+, or +:around+ the event. If omitted, +:before+ is assumed. This - # means the first example above can also be written as: - # - # set_callback :save, :before_method - # - # The callback can be specified as a symbol naming an instance method; as a - # proc, lambda, or block; as a string to be instance evaluated(deprecated); or as an - # object that responds to a certain method determined by the :scope - # argument to +define_callbacks+. - # - # If a proc, lambda, or block is given, its body is evaluated in the context - # of the current object. It can also optionally accept the current object as - # an argument. - # - # Before and around callbacks are called in the order that they are set; - # after callbacks are called in the reverse order. - # - # Around callbacks can access the return value from the event, if it - # wasn't halted, from the +yield+ call. - # - # ===== Options - # - # * :if - A symbol, a string or an array of symbols and strings, - # each naming an instance method or a proc; the callback will be called - # only when they all return a true value. - # * :unless - A symbol, a string or an array of symbols and - # strings, each naming an instance method or a proc; the callback will - # be called only when they all return a false value. - # * :prepend - If +true+, the callback will be prepended to the - # existing chain rather than appended. - def set_callback(name, *filter_list, &block) - type, filters, options = normalize_callback_params(filter_list, block) - self_chain = get_callbacks name - mapped = filters.map do |filter| - Callback.build(self_chain, filter, type, options) + # This is used internally to append, prepend and skip callbacks to the + # CallbackChain. + def __update_callbacks(name) #:nodoc: + ([self] + ActiveSupport::DescendantsTracker.descendants(self)).reverse_each do |target| + chain = target.get_callbacks name + yield target, chain.dup + end end - __update_callbacks(name) do |target, chain| - options[:prepend] ? chain.prepend(*mapped) : chain.append(*mapped) - target.set_callbacks name, chain + # Install a callback for the given event. + # + # set_callback :save, :before, :before_method + # set_callback :save, :after, :after_method, if: :condition + # set_callback :save, :around, ->(r, block) { stuff; result = block.call; stuff } + # + # The second argument indicates whether the callback is to be run +:before+, + # +:after+, or +:around+ the event. If omitted, +:before+ is assumed. This + # means the first example above can also be written as: + # + # set_callback :save, :before_method + # + # The callback can be specified as a symbol naming an instance method; as a + # proc, lambda, or block; as a string to be instance evaluated(deprecated); or as an + # object that responds to a certain method determined by the :scope + # argument to +define_callbacks+. + # + # If a proc, lambda, or block is given, its body is evaluated in the context + # of the current object. It can also optionally accept the current object as + # an argument. + # + # Before and around callbacks are called in the order that they are set; + # after callbacks are called in the reverse order. + # + # Around callbacks can access the return value from the event, if it + # wasn't halted, from the +yield+ call. + # + # ===== Options + # + # * :if - A symbol, a string or an array of symbols and strings, + # each naming an instance method or a proc; the callback will be called + # only when they all return a true value. + # * :unless - A symbol, a string or an array of symbols and + # strings, each naming an instance method or a proc; the callback will + # be called only when they all return a false value. + # * :prepend - If +true+, the callback will be prepended to the + # existing chain rather than appended. + def set_callback(name, *filter_list, &block) + type, filters, options = normalize_callback_params(filter_list, block) + self_chain = get_callbacks name + mapped = filters.map do |filter| + Callback.build(self_chain, filter, type, options) + end + + __update_callbacks(name) do |target, chain| + options[:prepend] ? chain.prepend(*mapped) : chain.append(*mapped) + target.set_callbacks name, chain + end end - end - # Skip a previously set callback. Like +set_callback+, :if or - # :unless options may be passed in order to control when the - # callback is skipped. - # - # class Writer < Person - # skip_callback :validate, :before, :check_membership, if: -> { self.age > 18 } - # end - # - # An ArgumentError will be raised if the callback has not - # already been set (unless the :raise option is set to false). - def skip_callback(name, *filter_list, &block) - type, filters, options = normalize_callback_params(filter_list, block) - options[:raise] = true unless options.key?(:raise) - - __update_callbacks(name) do |target, chain| - filters.each do |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" - end + # Skip a previously set callback. Like +set_callback+, :if or + # :unless options may be passed in order to control when the + # callback is skipped. + # + # class Writer < Person + # skip_callback :validate, :before, :check_membership, if: -> { self.age > 18 } + # end + # + # An ArgumentError will be raised if the callback has not + # already been set (unless the :raise option is set to false). + def skip_callback(name, *filter_list, &block) + type, filters, options = normalize_callback_params(filter_list, block) + options[:raise] = true unless options.key?(:raise) + + __update_callbacks(name) do |target, chain| + filters.each do |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" + end - if callback && (options.key?(:if) || options.key?(:unless)) - new_callback = callback.merge_conditional_options(chain, if_option: options[:if], unless_option: options[:unless]) - chain.insert(chain.index(callback), new_callback) - end + if callback && (options.key?(:if) || options.key?(:unless)) + new_callback = callback.merge_conditional_options(chain, if_option: options[:if], unless_option: options[:unless]) + chain.insert(chain.index(callback), new_callback) + end - chain.delete(callback) + chain.delete(callback) + end + target.set_callbacks name, chain end - target.set_callbacks name, chain end - end - # Remove all set callbacks for the given event. - def reset_callbacks(name) - callbacks = get_callbacks name + # Remove all set callbacks for the given event. + def reset_callbacks(name) + callbacks = get_callbacks name - ActiveSupport::DescendantsTracker.descendants(self).each do |target| - chain = target.get_callbacks(name).dup - callbacks.each { |c| chain.delete(c) } - target.set_callbacks name, chain - end + ActiveSupport::DescendantsTracker.descendants(self).each do |target| + chain = target.get_callbacks(name).dup + callbacks.each { |c| chain.delete(c) } + target.set_callbacks name, chain + end - self.set_callbacks name, callbacks.dup.clear - end + self.set_callbacks name, callbacks.dup.clear + end - # Define sets of events in the object life cycle that support callbacks. - # - # define_callbacks :validate - # define_callbacks :initialize, :save, :destroy - # - # ===== Options - # - # * :terminator - Determines when a before filter will halt the - # callback chain, preventing following before and around callbacks from - # being called and the event from being triggered. - # This should be a lambda to be executed. - # The current object and the result lambda of the callback will be provided - # to the terminator lambda. - # - # define_callbacks :validate, terminator: ->(target, result_lambda) { result_lambda.call == false } - # - # In this example, if any before validate callbacks returns +false+, - # any successive before and around callback is not executed. - # - # The default terminator halts the chain when a callback throws +:abort+. - # - # * :skip_after_callbacks_if_terminated - Determines if after - # callbacks should be terminated by the :terminator option. By - # default after callbacks are executed no matter if callback chain was - # terminated or not. This option makes sense only when :terminator - # option is specified. - # - # * :scope - Indicates which methods should be executed when an - # object is used as a callback. - # - # class Audit - # def before(caller) - # puts 'Audit: before is called' - # end - # - # def before_save(caller) - # puts 'Audit: before_save is called' - # end - # end - # - # class Account - # include ActiveSupport::Callbacks - # - # define_callbacks :save - # set_callback :save, :before, Audit.new - # - # def save - # run_callbacks :save do - # puts 'save in main' - # end - # end - # end - # - # In the above case whenever you save an account the method - # Audit#before will be called. On the other hand - # - # define_callbacks :save, scope: [:kind, :name] - # - # would trigger Audit#before_save instead. That's constructed - # by calling #{kind}_#{name} on the given instance. In this - # case "kind" is "before" and "name" is "save". In this context +:kind+ - # and +:name+ have special meanings: +:kind+ refers to the kind of - # callback (before/after/around) and +:name+ refers to the method on - # which callbacks are being defined. - # - # A declaration like - # - # define_callbacks :save, scope: [:name] - # - # would call Audit#save. - # - # ===== Notes - # - # +names+ passed to `define_callbacks` must not end with - # `!`, `?` or `=`. - # - # Calling `define_callbacks` multiple times with the same +names+ will - # overwrite previous callbacks registered with `set_callback`. - def define_callbacks(*names) - options = names.extract_options! - - names.each do |name| - class_attribute "_#{name}_callbacks", instance_writer: false - set_callbacks name, CallbackChain.new(name, options) - - module_eval <<-RUBY, __FILE__, __LINE__ + 1 + # Define sets of events in the object life cycle that support callbacks. + # + # define_callbacks :validate + # define_callbacks :initialize, :save, :destroy + # + # ===== Options + # + # * :terminator - Determines when a before filter will halt the + # callback chain, preventing following before and around callbacks from + # being called and the event from being triggered. + # This should be a lambda to be executed. + # The current object and the result lambda of the callback will be provided + # to the terminator lambda. + # + # define_callbacks :validate, terminator: ->(target, result_lambda) { result_lambda.call == false } + # + # In this example, if any before validate callbacks returns +false+, + # any successive before and around callback is not executed. + # + # The default terminator halts the chain when a callback throws +:abort+. + # + # * :skip_after_callbacks_if_terminated - Determines if after + # callbacks should be terminated by the :terminator option. By + # default after callbacks are executed no matter if callback chain was + # terminated or not. This option makes sense only when :terminator + # option is specified. + # + # * :scope - Indicates which methods should be executed when an + # object is used as a callback. + # + # class Audit + # def before(caller) + # puts 'Audit: before is called' + # end + # + # def before_save(caller) + # puts 'Audit: before_save is called' + # end + # end + # + # class Account + # include ActiveSupport::Callbacks + # + # define_callbacks :save + # set_callback :save, :before, Audit.new + # + # def save + # run_callbacks :save do + # puts 'save in main' + # end + # end + # end + # + # In the above case whenever you save an account the method + # Audit#before will be called. On the other hand + # + # define_callbacks :save, scope: [:kind, :name] + # + # would trigger Audit#before_save instead. That's constructed + # by calling #{kind}_#{name} on the given instance. In this + # case "kind" is "before" and "name" is "save". In this context +:kind+ + # and +:name+ have special meanings: +:kind+ refers to the kind of + # callback (before/after/around) and +:name+ refers to the method on + # which callbacks are being defined. + # + # A declaration like + # + # define_callbacks :save, scope: [:name] + # + # would call Audit#save. + # + # ===== Notes + # + # +names+ passed to `define_callbacks` must not end with + # `!`, `?` or `=`. + # + # Calling `define_callbacks` multiple times with the same +names+ will + # overwrite previous callbacks registered with `set_callback`. + def define_callbacks(*names) + options = names.extract_options! + + names.each do |name| + class_attribute "_#{name}_callbacks", instance_writer: false + set_callbacks name, CallbackChain.new(name, options) + + module_eval <<-RUBY, __FILE__, __LINE__ + 1 def _run_#{name}_callbacks(&block) __run_callbacks__(_#{name}_callbacks, &block) end RUBY + end end - end - protected + protected - def get_callbacks(name) # :nodoc: - send "_#{name}_callbacks" - end + def get_callbacks(name) # :nodoc: + send "_#{name}_callbacks" + end - def set_callbacks(name, callbacks) # :nodoc: - send "_#{name}_callbacks=", callbacks - end + def set_callbacks(name, callbacks) # :nodoc: + send "_#{name}_callbacks=", callbacks + end - def deprecated_false_terminator # :nodoc: - Proc.new do |target, result_lambda| - terminate = true - catch(:abort) do - result = result_lambda.call if result_lambda.is_a?(Proc) - if Callbacks.halt_and_display_warning_on_return_false && result == false - display_deprecation_warning_for_false_terminator - else - terminate = false + def deprecated_false_terminator # :nodoc: + Proc.new do |target, result_lambda| + terminate = true + catch(:abort) do + result = result_lambda.call if result_lambda.is_a?(Proc) + if Callbacks.halt_and_display_warning_on_return_false && result == false + display_deprecation_warning_for_false_terminator + else + terminate = false + end + end + terminate end end - terminate - end - end - private + private - def display_deprecation_warning_for_false_terminator - ActiveSupport::Deprecation.warn(<<-MSG.squish) + def display_deprecation_warning_for_false_terminator + ActiveSupport::Deprecation.warn(<<-MSG.squish) Returning `false` in Active Record and Active Model callbacks will not implicitly halt a callback chain in Rails 5.1. To explicitly halt the callback chain, please use `throw :abort` instead. MSG + end end - end end end diff --git a/activesupport/lib/active_support/concurrency/share_lock.rb b/activesupport/lib/active_support/concurrency/share_lock.rb index f57e81bad8..e61dadd0cc 100644 --- a/activesupport/lib/active_support/concurrency/share_lock.rb +++ b/activesupport/lib/active_support/concurrency/share_lock.rb @@ -201,26 +201,26 @@ module ActiveSupport private # Must be called within synchronize - def busy_for_exclusive?(purpose) - busy_for_sharing?(purpose) || - @sharing.size > (@sharing[Thread.current] > 0 ? 1 : 0) - end + def busy_for_exclusive?(purpose) + busy_for_sharing?(purpose) || + @sharing.size > (@sharing[Thread.current] > 0 ? 1 : 0) + end - def busy_for_sharing?(purpose) - (@exclusive_thread && @exclusive_thread != Thread.current) || - @waiting.any? { |t, (_, c)| t != Thread.current && !c.include?(purpose) } - end + def busy_for_sharing?(purpose) + (@exclusive_thread && @exclusive_thread != Thread.current) || + @waiting.any? { |t, (_, c)| t != Thread.current && !c.include?(purpose) } + end - def eligible_waiters?(compatible) - @waiting.any? { |t, (p, _)| compatible.include?(p) && @waiting.all? { |t2, (_, c2)| t == t2 || c2.include?(p) } } - end + def eligible_waiters?(compatible) + @waiting.any? { |t, (p, _)| compatible.include?(p) && @waiting.all? { |t2, (_, c2)| t == t2 || c2.include?(p) } } + end - def wait_for(method) - @sleeping[Thread.current] = method - @cv.wait_while { yield } - ensure - @sleeping.delete Thread.current - end + def wait_for(method) + @sleeping[Thread.current] = method + @cv.wait_while { yield } + ensure + @sleeping.delete Thread.current + end end end end diff --git a/activesupport/lib/active_support/core_ext/array/prepend_and_append.rb b/activesupport/lib/active_support/core_ext/array/prepend_and_append.rb index f8d48b69df..16a6789f8d 100644 --- a/activesupport/lib/active_support/core_ext/array/prepend_and_append.rb +++ b/activesupport/lib/active_support/core_ext/array/prepend_and_append.rb @@ -4,4 +4,4 @@ class Array # The human way of thinking about adding stuff to the beginning of a list is with prepend. alias_method :prepend, :unshift -end \ No newline at end of file +end diff --git a/activesupport/lib/active_support/core_ext/date/calculations.rb b/activesupport/lib/active_support/core_ext/date/calculations.rb index 5cc4e936cd..2e64097933 100644 --- a/activesupport/lib/active_support/core_ext/date/calculations.rb +++ b/activesupport/lib/active_support/core_ext/date/calculations.rb @@ -129,7 +129,7 @@ class Date options.fetch(:day, day) ) end - + # Allow Date to be compared with Time by converting to DateTime and relying on the <=> from there. def compare_with_coercion(other) if other.is_a?(Time) 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 e2432c8f8a..c5b46c598c 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 @@ -28,13 +28,12 @@ module DateAndTime private - def time_with_zone(time, zone) - if time - ActiveSupport::TimeWithZone.new(time.utc? ? time : time.getutc, zone) - else - ActiveSupport::TimeWithZone.new(nil, zone, to_time(:utc)) + def time_with_zone(time, zone) + if time + ActiveSupport::TimeWithZone.new(time.utc? ? time : time.getutc, zone) + else + ActiveSupport::TimeWithZone.new(nil, zone, to_time(:utc)) + end end - end end end - diff --git a/activesupport/lib/active_support/core_ext/date_time/conversions.rb b/activesupport/lib/active_support/core_ext/date_time/conversions.rb index 9fa64bbcdb..44ae96dbe8 100644 --- a/activesupport/lib/active_support/core_ext/date_time/conversions.rb +++ b/activesupport/lib/active_support/core_ext/date_time/conversions.rb @@ -95,11 +95,11 @@ class DateTime private - def offset_in_seconds - (offset * 86400).to_i - end + def offset_in_seconds + (offset * 86400).to_i + end - def seconds_since_unix_epoch - (jd - 2440588) * 86400 - offset_in_seconds + seconds_since_midnight - end + def seconds_since_unix_epoch + (jd - 2440588) * 86400 - offset_in_seconds + seconds_since_midnight + end end diff --git a/activesupport/lib/active_support/core_ext/hash/slice.rb b/activesupport/lib/active_support/core_ext/hash/slice.rb index 1d5f38231a..161b00dfb3 100644 --- a/activesupport/lib/active_support/core_ext/hash/slice.rb +++ b/activesupport/lib/active_support/core_ext/hash/slice.rb @@ -1,11 +1,11 @@ class Hash - # Slices a hash to include only the given keys. Returns a hash containing + # Slices a hash to include only the given keys. Returns a hash containing # the given keys. - # + # # { a: 1, b: 2, c: 3, d: 4 }.slice(:a, :b) # # => {:a=>1, :b=>2} - # - # This is useful for limiting an options hash to valid keys before + # + # This is useful for limiting an options hash to valid keys before # passing to a method: # # def search(criteria = {}) diff --git a/activesupport/lib/active_support/core_ext/numeric/inquiry.rb b/activesupport/lib/active_support/core_ext/numeric/inquiry.rb index 7e7ac1b0b2..ec79701189 100644 --- a/activesupport/lib/active_support/core_ext/numeric/inquiry.rb +++ b/activesupport/lib/active_support/core_ext/numeric/inquiry.rb @@ -1,26 +1,26 @@ unless 1.respond_to?(:positive?) # TODO: Remove this file when we drop support to ruby < 2.3 -class Numeric - # Returns true if the number is positive. - # - # 1.positive? # => true - # 0.positive? # => false - # -1.positive? # => false - def positive? - self > 0 - end + class Numeric + # Returns true if the number is positive. + # + # 1.positive? # => true + # 0.positive? # => false + # -1.positive? # => false + def positive? + self > 0 + end - # Returns true if the number is negative. - # - # -1.negative? # => true - # 0.negative? # => false - # 1.negative? # => false - def negative? - self < 0 + # Returns true if the number is negative. + # + # -1.negative? # => true + # 0.negative? # => false + # 1.negative? # => false + def negative? + self < 0 + end end -end -class Complex - undef :positive? - undef :negative? -end + class Complex + undef :positive? + undef :negative? + 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 26d5c43ae9..bf94b97ceb 100644 --- a/activesupport/lib/active_support/core_ext/string/inflections.rb +++ b/activesupport/lib/active_support/core_ext/string/inflections.rb @@ -164,7 +164,7 @@ class String # # <%= link_to(@person.name, person_path) %> # # => Donald E. Knuth - # + # # To preserve the case of the characters in a string, use the `preserve_case` argument. # # class Person diff --git a/activesupport/lib/active_support/core_ext/string/output_safety.rb b/activesupport/lib/active_support/core_ext/string/output_safety.rb index d01a837fc9..2b7e556ced 100644 --- a/activesupport/lib/active_support/core_ext/string/output_safety.rb +++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb @@ -243,9 +243,9 @@ module ActiveSupport #:nodoc: private - def html_escape_interpolated_argument(arg) - (!html_safe? || arg.html_safe?) ? arg : CGI.escapeHTML(arg.to_s) - end + def html_escape_interpolated_argument(arg) + (!html_safe? || arg.html_safe?) ? arg : CGI.escapeHTML(arg.to_s) + end end end diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index 73ca737c82..9f1593a23a 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -170,9 +170,9 @@ module ActiveSupport #:nodoc: end private - def pop_modules(modules) - modules.each { |mod| @stack[mod].pop } - end + def pop_modules(modules) + modules.each { |mod| @stack[mod].pop } + end end # An internal stack used to record which constants are loaded by any block. @@ -282,17 +282,17 @@ module ActiveSupport #:nodoc: private - def load(file, wrap = false) - result = false - load_dependency(file) { result = super } - result - end + def load(file, wrap = false) + result = false + load_dependency(file) { result = super } + result + end - def require(file) - result = false - load_dependency(file) { result = super } - result - end + def require(file) + result = false + load_dependency(file) { result = super } + result + end end # Exception file-blaming. diff --git a/activesupport/lib/active_support/duration/iso8601_parser.rb b/activesupport/lib/active_support/duration/iso8601_parser.rb index 3f113b1ef0..99a77c0bd3 100644 --- a/activesupport/lib/active_support/duration/iso8601_parser.rb +++ b/activesupport/lib/active_support/duration/iso8601_parser.rb @@ -80,44 +80,44 @@ module ActiveSupport private - def finished? - scanner.eos? - end + def finished? + scanner.eos? + end # Parses number which can be a float with either comma or period. - def number - PERIOD_OR_COMMA.match?(scanner[1]) ? scanner[1].tr(COMMA, PERIOD).to_f : scanner[1].to_i - end + def number + PERIOD_OR_COMMA.match?(scanner[1]) ? scanner[1].tr(COMMA, PERIOD).to_f : scanner[1].to_i + end - def scan(pattern) - scanner.scan(pattern) - end + def scan(pattern) + scanner.scan(pattern) + end - def raise_parsing_error(reason = nil) - raise ParsingError, "Invalid ISO 8601 duration: #{scanner.string.inspect} #{reason}".strip - end + def raise_parsing_error(reason = nil) + raise ParsingError, "Invalid ISO 8601 duration: #{scanner.string.inspect} #{reason}".strip + end # Checks for various semantic errors as stated in ISO 8601 standard. - def validate! - raise_parsing_error("is empty duration") if parts.empty? + def validate! + raise_parsing_error("is empty duration") if parts.empty? - # Mixing any of Y, M, D with W is invalid. - if parts.key?(:weeks) && (parts.keys & DATE_COMPONENTS).any? - raise_parsing_error("mixing weeks with other date parts not allowed") - end + # Mixing any of Y, M, D with W is invalid. + if parts.key?(:weeks) && (parts.keys & DATE_COMPONENTS).any? + raise_parsing_error("mixing weeks with other date parts not allowed") + end - # Specifying an empty T part is invalid. - if mode == :time && (parts.keys & TIME_COMPONENTS).empty? - raise_parsing_error("time part marker is present but time part is empty") - end + # Specifying an empty T part is invalid. + if mode == :time && (parts.keys & TIME_COMPONENTS).empty? + raise_parsing_error("time part marker is present but time part is empty") + end - fractions = parts.values.reject(&:zero?).select { |a| (a % 1) != 0 } - unless fractions.empty? || (fractions.size == 1 && fractions.last == @parts.values.reject(&:zero?).last) - raise_parsing_error "(only last part can be fractional)" - end + fractions = parts.values.reject(&:zero?).select { |a| (a % 1) != 0 } + unless fractions.empty? || (fractions.size == 1 && fractions.last == @parts.values.reject(&:zero?).last) + raise_parsing_error "(only last part can be fractional)" + end - return true - end + return true + end end end end diff --git a/activesupport/lib/active_support/evented_file_update_checker.rb b/activesupport/lib/active_support/evented_file_update_checker.rb index 576cd869e5..f54f88eb0a 100644 --- a/activesupport/lib/active_support/evented_file_update_checker.rb +++ b/activesupport/lib/active_support/evented_file_update_checker.rb @@ -124,71 +124,71 @@ module ActiveSupport @ph.filter_out_descendants(dtw) end - class PathHelper - def xpath(path) - Pathname.new(path).expand_path - end + class PathHelper + def xpath(path) + Pathname.new(path).expand_path + end - def normalize_extension(ext) - ext.to_s.sub(/\A\./, "") - end + def normalize_extension(ext) + ext.to_s.sub(/\A\./, "") + end - # Given a collection of Pathname objects returns the longest subpath - # common to all of them, or +nil+ if there is none. - def longest_common_subpath(paths) - return if paths.empty? - - lcsp = Pathname.new(paths[0]) - - paths[1..-1].each do |path| - until ascendant_of?(lcsp, path) - if lcsp.root? - # If we get here a root directory is not an ascendant of path. - # This may happen if there are paths in different drives on - # Windows. - return - else - lcsp = lcsp.parent + # Given a collection of Pathname objects returns the longest subpath + # common to all of them, or +nil+ if there is none. + def longest_common_subpath(paths) + return if paths.empty? + + lcsp = Pathname.new(paths[0]) + + paths[1..-1].each do |path| + until ascendant_of?(lcsp, path) + if lcsp.root? + # If we get here a root directory is not an ascendant of path. + # This may happen if there are paths in different drives on + # Windows. + return + else + lcsp = lcsp.parent + end end end - end - lcsp - end + lcsp + end - # Returns the deepest existing ascendant, which could be the argument itself. - def existing_parent(dir) - dir.ascend do |ascendant| - break ascendant if ascendant.directory? + # Returns the deepest existing ascendant, which could be the argument itself. + def existing_parent(dir) + dir.ascend do |ascendant| + break ascendant if ascendant.directory? + end end - end - # Filters out directories which are descendants of others in the collection (stable). - def filter_out_descendants(dirs) - return dirs if dirs.length < 2 + # Filters out directories which are descendants of others in the collection (stable). + def filter_out_descendants(dirs) + return dirs if dirs.length < 2 - dirs_sorted_by_nparts = dirs.sort_by { |dir| dir.each_filename.to_a.length } - descendants = [] + dirs_sorted_by_nparts = dirs.sort_by { |dir| dir.each_filename.to_a.length } + descendants = [] - until dirs_sorted_by_nparts.empty? - dir = dirs_sorted_by_nparts.shift + until dirs_sorted_by_nparts.empty? + dir = dirs_sorted_by_nparts.shift - dirs_sorted_by_nparts.reject! do |possible_descendant| - ascendant_of?(dir, possible_descendant) && descendants << possible_descendant + dirs_sorted_by_nparts.reject! do |possible_descendant| + ascendant_of?(dir, possible_descendant) && descendants << possible_descendant + end end - end - # Array#- preserves order. - dirs - descendants - end + # Array#- preserves order. + dirs - descendants + end - private + private - def ascendant_of?(base, other) - base != other && other.ascend do |ascendant| - break true if base == ascendant + def ascendant_of?(base, other) + base != other && other.ascend do |ascendant| + break true if base == ascendant + end end - end - end + end end end diff --git a/activesupport/lib/active_support/file_update_checker.rb b/activesupport/lib/active_support/file_update_checker.rb index 6befd1de51..0b7d67e37a 100644 --- a/activesupport/lib/active_support/file_update_checker.rb +++ b/activesupport/lib/active_support/file_update_checker.rb @@ -93,17 +93,17 @@ module ActiveSupport private - def watched - @watched || begin - all = @files.select { |f| File.exist?(f) } - all.concat(Dir[@glob]) if @glob - all + def watched + @watched || begin + all = @files.select { |f| File.exist?(f) } + all.concat(Dir[@glob]) if @glob + all + end end - end - def updated_at(paths) - @updated_at || max_mtime(paths) || Time.at(0) - end + def updated_at(paths) + @updated_at || max_mtime(paths) || Time.at(0) + end # This method returns the maximum mtime of the files in +paths+, or +nil+ # if the array is empty. @@ -112,46 +112,46 @@ module ActiveSupport # can happen for example if the user changes the clock by hand. It is # healthy to consider this edge case because with mtimes in the future # reloading is not triggered. - def max_mtime(paths) - time_now = Time.now - max_mtime = nil - - # Time comparisons are performed with #compare_without_coercion because - # AS redefines these operators in a way that is much slower and does not - # bring any benefit in this particular code. - # - # Read t1.compare_without_coercion(t2) < 0 as t1 < t2. - paths.each do |path| - mtime = File.mtime(path) - - next if time_now.compare_without_coercion(mtime) < 0 - - if max_mtime.nil? || max_mtime.compare_without_coercion(mtime) < 0 - max_mtime = mtime + def max_mtime(paths) + time_now = Time.now + max_mtime = nil + + # Time comparisons are performed with #compare_without_coercion because + # AS redefines these operators in a way that is much slower and does not + # bring any benefit in this particular code. + # + # Read t1.compare_without_coercion(t2) < 0 as t1 < t2. + paths.each do |path| + mtime = File.mtime(path) + + next if time_now.compare_without_coercion(mtime) < 0 + + if max_mtime.nil? || max_mtime.compare_without_coercion(mtime) < 0 + max_mtime = mtime + end end - end - max_mtime - end + max_mtime + end - def compile_glob(hash) - hash.freeze # Freeze so changes aren't accidentally pushed - return if hash.empty? + def compile_glob(hash) + hash.freeze # Freeze so changes aren't accidentally pushed + return if hash.empty? - globs = hash.map do |key, value| - "#{escape(key)}/**/*#{compile_ext(value)}" + globs = hash.map do |key, value| + "#{escape(key)}/**/*#{compile_ext(value)}" + end + "{#{globs.join(",")}}" end - "{#{globs.join(",")}}" - end - def escape(key) - key.gsub(",",'\,') - end + def escape(key) + key.gsub(",",'\,') + end - def compile_ext(array) - array = Array(array) - return if array.empty? - ".{#{array.join(",")}}" - end + def compile_ext(array) + array = Array(array) + return if array.empty? + ".{#{array.join(",")}}" + end end end diff --git a/activesupport/lib/active_support/gzip.rb b/activesupport/lib/active_support/gzip.rb index 38734a56b5..4aee8dddba 100644 --- a/activesupport/lib/active_support/gzip.rb +++ b/activesupport/lib/active_support/gzip.rb @@ -9,7 +9,7 @@ module ActiveSupport # # => "\x1F\x8B\b\x00o\x8D\xCDO\x00\x03K\xCE\xCF-(J-.V\xC8MU\x04\x00R>n\x83\f\x00\x00\x00" # # ActiveSupport::Gzip.decompress(gzip) - # # => "compress me!" + # # => "compress me!" module Gzip class Stream < StringIO def initialize(*) diff --git a/activesupport/lib/active_support/inflector/methods.rb b/activesupport/lib/active_support/inflector/methods.rb index ddbdac4eae..fcfe063290 100644 --- a/activesupport/lib/active_support/inflector/methods.rb +++ b/activesupport/lib/active_support/inflector/methods.rb @@ -361,31 +361,31 @@ module ActiveSupport # # const_regexp("Foo::Bar::Baz") # => "Foo(::Bar(::Baz)?)?" # const_regexp("::") # => "::" - def const_regexp(camel_cased_word) #:nodoc: - parts = camel_cased_word.split("::".freeze) + def const_regexp(camel_cased_word) #:nodoc: + parts = camel_cased_word.split("::".freeze) - return Regexp.escape(camel_cased_word) if parts.blank? + return Regexp.escape(camel_cased_word) if parts.blank? - last = parts.pop + last = parts.pop - parts.reverse.inject(last) do |acc, part| - part.empty? ? acc : "#{part}(::#{acc})?" + parts.reverse.inject(last) do |acc, part| + part.empty? ? acc : "#{part}(::#{acc})?" + end end - end # Applies inflection rules for +singularize+ and +pluralize+. # # apply_inflections('post', inflections.plurals) # => "posts" # apply_inflections('posts', inflections.singulars) # => "post" - def apply_inflections(word, rules) - result = word.to_s.dup + def apply_inflections(word, rules) + result = word.to_s.dup - if word.empty? || inflections.uncountables.uncountable?(result) - result - else - rules.each { |(rule, replacement)| break if result.sub!(rule, replacement) } - result + if word.empty? || inflections.uncountables.uncountable?(result) + result + else + rules.each { |(rule, replacement)| break if result.sub!(rule, replacement) } + result + end end - end end end diff --git a/activesupport/lib/active_support/inflector/transliterate.rb b/activesupport/lib/active_support/inflector/transliterate.rb index 8f7c6987bc..3f4eeff2dd 100644 --- a/activesupport/lib/active_support/inflector/transliterate.rb +++ b/activesupport/lib/active_support/inflector/transliterate.rb @@ -104,7 +104,7 @@ module ActiveSupport # Remove leading/trailing separator. parameterized_string.gsub!(re_leading_trailing_separator, "".freeze) end - + parameterized_string.downcase! unless preserve_case parameterized_string end diff --git a/activesupport/lib/active_support/key_generator.rb b/activesupport/lib/active_support/key_generator.rb index 8b7c5f170b..156cfc32f8 100644 --- a/activesupport/lib/active_support/key_generator.rb +++ b/activesupport/lib/active_support/key_generator.rb @@ -53,19 +53,19 @@ module ActiveSupport # To prevent users from using something insecure like "Password" we make sure that the # secret they've provided is at least 30 characters in length. - def ensure_secret_secure(secret) - if secret.blank? - raise ArgumentError, "A secret is required to generate an integrity hash " \ - "for cookie session data. Set a secret_key_base of at least " \ - "#{SECRET_MIN_LENGTH} characters in config/secrets.yml." - end + def ensure_secret_secure(secret) + if secret.blank? + raise ArgumentError, "A secret is required to generate an integrity hash " \ + "for cookie session data. Set a secret_key_base of at least " \ + "#{SECRET_MIN_LENGTH} characters in config/secrets.yml." + end - if secret.length < SECRET_MIN_LENGTH - raise ArgumentError, "Secret should be something secure, " \ - "like \"#{SecureRandom.hex(16)}\". The value you " \ - "provided, \"#{secret}\", is shorter than the minimum length " \ - "of #{SECRET_MIN_LENGTH} characters." + if secret.length < SECRET_MIN_LENGTH + raise ArgumentError, "Secret should be something secure, " \ + "like \"#{SecureRandom.hex(16)}\". The value you " \ + "provided, \"#{secret}\", is shorter than the minimum length " \ + "of #{SECRET_MIN_LENGTH} characters." + end end - end end end diff --git a/activesupport/lib/active_support/log_subscriber/test_helper.rb b/activesupport/lib/active_support/log_subscriber/test_helper.rb index 7db156b057..a7e30632f6 100644 --- a/activesupport/lib/active_support/log_subscriber/test_helper.rb +++ b/activesupport/lib/active_support/log_subscriber/test_helper.rb @@ -62,11 +62,11 @@ module ActiveSupport end def method_missing(level, message = nil) - if block_given? - @logged[level] << yield - else - @logged[level] << message - end + if block_given? + @logged[level] << yield + else + @logged[level] << message + end end def logged(level) diff --git a/activesupport/lib/active_support/message_encryptor.rb b/activesupport/lib/active_support/message_encryptor.rb index 2fe1e42273..c198e4e6f1 100644 --- a/activesupport/lib/active_support/message_encryptor.rb +++ b/activesupport/lib/active_support/message_encryptor.rb @@ -79,66 +79,66 @@ module ActiveSupport private - def _encrypt(value) - cipher = new_cipher - cipher.encrypt - cipher.key = @secret + def _encrypt(value) + cipher = new_cipher + cipher.encrypt + cipher.key = @secret - # Rely on OpenSSL for the initialization vector - iv = cipher.random_iv - cipher.auth_data = "" if aead_mode? + # Rely on OpenSSL for the initialization vector + iv = cipher.random_iv + cipher.auth_data = "" if aead_mode? - encrypted_data = cipher.update(@serializer.dump(value)) - encrypted_data << cipher.final + encrypted_data = cipher.update(@serializer.dump(value)) + encrypted_data << cipher.final - blob = "#{::Base64.strict_encode64 encrypted_data}--#{::Base64.strict_encode64 iv}" - blob << "--#{::Base64.strict_encode64 cipher.auth_tag}" if aead_mode? - blob - end - - def _decrypt(encrypted_message) - cipher = new_cipher - 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 - # https://github.com/ruby/openssl/issues/63 - raise InvalidMessage if aead_mode? && auth_tag.bytes.length != 16 - - cipher.decrypt - cipher.key = @secret - cipher.iv = iv - if aead_mode? - cipher.auth_tag = auth_tag - cipher.auth_data = "" + blob = "#{::Base64.strict_encode64 encrypted_data}--#{::Base64.strict_encode64 iv}" + blob << "--#{::Base64.strict_encode64 cipher.auth_tag}" if aead_mode? + blob end - decrypted_data = cipher.update(encrypted_data) - decrypted_data << cipher.final - - @serializer.load(decrypted_data) - rescue OpenSSLCipherError, TypeError, ArgumentError - raise InvalidMessage - end + def _decrypt(encrypted_message) + cipher = new_cipher + 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 + # https://github.com/ruby/openssl/issues/63 + raise InvalidMessage if aead_mode? && auth_tag.bytes.length != 16 + + cipher.decrypt + cipher.key = @secret + cipher.iv = iv + if aead_mode? + cipher.auth_tag = auth_tag + cipher.auth_data = "" + end + + decrypted_data = cipher.update(encrypted_data) + decrypted_data << cipher.final + + @serializer.load(decrypted_data) + rescue OpenSSLCipherError, TypeError, ArgumentError + raise InvalidMessage + end - def new_cipher - OpenSSL::Cipher.new(@cipher) - end + def new_cipher + OpenSSL::Cipher.new(@cipher) + end - def verifier - @verifier - end + def verifier + @verifier + end - def aead_mode? - @aead_mode ||= new_cipher.authenticated? - end + def aead_mode? + @aead_mode ||= new_cipher.authenticated? + end - def resolve_verifier - if aead_mode? - NullVerifier - else - MessageVerifier.new(@sign_secret || @secret, digest: @digest, serializer: NullSerializer) + def resolve_verifier + if aead_mode? + NullVerifier + else + MessageVerifier.new(@sign_secret || @secret, digest: @digest, serializer: NullSerializer) + end end - end end end diff --git a/activesupport/lib/active_support/multibyte/unicode.rb b/activesupport/lib/active_support/multibyte/unicode.rb index 86f80a97e5..dfd87c9397 100644 --- a/activesupport/lib/active_support/multibyte/unicode.rb +++ b/activesupport/lib/active_support/multibyte/unicode.rb @@ -389,25 +389,25 @@ module ActiveSupport private - def apply_mapping(string, mapping) #:nodoc: - database.codepoints - string.each_codepoint.map do |codepoint| - cp = database.codepoints[codepoint] - if cp and (ncp = cp.send(mapping)) and ncp > 0 - ncp - else - codepoint - end - end.pack("U*") - end + def apply_mapping(string, mapping) #:nodoc: + database.codepoints + string.each_codepoint.map do |codepoint| + cp = database.codepoints[codepoint] + if cp and (ncp = cp.send(mapping)) and ncp > 0 + ncp + else + codepoint + end + end.pack("U*") + end - def recode_windows1252_chars(string) - string.encode(Encoding::UTF_8, Encoding::Windows_1252, invalid: :replace, undef: :replace) - end + def recode_windows1252_chars(string) + string.encode(Encoding::UTF_8, Encoding::Windows_1252, invalid: :replace, undef: :replace) + end - def database - @database ||= UnicodeDatabase.new - end + def database + @database ||= UnicodeDatabase.new + end end end end diff --git a/activesupport/lib/active_support/notifications/instrumenter.rb b/activesupport/lib/active_support/notifications/instrumenter.rb index 16e6ec95fb..23262d5398 100644 --- a/activesupport/lib/active_support/notifications/instrumenter.rb +++ b/activesupport/lib/active_support/notifications/instrumenter.rb @@ -44,9 +44,9 @@ module ActiveSupport private - def unique_id - SecureRandom.hex(10) - end + def unique_id + SecureRandom.hex(10) + end end class Event diff --git a/activesupport/lib/active_support/number_helper/number_to_human_size_converter.rb b/activesupport/lib/active_support/number_helper/number_to_human_size_converter.rb index 2b8ff77986..78cb33aa62 100644 --- a/activesupport/lib/active_support/number_helper/number_to_human_size_converter.rb +++ b/activesupport/lib/active_support/number_helper/number_to_human_size_converter.rb @@ -59,4 +59,3 @@ module ActiveSupport end end end - diff --git a/activesupport/lib/active_support/number_helper/number_to_phone_converter.rb b/activesupport/lib/active_support/number_helper/number_to_phone_converter.rb index dee74fa7a6..07b1f18695 100644 --- a/activesupport/lib/active_support/number_helper/number_to_phone_converter.rb +++ b/activesupport/lib/active_support/number_helper/number_to_phone_converter.rb @@ -55,4 +55,3 @@ module ActiveSupport end end end - diff --git a/activesupport/lib/active_support/testing/stream.rb b/activesupport/lib/active_support/testing/stream.rb index 895192ad05..1d06b94559 100644 --- a/activesupport/lib/active_support/testing/stream.rb +++ b/activesupport/lib/active_support/testing/stream.rb @@ -3,40 +3,40 @@ module ActiveSupport module Stream #:nodoc: private - def silence_stream(stream) - old_stream = stream.dup - stream.reopen(IO::NULL) - stream.sync = true - yield - ensure - stream.reopen(old_stream) - old_stream.close - end + def silence_stream(stream) + old_stream = stream.dup + stream.reopen(IO::NULL) + stream.sync = true + yield + ensure + stream.reopen(old_stream) + old_stream.close + end - def quietly - silence_stream(STDOUT) do - silence_stream(STDERR) do - yield + def quietly + silence_stream(STDOUT) do + silence_stream(STDERR) do + yield + end end end - end - def capture(stream) - stream = stream.to_s - captured_stream = Tempfile.new(stream) - stream_io = eval("$#{stream}") - origin_stream = stream_io.dup - stream_io.reopen(captured_stream) + def capture(stream) + stream = stream.to_s + captured_stream = Tempfile.new(stream) + stream_io = eval("$#{stream}") + origin_stream = stream_io.dup + stream_io.reopen(captured_stream) - yield + yield - stream_io.rewind - return captured_stream.read - ensure - captured_stream.close - captured_stream.unlink - stream_io.reopen(origin_stream) - end + stream_io.rewind + return captured_stream.read + ensure + captured_stream.close + captured_stream.unlink + stream_io.reopen(origin_stream) + end end end end diff --git a/activesupport/lib/active_support/values/time_zone.rb b/activesupport/lib/active_support/values/time_zone.rb index d805381d1e..26906d2911 100644 --- a/activesupport/lib/active_support/values/time_zone.rb +++ b/activesupport/lib/active_support/values/time_zone.rb @@ -227,11 +227,11 @@ module ActiveSupport def [](arg) case arg when String - begin - @lazy_zones_map[arg] ||= create(arg) - rescue TZInfo::InvalidTimezoneIdentifier - nil - end + begin + @lazy_zones_map[arg] ||= create(arg) + rescue TZInfo::InvalidTimezoneIdentifier + nil + end when Numeric, ActiveSupport::Duration arg *= 3600 if arg.abs <= 13 all.find { |z| z.utc_offset == arg.to_i } diff --git a/activesupport/lib/active_support/xml_mini.rb b/activesupport/lib/active_support/xml_mini.rb index 5611b1b143..12a7c61240 100644 --- a/activesupport/lib/active_support/xml_mini.rb +++ b/activesupport/lib/active_support/xml_mini.rb @@ -151,29 +151,29 @@ module ActiveSupport protected - def _dasherize(key) - # $2 must be a non-greedy regex for this to work - left, middle, right = /\A(_*)(.*?)(_*)\Z/.match(key.strip)[1,3] - "#{left}#{middle.tr('_ ', '--')}#{right}" - end + def _dasherize(key) + # $2 must be a non-greedy regex for this to work + left, middle, right = /\A(_*)(.*?)(_*)\Z/.match(key.strip)[1,3] + "#{left}#{middle.tr('_ ', '--')}#{right}" + end # TODO: Add support for other encodings - def _parse_binary(bin, entity) #:nodoc: - case entity["encoding"] - when "base64" - ::Base64.decode64(bin) - else - bin + def _parse_binary(bin, entity) #:nodoc: + case entity["encoding"] + when "base64" + ::Base64.decode64(bin) + else + bin + end end - end - def _parse_file(file, entity) - f = StringIO.new(::Base64.decode64(file)) - f.extend(FileLike) - f.original_filename = entity["name"] - f.content_type = entity["content_type"] - f - end + def _parse_file(file, entity) + f = StringIO.new(::Base64.decode64(file)) + f.extend(FileLike) + f.original_filename = entity["name"] + f.content_type = entity["content_type"] + f + end private diff --git a/activesupport/lib/active_support/xml_mini/jdom.rb b/activesupport/lib/active_support/xml_mini/jdom.rb index 44923f8da9..90f6cc464f 100644 --- a/activesupport/lib/active_support/xml_mini/jdom.rb +++ b/activesupport/lib/active_support/xml_mini/jdom.rb @@ -58,35 +58,35 @@ module ActiveSupport # Hash to merge the converted element into. # element:: # XML element to merge into hash - def merge_element!(hash, element, depth) - raise "Document too deep!" if depth == 0 - delete_empty(hash) - merge!(hash, element.tag_name, collapse(element, depth)) - end + def merge_element!(hash, element, depth) + raise "Document too deep!" if depth == 0 + delete_empty(hash) + merge!(hash, element.tag_name, collapse(element, depth)) + end - def delete_empty(hash) - hash.delete(CONTENT_KEY) if hash[CONTENT_KEY] == "" - end + def delete_empty(hash) + hash.delete(CONTENT_KEY) if hash[CONTENT_KEY] == "" + end # Actually converts an XML document element into a data structure. # # element:: # The document element to be collapsed. - def collapse(element, depth) - hash = get_attributes(element) - - child_nodes = element.child_nodes - if child_nodes.length > 0 - (0...child_nodes.length).each do |i| - child = child_nodes.item(i) - merge_element!(hash, child, depth - 1) unless child.node_type == Node.TEXT_NODE + def collapse(element, depth) + hash = get_attributes(element) + + child_nodes = element.child_nodes + if child_nodes.length > 0 + (0...child_nodes.length).each do |i| + child = child_nodes.item(i) + merge_element!(hash, child, depth - 1) unless child.node_type == Node.TEXT_NODE + end + merge_texts!(hash, element) unless empty_content?(element) + hash + else + merge_texts!(hash, element) end - merge_texts!(hash, element) unless empty_content?(element) - hash - else - merge_texts!(hash, element) end - end # Merge all the texts of an element into the hash # @@ -94,16 +94,16 @@ module ActiveSupport # Hash to add the converted element to. # element:: # XML element whose texts are to me merged into the hash - def merge_texts!(hash, element) - delete_empty(hash) - text_children = texts(element) - if text_children.join.empty? - hash - else - # must use value to prevent double-escaping - merge!(hash, CONTENT_KEY, text_children.join) + def merge_texts!(hash, element) + delete_empty(hash) + text_children = texts(element) + if text_children.join.empty? + hash + else + # must use value to prevent double-escaping + merge!(hash, CONTENT_KEY, text_children.join) + end end - end # Adds a new key/value pair to an existing Hash. If the key to be added # already exists and the existing value associated with key is not @@ -116,66 +116,66 @@ module ActiveSupport # Key to be added. # value:: # Value to be associated with key. - def merge!(hash, key, value) - if hash.has_key?(key) - if hash[key].instance_of?(Array) - hash[key] << value + def merge!(hash, key, value) + if hash.has_key?(key) + if hash[key].instance_of?(Array) + hash[key] << value + else + hash[key] = [hash[key], value] + end + elsif value.instance_of?(Array) + hash[key] = [value] else - hash[key] = [hash[key], value] + hash[key] = value end - elsif value.instance_of?(Array) - hash[key] = [value] - else - hash[key] = value + hash end - hash - end # Converts the attributes array of an XML element into a hash. # Returns an empty Hash if node has no attributes. # # element:: # XML element to extract attributes from. - def get_attributes(element) - attribute_hash = {} - attributes = element.attributes - (0...attributes.length).each do |i| - attribute_hash[CONTENT_KEY] ||= "" - attribute_hash[attributes.item(i).name] = attributes.item(i).value + def get_attributes(element) + attribute_hash = {} + attributes = element.attributes + (0...attributes.length).each do |i| + attribute_hash[CONTENT_KEY] ||= "" + attribute_hash[attributes.item(i).name] = attributes.item(i).value + end + attribute_hash end - attribute_hash - end # Determines if a document element has text content # # element:: # XML element to be checked. - def texts(element) - texts = [] - child_nodes = element.child_nodes - (0...child_nodes.length).each do |i| - item = child_nodes.item(i) - if item.node_type == Node.TEXT_NODE - texts << item.get_data + def texts(element) + texts = [] + child_nodes = element.child_nodes + (0...child_nodes.length).each do |i| + item = child_nodes.item(i) + if item.node_type == Node.TEXT_NODE + texts << item.get_data + end end + texts end - texts - end # Determines if a document element has text content # # element:: # XML element to be checked. - def empty_content?(element) - text = "" - child_nodes = element.child_nodes - (0...child_nodes.length).each do |i| - item = child_nodes.item(i) - if item.node_type == Node.TEXT_NODE - text << item.get_data.strip + def empty_content?(element) + text = "" + child_nodes = element.child_nodes + (0...child_nodes.length).each do |i| + item = child_nodes.item(i) + if item.node_type == Node.TEXT_NODE + text << item.get_data.strip + end end + text.strip.length == 0 end - text.strip.length == 0 - end end end diff --git a/activesupport/test/autoload_test.rb b/activesupport/test/autoload_test.rb index 6a0ce5f3dd..c4d6a69212 100644 --- a/activesupport/test/autoload_test.rb +++ b/activesupport/test/autoload_test.rb @@ -78,4 +78,4 @@ class TestAutoloadModule < ActiveSupport::TestCase assert !$LOADED_FEATURES.include?(@another_class_path) assert_nothing_raised { ::Fixtures::AnotherClass } end -end \ No newline at end of file +end diff --git a/activesupport/test/autoloading_fixtures/a/b.rb b/activesupport/test/autoloading_fixtures/a/b.rb index 9c9e6454cf..0dbbbbd181 100644 --- a/activesupport/test/autoloading_fixtures/a/b.rb +++ b/activesupport/test/autoloading_fixtures/a/b.rb @@ -1,2 +1,2 @@ class A::B -end \ No newline at end of file +end diff --git a/activesupport/test/autoloading_fixtures/a/c/d.rb b/activesupport/test/autoloading_fixtures/a/c/d.rb index 0f40d6fbc4..2c0ec5f182 100644 --- a/activesupport/test/autoloading_fixtures/a/c/d.rb +++ b/activesupport/test/autoloading_fixtures/a/c/d.rb @@ -1,2 +1,2 @@ class A::C::D -end \ No newline at end of file +end diff --git a/activesupport/test/autoloading_fixtures/a/c/em/f.rb b/activesupport/test/autoloading_fixtures/a/c/em/f.rb index 8b28e19148..3ff1b7efa0 100644 --- a/activesupport/test/autoloading_fixtures/a/c/em/f.rb +++ b/activesupport/test/autoloading_fixtures/a/c/em/f.rb @@ -1,2 +1,2 @@ class A::C::EM::F -end \ No newline at end of file +end diff --git a/activesupport/test/autoloading_fixtures/conflict.rb b/activesupport/test/autoloading_fixtures/conflict.rb index 4ac6201902..d7f42b5d5f 100644 --- a/activesupport/test/autoloading_fixtures/conflict.rb +++ b/activesupport/test/autoloading_fixtures/conflict.rb @@ -1 +1 @@ -Conflict = 2 \ No newline at end of file +Conflict = 2 diff --git a/activesupport/test/autoloading_fixtures/cross_site_dependency.rb b/activesupport/test/autoloading_fixtures/cross_site_dependency.rb index 21ee554e92..de941bf271 100644 --- a/activesupport/test/autoloading_fixtures/cross_site_dependency.rb +++ b/activesupport/test/autoloading_fixtures/cross_site_dependency.rb @@ -1,2 +1,2 @@ class CrossSiteDependency -end \ No newline at end of file +end diff --git a/activesupport/test/autoloading_fixtures/d.rb b/activesupport/test/autoloading_fixtures/d.rb index 45c794d4ca..52850e1e1a 100644 --- a/activesupport/test/autoloading_fixtures/d.rb +++ b/activesupport/test/autoloading_fixtures/d.rb @@ -1,2 +1,2 @@ class D -end \ No newline at end of file +end diff --git a/activesupport/test/autoloading_fixtures/em.rb b/activesupport/test/autoloading_fixtures/em.rb index 16a1838667..e47024999e 100644 --- a/activesupport/test/autoloading_fixtures/em.rb +++ b/activesupport/test/autoloading_fixtures/em.rb @@ -1,2 +1,2 @@ class EM -end \ No newline at end of file +end diff --git a/activesupport/test/autoloading_fixtures/load_path/loaded_constant.rb b/activesupport/test/autoloading_fixtures/load_path/loaded_constant.rb index e3d1218c96..d2c4f6b0c5 100644 --- a/activesupport/test/autoloading_fixtures/load_path/loaded_constant.rb +++ b/activesupport/test/autoloading_fixtures/load_path/loaded_constant.rb @@ -1,3 +1,2 @@ module LoadedConstant end - diff --git a/activesupport/test/autoloading_fixtures/module_folder/nested_sibling.rb b/activesupport/test/autoloading_fixtures/module_folder/nested_sibling.rb index 80244b8bab..04c426833e 100644 --- a/activesupport/test/autoloading_fixtures/module_folder/nested_sibling.rb +++ b/activesupport/test/autoloading_fixtures/module_folder/nested_sibling.rb @@ -1,2 +1,2 @@ class ModuleFolder::NestedSibling -end \ No newline at end of file +end diff --git a/activesupport/test/autoloading_fixtures/module_with_custom_const_missing/a/b.rb b/activesupport/test/autoloading_fixtures/module_with_custom_const_missing/a/b.rb index d12d02f3aa..4f2020c503 100644 --- a/activesupport/test/autoloading_fixtures/module_with_custom_const_missing/a/b.rb +++ b/activesupport/test/autoloading_fixtures/module_with_custom_const_missing/a/b.rb @@ -1 +1 @@ -ModuleWithCustomConstMissing::A::B = "10" \ No newline at end of file +ModuleWithCustomConstMissing::A::B = "10" diff --git a/activesupport/test/autoloading_fixtures/requires_constant.rb b/activesupport/test/autoloading_fixtures/requires_constant.rb index 14804a0de0..f04dcc4091 100644 --- a/activesupport/test/autoloading_fixtures/requires_constant.rb +++ b/activesupport/test/autoloading_fixtures/requires_constant.rb @@ -2,4 +2,3 @@ require "loaded_constant" module RequiresConstant end - diff --git a/activesupport/test/autoloading_fixtures/typo.rb b/activesupport/test/autoloading_fixtures/typo.rb index 8e047f5fd4..0ffe07c2b3 100644 --- a/activesupport/test/autoloading_fixtures/typo.rb +++ b/activesupport/test/autoloading_fixtures/typo.rb @@ -1,2 +1 @@ TypO = 1 - diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb index 422b7f0834..072a2530ba 100644 --- a/activesupport/test/caching_test.rb +++ b/activesupport/test/caching_test.rb @@ -130,13 +130,13 @@ class CacheKeyTest < ActiveSupport::TestCase private - def with_env(kv) - old_values = {} - kv.each { |key, value| old_values[key], ENV[key] = ENV[key], value } - yield - ensure - old_values.each { |key, value| ENV[key] = value} - end + def with_env(kv) + old_values = {} + kv.each { |key, value| old_values[key], ENV[key] = ENV[key], value } + yield + ensure + old_values.each { |key, value| ENV[key] = value} + end end class CacheStoreSettingTest < ActiveSupport::TestCase diff --git a/activesupport/test/core_ext/date_ext_test.rb b/activesupport/test/core_ext/date_ext_test.rb index 0c9b88d861..0655197335 100644 --- a/activesupport/test/core_ext/date_ext_test.rb +++ b/activesupport/test/core_ext/date_ext_test.rb @@ -407,4 +407,3 @@ class DateExtBehaviorTest < ActiveSupport::TestCase end end end - diff --git a/activesupport/test/core_ext/module/anonymous_test.rb b/activesupport/test/core_ext/module/anonymous_test.rb index 36aecfa4c8..f885444284 100644 --- a/activesupport/test/core_ext/module/anonymous_test.rb +++ b/activesupport/test/core_ext/module/anonymous_test.rb @@ -11,4 +11,4 @@ class AnonymousTest < ActiveSupport::TestCase assert !Kernel.anonymous? assert !Object.anonymous? end -end \ No newline at end of file +end 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 903c7206cd..cda5a34442 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 @@ -65,15 +65,15 @@ class ModuleAttributeAccessorPerThreadTest < ActiveSupport::TestCase threads << Thread.new do @class.foo = "other things" sleep 1 - assert_equal "other things", @class.foo + assert_equal "other things", @class.foo end - + threads << Thread.new do @class.foo = "really other things" sleep 1 - assert_equal "really other things", @class.foo + assert_equal "really other things", @class.foo end - + threads.each { |t| t.join } end diff --git a/activesupport/test/core_ext/module/qualified_const_test.rb b/activesupport/test/core_ext/module/qualified_const_test.rb index 1362171b09..dcfac4ced1 100644 --- a/activesupport/test/core_ext/module/qualified_const_test.rb +++ b/activesupport/test/core_ext/module/qualified_const_test.rb @@ -111,8 +111,8 @@ class QualifiedConstTest < ActiveSupport::TestCase private - def assert_raise_with_message(expected_exception, expected_message, &block) - exception = assert_raise(expected_exception, &block) - assert_equal expected_message, exception.message - end + def assert_raise_with_message(expected_exception, expected_message, &block) + exception = assert_raise(expected_exception, &block) + assert_equal expected_message, exception.message + end end diff --git a/activesupport/test/core_ext/module/reachable_test.rb b/activesupport/test/core_ext/module/reachable_test.rb index 01b5f34845..487c7dee16 100644 --- a/activesupport/test/core_ext/module/reachable_test.rb +++ b/activesupport/test/core_ext/module/reachable_test.rb @@ -38,4 +38,4 @@ class AnonymousTest < ActiveSupport::TestCase assert !c.reachable? assert !m.reachable? end -end \ No newline at end of file +end diff --git a/activesupport/test/core_ext/module_test.rb b/activesupport/test/core_ext/module_test.rb index 9a2e52efa7..bfe60e0f5f 100644 --- a/activesupport/test/core_ext/module_test.rb +++ b/activesupport/test/core_ext/module_test.rb @@ -43,9 +43,9 @@ class Someone < Struct.new(:name, :place) private - def private_name - "Private" - end + def private_name + "Private" + end end Invoice = Struct.new(:client) do diff --git a/activesupport/test/core_ext/object/inclusion_test.rb b/activesupport/test/core_ext/object/inclusion_test.rb index 9258c46be5..be211ec7dc 100644 --- a/activesupport/test/core_ext/object/inclusion_test.rb +++ b/activesupport/test/core_ext/object/inclusion_test.rb @@ -46,11 +46,11 @@ class InTest < ActiveSupport::TestCase assert !A.in?(A) assert !A.in?(D) end - + def test_no_method_catching assert_raise(ArgumentError) { 1.in?(1) } end - + def test_presence_in assert_equal "stuff", "stuff".presence_in(%w( lots of stuff )) assert_nil "stuff".presence_in(%w( lots of crap )) diff --git a/activesupport/test/dependencies/conflict.rb b/activesupport/test/dependencies/conflict.rb index e888b7b54c..7eff49bbfa 100644 --- a/activesupport/test/dependencies/conflict.rb +++ b/activesupport/test/dependencies/conflict.rb @@ -1 +1 @@ -Conflict = 1 \ No newline at end of file +Conflict = 1 diff --git a/activesupport/test/dependencies/cross_site_depender.rb b/activesupport/test/dependencies/cross_site_depender.rb index a31015fc5e..fbc3b64f56 100644 --- a/activesupport/test/dependencies/cross_site_depender.rb +++ b/activesupport/test/dependencies/cross_site_depender.rb @@ -1,3 +1,3 @@ class CrossSiteDepender CrossSiteDependency -end \ No newline at end of file +end diff --git a/activesupport/test/dependencies/service_one.rb b/activesupport/test/dependencies/service_one.rb index f43bfea235..afc3042269 100644 --- a/activesupport/test/dependencies/service_one.rb +++ b/activesupport/test/dependencies/service_one.rb @@ -2,4 +2,4 @@ $loaded_service_one ||= 0 $loaded_service_one += 1 class ServiceOne -end \ No newline at end of file +end diff --git a/activesupport/test/dependencies/service_two.rb b/activesupport/test/dependencies/service_two.rb index 5205a78bb8..aabfc3c553 100644 --- a/activesupport/test/dependencies/service_two.rb +++ b/activesupport/test/dependencies/service_two.rb @@ -1,2 +1,2 @@ class ServiceTwo -end \ No newline at end of file +end diff --git a/activesupport/test/dependencies_test_helpers.rb b/activesupport/test/dependencies_test_helpers.rb index 4ee01fda39..9bc63ed89e 100644 --- a/activesupport/test/dependencies_test_helpers.rb +++ b/activesupport/test/dependencies_test_helpers.rb @@ -25,4 +25,4 @@ module DependenciesTestHelpers Object.send(:remove_const, constant) if Object.const_defined?(constant) end end -end \ No newline at end of file +end diff --git a/activesupport/test/descendants_tracker_test_cases.rb b/activesupport/test/descendants_tracker_test_cases.rb index 4fba58bd47..09c5ce1f07 100644 --- a/activesupport/test/descendants_tracker_test_cases.rb +++ b/activesupport/test/descendants_tracker_test_cases.rb @@ -42,24 +42,24 @@ module DescendantsTrackerTestCases protected - def assert_equal_sets(expected, actual) - assert_equal Set.new(expected), Set.new(actual) - end - - def mark_as_autoloaded(*klasses) - # If ActiveSupport::Dependencies is not loaded, forget about autoloading. - # This allows using AS::DescendantsTracker without AS::Dependencies. - if defined? ActiveSupport::Dependencies - old_autoloaded = ActiveSupport::Dependencies.autoloaded_constants.dup - ActiveSupport::Dependencies.autoloaded_constants = klasses.map(&:name) + def assert_equal_sets(expected, actual) + assert_equal Set.new(expected), Set.new(actual) end - old_descendants = ActiveSupport::DescendantsTracker.class_eval("@@direct_descendants").dup - old_descendants.each { |k, v| old_descendants[k] = v.dup } + def mark_as_autoloaded(*klasses) + # If ActiveSupport::Dependencies is not loaded, forget about autoloading. + # This allows using AS::DescendantsTracker without AS::Dependencies. + if defined? ActiveSupport::Dependencies + old_autoloaded = ActiveSupport::Dependencies.autoloaded_constants.dup + ActiveSupport::Dependencies.autoloaded_constants = klasses.map(&:name) + end + + old_descendants = ActiveSupport::DescendantsTracker.class_eval("@@direct_descendants").dup + old_descendants.each { |k, v| old_descendants[k] = v.dup } - yield - ensure - ActiveSupport::Dependencies.autoloaded_constants = old_autoloaded if defined? ActiveSupport::Dependencies - ActiveSupport::DescendantsTracker.class_eval("@@direct_descendants").replace(old_descendants) - end + yield + ensure + ActiveSupport::Dependencies.autoloaded_constants = old_autoloaded if defined? ActiveSupport::Dependencies + ActiveSupport::DescendantsTracker.class_eval("@@direct_descendants").replace(old_descendants) + end end diff --git a/activesupport/test/fixtures/autoload/another_class.rb b/activesupport/test/fixtures/autoload/another_class.rb index a240b3de41..ab6e075ab4 100644 --- a/activesupport/test/fixtures/autoload/another_class.rb +++ b/activesupport/test/fixtures/autoload/another_class.rb @@ -1,2 +1,2 @@ class Fixtures::AnotherClass -end \ No newline at end of file +end diff --git a/activesupport/test/fixtures/autoload/some_class.rb b/activesupport/test/fixtures/autoload/some_class.rb index 13b3c73ef5..30d41eb0bf 100644 --- a/activesupport/test/fixtures/autoload/some_class.rb +++ b/activesupport/test/fixtures/autoload/some_class.rb @@ -1,2 +1,2 @@ class Fixtures::Autoload::SomeClass -end \ No newline at end of file +end diff --git a/activesupport/test/inflector_test_cases.rb b/activesupport/test/inflector_test_cases.rb index 4ee723076e..a8283301b3 100644 --- a/activesupport/test/inflector_test_cases.rb +++ b/activesupport/test/inflector_test_cases.rb @@ -176,12 +176,12 @@ module InflectorTestCases StringToParameterizedPreserveCase = { "Donald E. Knuth" => "Donald-E-Knuth", - "Random text with *(bad)* characters" => "Random-text-with-bad-characters", - "Allow_Under_Scores" => "Allow_Under_Scores", - "Trailing bad characters!@#" => "Trailing-bad-characters", - "!@#Leading bad characters" => "Leading-bad-characters", - "Squeeze separators" => "Squeeze-separators", - "Test with + sign" => "Test-with-sign", + "Random text with *(bad)* characters" => "Random-text-with-bad-characters", + "Allow_Under_Scores" => "Allow_Under_Scores", + "Trailing bad characters!@#" => "Trailing-bad-characters", + "!@#Leading bad characters" => "Leading-bad-characters", + "Squeeze separators" => "Squeeze-separators", + "Test with + sign" => "Test-with-sign", "Test with malformed utf8 \xA9" => "Test-with-malformed-utf8" } @@ -199,11 +199,11 @@ module InflectorTestCases StringToParameterizePreserveCaseWithNoSeparator = { "Donald E. Knuth" => "DonaldEKnuth", "With-some-dashes" => "With-some-dashes", - "Random text with *(bad)* characters" => "Randomtextwithbadcharacters", - "Trailing bad characters!@#" => "Trailingbadcharacters", - "!@#Leading bad characters" => "Leadingbadcharacters", - "Squeeze separators" => "Squeezeseparators", - "Test with + sign" => "Testwithsign", + "Random text with *(bad)* characters" => "Randomtextwithbadcharacters", + "Trailing bad characters!@#" => "Trailingbadcharacters", + "!@#Leading bad characters" => "Leadingbadcharacters", + "Squeeze separators" => "Squeezeseparators", + "Test with + sign" => "Testwithsign", "Test with malformed utf8 \xA9" => "Testwithmalformedutf8" } @@ -220,14 +220,14 @@ module InflectorTestCases } StringToParameterizePreserceCaseWithUnderscore = { - "Donald E. Knuth" => "Donald_E_Knuth", + "Donald E. Knuth" => "Donald_E_Knuth", "Random text with *(bad)* characters" => "Random_text_with_bad_characters", - "With-some-dashes" => "With-some-dashes", - "Allow_Under_Scores" => "Allow_Under_Scores", - "Trailing bad characters!@#" => "Trailing_bad_characters", - "!@#Leading bad characters" => "Leading_bad_characters", - "Squeeze separators" => "Squeeze_separators", - "Test with + sign" => "Test_with_sign", + "With-some-dashes" => "With-some-dashes", + "Allow_Under_Scores" => "Allow_Under_Scores", + "Trailing bad characters!@#" => "Trailing_bad_characters", + "!@#Leading bad characters" => "Leading_bad_characters", + "Squeeze separators" => "Squeeze_separators", + "Test with + sign" => "Test_with_sign", "Test with malformed utf8 \xA9" => "Test_with_malformed_utf8" } diff --git a/activesupport/test/json/decoding_test.rb b/activesupport/test/json/decoding_test.rb index 04eb10aafe..97cc508268 100644 --- a/activesupport/test/json/decoding_test.rb +++ b/activesupport/test/json/decoding_test.rb @@ -107,12 +107,11 @@ class TestJSONDecoding < ActiveSupport::TestCase private - def with_parse_json_times(value) - old_value = ActiveSupport.parse_json_times - ActiveSupport.parse_json_times = value - yield - ensure - ActiveSupport.parse_json_times = old_value - end + def with_parse_json_times(value) + old_value = ActiveSupport.parse_json_times + ActiveSupport.parse_json_times = value + yield + ensure + ActiveSupport.parse_json_times = old_value + end end - diff --git a/activesupport/test/key_generator_test.rb b/activesupport/test/key_generator_test.rb index 705537007a..89db9563ac 100644 --- a/activesupport/test/key_generator_test.rb +++ b/activesupport/test/key_generator_test.rb @@ -7,71 +7,71 @@ rescue LoadError, NameError $stderr.puts "Skipping KeyGenerator test: broken OpenSSL install" else -require "active_support/time" -require "active_support/json" - -class KeyGeneratorTest < ActiveSupport::TestCase - def setup - @secret = SecureRandom.hex(64) - @generator = ActiveSupport::KeyGenerator.new(@secret, iterations: 2) - end - - test "Generating a key of the default length" do - derived_key = @generator.generate_key("some_salt") - assert_kind_of String, derived_key - assert_equal 64, derived_key.length, "Should have generated a key of the default size" - end - - test "Generating a key of an alternative length" do - derived_key = @generator.generate_key("some_salt", 32) - assert_kind_of String, derived_key - assert_equal 32, derived_key.length, "Should have generated a key of the right size" + require "active_support/time" + require "active_support/json" + + class KeyGeneratorTest < ActiveSupport::TestCase + def setup + @secret = SecureRandom.hex(64) + @generator = ActiveSupport::KeyGenerator.new(@secret, iterations: 2) + end + + test "Generating a key of the default length" do + derived_key = @generator.generate_key("some_salt") + assert_kind_of String, derived_key + assert_equal 64, derived_key.length, "Should have generated a key of the default size" + end + + test "Generating a key of an alternative length" do + derived_key = @generator.generate_key("some_salt", 32) + assert_kind_of String, derived_key + assert_equal 32, derived_key.length, "Should have generated a key of the right size" + end + + test "Expected results" do + # For any given set of inputs, this method must continue to return + # the same output: if it changes, any existing values relying on a + # key would break. + + expected = "b129376f68f1ecae788d7433310249d65ceec090ecacd4c872a3a9e9ec78e055739be5cc6956345d5ae38e7e1daa66f1de587dc8da2bf9e8b965af4b3918a122" + assert_equal expected, ActiveSupport::KeyGenerator.new("0" * 64).generate_key("some_salt").unpack("H*").first + + expected = "b129376f68f1ecae788d7433310249d65ceec090ecacd4c872a3a9e9ec78e055" + assert_equal expected, ActiveSupport::KeyGenerator.new("0" * 64).generate_key("some_salt", 32).unpack("H*").first + + expected = "cbea7f7f47df705967dc508f4e446fd99e7797b1d70011c6899cd39bbe62907b8508337d678505a7dc8184e037f1003ba3d19fc5d829454668e91d2518692eae" + assert_equal expected, ActiveSupport::KeyGenerator.new("0" * 64, iterations: 2).generate_key("some_salt").unpack("H*").first + end end - test "Expected results" do - # For any given set of inputs, this method must continue to return - # the same output: if it changes, any existing values relying on a - # key would break. + class CachingKeyGeneratorTest < ActiveSupport::TestCase + def setup + @secret = SecureRandom.hex(64) + @generator = ActiveSupport::KeyGenerator.new(@secret, iterations: 2) + @caching_generator = ActiveSupport::CachingKeyGenerator.new(@generator) + end - expected = "b129376f68f1ecae788d7433310249d65ceec090ecacd4c872a3a9e9ec78e055739be5cc6956345d5ae38e7e1daa66f1de587dc8da2bf9e8b965af4b3918a122" - assert_equal expected, ActiveSupport::KeyGenerator.new("0" * 64).generate_key("some_salt").unpack("H*").first + test "Generating a cached key for same salt and key size" do + derived_key = @caching_generator.generate_key("some_salt", 32) + cached_key = @caching_generator.generate_key("some_salt", 32) - expected = "b129376f68f1ecae788d7433310249d65ceec090ecacd4c872a3a9e9ec78e055" - assert_equal expected, ActiveSupport::KeyGenerator.new("0" * 64).generate_key("some_salt", 32).unpack("H*").first + assert_equal derived_key, cached_key + assert_equal derived_key.object_id, cached_key.object_id + end - expected = "cbea7f7f47df705967dc508f4e446fd99e7797b1d70011c6899cd39bbe62907b8508337d678505a7dc8184e037f1003ba3d19fc5d829454668e91d2518692eae" - assert_equal expected, ActiveSupport::KeyGenerator.new("0" * 64, iterations: 2).generate_key("some_salt").unpack("H*").first - end -end + test "Does not cache key for different salt" do + derived_key = @caching_generator.generate_key("some_salt", 32) + different_salt_key = @caching_generator.generate_key("other_salt", 32) -class CachingKeyGeneratorTest < ActiveSupport::TestCase - def setup - @secret = SecureRandom.hex(64) - @generator = ActiveSupport::KeyGenerator.new(@secret, iterations: 2) - @caching_generator = ActiveSupport::CachingKeyGenerator.new(@generator) - end + assert_not_equal derived_key, different_salt_key + end - test "Generating a cached key for same salt and key size" do - derived_key = @caching_generator.generate_key("some_salt", 32) - cached_key = @caching_generator.generate_key("some_salt", 32) + test "Does not cache key for different length" do + derived_key = @caching_generator.generate_key("some_salt", 32) + different_length_key = @caching_generator.generate_key("some_salt", 64) - assert_equal derived_key, cached_key - assert_equal derived_key.object_id, cached_key.object_id + assert_not_equal derived_key, different_length_key + end end - test "Does not cache key for different salt" do - derived_key = @caching_generator.generate_key("some_salt", 32) - different_salt_key = @caching_generator.generate_key("other_salt", 32) - - assert_not_equal derived_key, different_salt_key - end - - test "Does not cache key for different length" do - derived_key = @caching_generator.generate_key("some_salt", 32) - different_length_key = @caching_generator.generate_key("some_salt", 64) - - assert_not_equal derived_key, different_length_key - end -end - end diff --git a/activesupport/test/lazy_load_hooks_test.rb b/activesupport/test/lazy_load_hooks_test.rb index d08efa429a..3b1959a1c9 100644 --- a/activesupport/test/lazy_load_hooks_test.rb +++ b/activesupport/test/lazy_load_hooks_test.rb @@ -93,4 +93,4 @@ private @incr = incr end end -end \ No newline at end of file +end diff --git a/activesupport/test/message_encryptor_test.rb b/activesupport/test/message_encryptor_test.rb index a4976fa1ea..fb0b1e377d 100644 --- a/activesupport/test/message_encryptor_test.rb +++ b/activesupport/test/message_encryptor_test.rb @@ -90,21 +90,21 @@ class MessageEncryptorTest < ActiveSupport::TestCase private - def assert_not_decrypted(value) - assert_raise(ActiveSupport::MessageEncryptor::InvalidMessage) do - @encryptor.decrypt_and_verify(@verifier.generate(value)) + def assert_not_decrypted(value) + assert_raise(ActiveSupport::MessageEncryptor::InvalidMessage) do + @encryptor.decrypt_and_verify(@verifier.generate(value)) + end end - end - def assert_not_verified(value) - assert_raise(ActiveSupport::MessageVerifier::InvalidSignature) do - @encryptor.decrypt_and_verify(value) + def assert_not_verified(value) + assert_raise(ActiveSupport::MessageVerifier::InvalidSignature) do + @encryptor.decrypt_and_verify(value) + end end - end - def munge(base64_string) - bits = ::Base64.strict_decode64(base64_string) - bits.reverse! - ::Base64.strict_encode64(bits) - end + def munge(base64_string) + bits = ::Base64.strict_decode64(base64_string) + bits.reverse! + ::Base64.strict_encode64(bits) + end end diff --git a/activesupport/test/multibyte_chars_test.rb b/activesupport/test/multibyte_chars_test.rb index 81f05dcd5b..9ca9c7c803 100644 --- a/activesupport/test/multibyte_chars_test.rb +++ b/activesupport/test/multibyte_chars_test.rb @@ -513,7 +513,7 @@ class MultibyteCharsExtrasTest < ActiveSupport::TestCase "аБвг АБВГ" => "Абвг абвг", "АБВГ АБВГ" => "Абвг абвг", "" => "" }.each do |f,t| - assert_equal t, chars(f).capitalize + assert_equal t, chars(f).capitalize end end @@ -720,16 +720,16 @@ class MultibyteCharsExtrasTest < ActiveSupport::TestCase private - def string_from_classes(classes) - # Characters from the character classes as described in UAX #29 - character_from_class = { - l: 0x1100, v: 0x1160, t: 0x11A8, lv: 0xAC00, lvt: 0xAC01, cr: 0x000D, lf: 0x000A, - extend: 0x094D, n: 0x64, spacingmark: 0x0903, r: 0x1F1E6, control: 0x0001 - } - classes.collect do |k| - character_from_class[k.intern] - end.pack("U*") - end + def string_from_classes(classes) + # Characters from the character classes as described in UAX #29 + character_from_class = { + l: 0x1100, v: 0x1160, t: 0x11A8, lv: 0xAC00, lvt: 0xAC01, cr: 0x000D, lf: 0x000A, + extend: 0x094D, n: 0x64, spacingmark: 0x0903, r: 0x1F1E6, control: 0x0001 + } + classes.collect do |k| + character_from_class[k.intern] + end.pack("U*") + end end class MultibyteInternalsTest < ActiveSupport::TestCase diff --git a/activesupport/test/share_lock_test.rb b/activesupport/test/share_lock_test.rb index 168ead2401..8155d46934 100644 --- a/activesupport/test/share_lock_test.rb +++ b/activesupport/test/share_lock_test.rb @@ -489,90 +489,90 @@ class ShareLockTest < ActiveSupport::TestCase private - module CustomAssertions - SUFFICIENT_TIMEOUT = 0.2 + module CustomAssertions + SUFFICIENT_TIMEOUT = 0.2 - private + private - def assert_threads_stuck_but_releasable_by_latch(threads, latch) - assert_threads_stuck threads - latch.count_down - assert_threads_not_stuck threads - end + def assert_threads_stuck_but_releasable_by_latch(threads, latch) + assert_threads_stuck threads + latch.count_down + assert_threads_not_stuck threads + end - def assert_threads_stuck(threads) - sleep(SUFFICIENT_TIMEOUT) # give threads time to do their business - assert(Array(threads).all? { |t| t.join(0.001).nil? }) - end + def assert_threads_stuck(threads) + sleep(SUFFICIENT_TIMEOUT) # give threads time to do their business + assert(Array(threads).all? { |t| t.join(0.001).nil? }) + end - def assert_threads_not_stuck(threads) - assert(Array(threads).all? { |t| t.join(SUFFICIENT_TIMEOUT) }) + def assert_threads_not_stuck(threads) + assert(Array(threads).all? { |t| t.join(SUFFICIENT_TIMEOUT) }) + end end - end - class CustomAssertionsTest < ActiveSupport::TestCase - include CustomAssertions + class CustomAssertionsTest < ActiveSupport::TestCase + include CustomAssertions - def setup - @latch = Concurrent::CountDownLatch.new - @thread = Thread.new { @latch.wait } - end + def setup + @latch = Concurrent::CountDownLatch.new + @thread = Thread.new { @latch.wait } + end - def teardown - @latch.count_down - @thread.join - end + def teardown + @latch.count_down + @thread.join + end - def test_happy_path - assert_threads_stuck_but_releasable_by_latch @thread, @latch - end + def test_happy_path + assert_threads_stuck_but_releasable_by_latch @thread, @latch + end - def test_detects_stuck_thread - assert_raises(Minitest::Assertion) do - assert_threads_not_stuck @thread + def test_detects_stuck_thread + assert_raises(Minitest::Assertion) do + assert_threads_not_stuck @thread + end end - end - def test_detects_free_thread - @latch.count_down - assert_raises(Minitest::Assertion) do - assert_threads_stuck @thread + def test_detects_free_thread + @latch.count_down + assert_raises(Minitest::Assertion) do + assert_threads_stuck @thread + end end - end - def test_detects_already_released - @latch.count_down - assert_raises(Minitest::Assertion) do - assert_threads_stuck_but_releasable_by_latch @thread, @latch + def test_detects_already_released + @latch.count_down + assert_raises(Minitest::Assertion) do + assert_threads_stuck_but_releasable_by_latch @thread, @latch + end end - end - def test_detects_remains_latched - another_latch = Concurrent::CountDownLatch.new - assert_raises(Minitest::Assertion) do - assert_threads_stuck_but_releasable_by_latch @thread, another_latch + def test_detects_remains_latched + another_latch = Concurrent::CountDownLatch.new + assert_raises(Minitest::Assertion) do + assert_threads_stuck_but_releasable_by_latch @thread, another_latch + end end end - end - include CustomAssertions + include CustomAssertions - def with_thread_waiting_in_lock_section(lock_section) - in_section = Concurrent::CountDownLatch.new - section_release = Concurrent::CountDownLatch.new + def with_thread_waiting_in_lock_section(lock_section) + in_section = Concurrent::CountDownLatch.new + section_release = Concurrent::CountDownLatch.new - stuck_thread = Thread.new do - @lock.send(lock_section) do - in_section.count_down - section_release.wait + stuck_thread = Thread.new do + @lock.send(lock_section) do + in_section.count_down + section_release.wait + end end - end - in_section.wait + in_section.wait - yield section_release - ensure - section_release.count_down - stuck_thread.join # clean up - end + yield section_release + ensure + section_release.count_down + stuck_thread.join # clean up + end end diff --git a/activesupport/test/subscriber_test.rb b/activesupport/test/subscriber_test.rb index 5ec8affc9b..9127da35d4 100644 --- a/activesupport/test/subscriber_test.rb +++ b/activesupport/test/subscriber_test.rb @@ -16,9 +16,9 @@ class TestSubscriber < ActiveSupport::Subscriber private - def private_party(event) - events << event - end + def private_party(event) + events << event + end end # Monkey patch subscriber to test that only one subscriber per method is added. diff --git a/activesupport/test/xml_mini/jdom_engine_test.rb b/activesupport/test/xml_mini/jdom_engine_test.rb index fea3711c37..43edd49663 100644 --- a/activesupport/test/xml_mini/jdom_engine_test.rb +++ b/activesupport/test/xml_mini/jdom_engine_test.rb @@ -19,18 +19,18 @@ if RUBY_PLATFORM.include?("java") end def test_file_from_xml - hash = Hash.from_xml(<<-eoxml) + hash = Hash.from_xml(<<-eoxml) eoxml - assert hash.has_key?("blog") - assert hash["blog"].has_key?("logo") + assert hash.has_key?("blog") + assert hash["blog"].has_key?("logo") - file = hash["blog"]["logo"] - assert_equal "logo.png", file.original_filename - assert_equal "image/png", file.content_type + file = hash["blog"]["logo"] + assert_equal "logo.png", file.original_filename + assert_equal "image/png", file.content_type end def test_not_allowed_to_expand_entities_to_files diff --git a/activesupport/test/xml_mini/libxml_engine_test.rb b/activesupport/test/xml_mini/libxml_engine_test.rb index c40145ae5f..d5fd17d06e 100644 --- a/activesupport/test/xml_mini/libxml_engine_test.rb +++ b/activesupport/test/xml_mini/libxml_engine_test.rb @@ -3,56 +3,56 @@ begin rescue LoadError # Skip libxml tests else -require "abstract_unit" -require "active_support/xml_mini" -require "active_support/core_ext/hash/conversions" + require "abstract_unit" + require "active_support/xml_mini" + require "active_support/core_ext/hash/conversions" -class LibxmlEngineTest < ActiveSupport::TestCase - include ActiveSupport + class LibxmlEngineTest < ActiveSupport::TestCase + include ActiveSupport - def setup - @default_backend = XmlMini.backend - XmlMini.backend = "LibXML" + def setup + @default_backend = XmlMini.backend + XmlMini.backend = "LibXML" - LibXML::XML::Error.set_handler(&lambda { |error| }) #silence libxml, exceptions will do - end + LibXML::XML::Error.set_handler(&lambda { |error| }) #silence libxml, exceptions will do + end - def teardown - XmlMini.backend = @default_backend - end + def teardown + XmlMini.backend = @default_backend + end - def test_exception_thrown_on_expansion_attack - assert_raise LibXML::XML::Error do - attack_xml = %{ - - - - - - - - ]> - - &a; - - } - Hash.from_xml(attack_xml) + def test_exception_thrown_on_expansion_attack + assert_raise LibXML::XML::Error do + attack_xml = %{ + + + + + + + + ]> + + &a; + + } + Hash.from_xml(attack_xml) + end end - end - def test_setting_libxml_as_backend - XmlMini.backend = "LibXML" - assert_equal XmlMini_LibXML, XmlMini.backend - end + def test_setting_libxml_as_backend + XmlMini.backend = "LibXML" + assert_equal XmlMini_LibXML, XmlMini.backend + end - def test_blank_returns_empty_hash - assert_equal({}, XmlMini.parse(nil)) - assert_equal({}, XmlMini.parse("")) - end + def test_blank_returns_empty_hash + assert_equal({}, XmlMini.parse(nil)) + assert_equal({}, XmlMini.parse("")) + end - def test_array_type_makes_an_array - assert_equal_rexml(<<-eoxml) + def test_array_type_makes_an_array + assert_equal_rexml(<<-eoxml) a post @@ -60,67 +60,67 @@ class LibxmlEngineTest < ActiveSupport::TestCase eoxml - end + end - def test_one_node_document_as_hash - assert_equal_rexml(<<-eoxml) - - eoxml - end + def test_one_node_document_as_hash + assert_equal_rexml(<<-eoxml) + + eoxml + end - def test_one_node_with_attributes_document_as_hash - assert_equal_rexml(<<-eoxml) - - eoxml - end + def test_one_node_with_attributes_document_as_hash + assert_equal_rexml(<<-eoxml) + + eoxml + end - def test_products_node_with_book_node_as_hash - assert_equal_rexml(<<-eoxml) + def test_products_node_with_book_node_as_hash + assert_equal_rexml(<<-eoxml) eoxml - end + end - def test_products_node_with_two_book_nodes_as_hash - assert_equal_rexml(<<-eoxml) + def test_products_node_with_two_book_nodes_as_hash + assert_equal_rexml(<<-eoxml) eoxml - end + end - def test_single_node_with_content_as_hash - assert_equal_rexml(<<-eoxml) + def test_single_node_with_content_as_hash + assert_equal_rexml(<<-eoxml) hello world eoxml - end + end - def test_children_with_children - assert_equal_rexml(<<-eoxml) + def test_children_with_children + assert_equal_rexml(<<-eoxml) eoxml - end + end - def test_children_with_text - assert_equal_rexml(<<-eoxml) + def test_children_with_text + assert_equal_rexml(<<-eoxml) hello everyone eoxml - end + end - def test_children_with_non_adjacent_text - assert_equal_rexml(<<-eoxml) + def test_children_with_non_adjacent_text + assert_equal_rexml(<<-eoxml) good @@ -129,10 +129,10 @@ class LibxmlEngineTest < ActiveSupport::TestCase morning eoxml - end + end - def test_parse_from_io - io = StringIO.new(<<-eoxml) + def test_parse_from_io + io = StringIO.new(<<-eoxml) good @@ -141,31 +141,31 @@ class LibxmlEngineTest < ActiveSupport::TestCase morning eoxml - assert_equal_rexml(io) - end + assert_equal_rexml(io) + end - def test_children_with_simple_cdata - assert_equal_rexml(<<-eoxml) + def test_children_with_simple_cdata + assert_equal_rexml(<<-eoxml) eoxml - end + end - def test_children_with_multiple_cdata - assert_equal_rexml(<<-eoxml) + def test_children_with_multiple_cdata + assert_equal_rexml(<<-eoxml) eoxml - end + end - def test_children_with_text_and_cdata - assert_equal_rexml(<<-eoxml) + def test_children_with_text_and_cdata + assert_equal_rexml(<<-eoxml) hello @@ -173,32 +173,32 @@ class LibxmlEngineTest < ActiveSupport::TestCase eoxml - end + end - def test_children_with_blank_text - assert_equal_rexml(<<-eoxml) + def test_children_with_blank_text + assert_equal_rexml(<<-eoxml) eoxml - end + end - def test_children_with_blank_text_and_attribute - assert_equal_rexml(<<-eoxml) + def test_children_with_blank_text_and_attribute + assert_equal_rexml(<<-eoxml) eoxml - end + end - private - def assert_equal_rexml(xml) - parsed_xml = XmlMini.parse(xml) - xml.rewind if xml.respond_to?(:rewind) - hash = XmlMini.with_backend("REXML") { XmlMini.parse(xml) } - assert_equal(hash, parsed_xml) - end -end + private + def assert_equal_rexml(xml) + parsed_xml = XmlMini.parse(xml) + xml.rewind if xml.respond_to?(:rewind) + hash = XmlMini.with_backend("REXML") { XmlMini.parse(xml) } + assert_equal(hash, parsed_xml) + end + end end diff --git a/activesupport/test/xml_mini/libxmlsax_engine_test.rb b/activesupport/test/xml_mini/libxmlsax_engine_test.rb index a92cd9da8c..e25fa2813c 100644 --- a/activesupport/test/xml_mini/libxmlsax_engine_test.rb +++ b/activesupport/test/xml_mini/libxmlsax_engine_test.rb @@ -3,25 +3,25 @@ begin rescue LoadError # Skip libxml tests else -require "abstract_unit" -require "active_support/xml_mini" -require "active_support/core_ext/hash/conversions" + require "abstract_unit" + require "active_support/xml_mini" + require "active_support/core_ext/hash/conversions" -class LibXMLSAXEngineTest < ActiveSupport::TestCase - include ActiveSupport + class LibXMLSAXEngineTest < ActiveSupport::TestCase + include ActiveSupport - def setup - @default_backend = XmlMini.backend - XmlMini.backend = "LibXMLSAX" - end + def setup + @default_backend = XmlMini.backend + XmlMini.backend = "LibXMLSAX" + end - def teardown - XmlMini.backend = @default_backend - end + def teardown + XmlMini.backend = @default_backend + end - def test_exception_thrown_on_expansion_attack - assert_raise LibXML::XML::Error do - attack_xml = <<-EOT + def test_exception_thrown_on_expansion_attack + assert_raise LibXML::XML::Error do + attack_xml = <<-EOT @@ -37,22 +37,22 @@ class LibXMLSAXEngineTest < ActiveSupport::TestCase EOT - Hash.from_xml(attack_xml) + Hash.from_xml(attack_xml) + end end - end - def test_setting_libxml_as_backend - XmlMini.backend = "LibXMLSAX" - assert_equal XmlMini_LibXMLSAX, XmlMini.backend - end + def test_setting_libxml_as_backend + XmlMini.backend = "LibXMLSAX" + assert_equal XmlMini_LibXMLSAX, XmlMini.backend + end - def test_blank_returns_empty_hash - assert_equal({}, XmlMini.parse(nil)) - assert_equal({}, XmlMini.parse("")) - end + def test_blank_returns_empty_hash + assert_equal({}, XmlMini.parse(nil)) + assert_equal({}, XmlMini.parse("")) + end - def test_array_type_makes_an_array - assert_equal_rexml(<<-eoxml) + def test_array_type_makes_an_array + assert_equal_rexml(<<-eoxml) a post @@ -60,67 +60,67 @@ class LibXMLSAXEngineTest < ActiveSupport::TestCase eoxml - end + end - def test_one_node_document_as_hash - assert_equal_rexml(<<-eoxml) - - eoxml - end + def test_one_node_document_as_hash + assert_equal_rexml(<<-eoxml) + + eoxml + end - def test_one_node_with_attributes_document_as_hash - assert_equal_rexml(<<-eoxml) - - eoxml - end + def test_one_node_with_attributes_document_as_hash + assert_equal_rexml(<<-eoxml) + + eoxml + end - def test_products_node_with_book_node_as_hash - assert_equal_rexml(<<-eoxml) + def test_products_node_with_book_node_as_hash + assert_equal_rexml(<<-eoxml) eoxml - end + end - def test_products_node_with_two_book_nodes_as_hash - assert_equal_rexml(<<-eoxml) + def test_products_node_with_two_book_nodes_as_hash + assert_equal_rexml(<<-eoxml) eoxml - end + end - def test_single_node_with_content_as_hash - assert_equal_rexml(<<-eoxml) + def test_single_node_with_content_as_hash + assert_equal_rexml(<<-eoxml) hello world eoxml - end + end - def test_children_with_children - assert_equal_rexml(<<-eoxml) + def test_children_with_children + assert_equal_rexml(<<-eoxml) eoxml - end + end - def test_children_with_text - assert_equal_rexml(<<-eoxml) + def test_children_with_text + assert_equal_rexml(<<-eoxml) hello everyone eoxml - end + end - def test_children_with_non_adjacent_text - assert_equal_rexml(<<-eoxml) + def test_children_with_non_adjacent_text + assert_equal_rexml(<<-eoxml) good @@ -129,10 +129,10 @@ class LibXMLSAXEngineTest < ActiveSupport::TestCase morning eoxml - end + end - def test_parse_from_io - io = StringIO.new(<<-eoxml) + def test_parse_from_io + io = StringIO.new(<<-eoxml) good @@ -141,31 +141,31 @@ class LibXMLSAXEngineTest < ActiveSupport::TestCase morning eoxml - assert_equal_rexml(io) - end + assert_equal_rexml(io) + end - def test_children_with_simple_cdata - assert_equal_rexml(<<-eoxml) + def test_children_with_simple_cdata + assert_equal_rexml(<<-eoxml) eoxml - end + end - def test_children_with_multiple_cdata - assert_equal_rexml(<<-eoxml) + def test_children_with_multiple_cdata + assert_equal_rexml(<<-eoxml) eoxml - end + end - def test_children_with_text_and_cdata - assert_equal_rexml(<<-eoxml) + def test_children_with_text_and_cdata + assert_equal_rexml(<<-eoxml) hello @@ -173,23 +173,23 @@ class LibXMLSAXEngineTest < ActiveSupport::TestCase eoxml - end + end - def test_children_with_blank_text - assert_equal_rexml(<<-eoxml) + def test_children_with_blank_text + assert_equal_rexml(<<-eoxml) eoxml - end - - private - def assert_equal_rexml(xml) - parsed_xml = XmlMini.parse(xml) - xml.rewind if xml.respond_to?(:rewind) - hash = XmlMini.with_backend("REXML") { XmlMini.parse(xml) } - assert_equal(hash, parsed_xml) end -end + + private + def assert_equal_rexml(xml) + parsed_xml = XmlMini.parse(xml) + xml.rewind if xml.respond_to?(:rewind) + hash = XmlMini.with_backend("REXML") { XmlMini.parse(xml) } + assert_equal(hash, parsed_xml) + end + end end diff --git a/activesupport/test/xml_mini/nokogiri_engine_test.rb b/activesupport/test/xml_mini/nokogiri_engine_test.rb index dd169e7eb4..44b82da4e4 100644 --- a/activesupport/test/xml_mini/nokogiri_engine_test.rb +++ b/activesupport/test/xml_mini/nokogiri_engine_test.rb @@ -3,38 +3,38 @@ begin rescue LoadError # Skip nokogiri tests else -require "abstract_unit" -require "active_support/xml_mini" -require "active_support/core_ext/hash/conversions" - -class NokogiriEngineTest < ActiveSupport::TestCase - def setup - @default_backend = ActiveSupport::XmlMini.backend - ActiveSupport::XmlMini.backend = "Nokogiri" - end + require "abstract_unit" + require "active_support/xml_mini" + require "active_support/core_ext/hash/conversions" + + class NokogiriEngineTest < ActiveSupport::TestCase + def setup + @default_backend = ActiveSupport::XmlMini.backend + ActiveSupport::XmlMini.backend = "Nokogiri" + end - def teardown - ActiveSupport::XmlMini.backend = @default_backend - end + def teardown + ActiveSupport::XmlMini.backend = @default_backend + end - def test_file_from_xml - hash = Hash.from_xml(<<-eoxml) + def test_file_from_xml + hash = Hash.from_xml(<<-eoxml) eoxml - assert hash.has_key?("blog") - assert hash["blog"].has_key?("logo") + assert hash.has_key?("blog") + assert hash["blog"].has_key?("logo") - file = hash["blog"]["logo"] - assert_equal "logo.png", file.original_filename - assert_equal "image/png", file.content_type - end + file = hash["blog"]["logo"] + assert_equal "logo.png", file.original_filename + assert_equal "image/png", file.content_type + end - def test_exception_thrown_on_expansion_attack - assert_raise Nokogiri::XML::SyntaxError do - attack_xml = <<-EOT + def test_exception_thrown_on_expansion_attack + assert_raise Nokogiri::XML::SyntaxError do + attack_xml = <<-EOT @@ -49,22 +49,22 @@ class NokogiriEngineTest < ActiveSupport::TestCase &a; EOT - Hash.from_xml(attack_xml) + Hash.from_xml(attack_xml) + end end - end - def test_setting_nokogiri_as_backend - ActiveSupport::XmlMini.backend = "Nokogiri" - assert_equal ActiveSupport::XmlMini_Nokogiri, ActiveSupport::XmlMini.backend - end + def test_setting_nokogiri_as_backend + ActiveSupport::XmlMini.backend = "Nokogiri" + assert_equal ActiveSupport::XmlMini_Nokogiri, ActiveSupport::XmlMini.backend + end - def test_blank_returns_empty_hash - assert_equal({}, ActiveSupport::XmlMini.parse(nil)) - assert_equal({}, ActiveSupport::XmlMini.parse("")) - end + def test_blank_returns_empty_hash + assert_equal({}, ActiveSupport::XmlMini.parse(nil)) + assert_equal({}, ActiveSupport::XmlMini.parse("")) + end - def test_array_type_makes_an_array - assert_equal_rexml(<<-eoxml) + def test_array_type_makes_an_array + assert_equal_rexml(<<-eoxml) a post @@ -72,67 +72,67 @@ class NokogiriEngineTest < ActiveSupport::TestCase eoxml - end + end - def test_one_node_document_as_hash - assert_equal_rexml(<<-eoxml) - - eoxml - end + def test_one_node_document_as_hash + assert_equal_rexml(<<-eoxml) + + eoxml + end - def test_one_node_with_attributes_document_as_hash - assert_equal_rexml(<<-eoxml) - - eoxml - end + def test_one_node_with_attributes_document_as_hash + assert_equal_rexml(<<-eoxml) + + eoxml + end - def test_products_node_with_book_node_as_hash - assert_equal_rexml(<<-eoxml) + def test_products_node_with_book_node_as_hash + assert_equal_rexml(<<-eoxml) eoxml - end + end - def test_products_node_with_two_book_nodes_as_hash - assert_equal_rexml(<<-eoxml) + def test_products_node_with_two_book_nodes_as_hash + assert_equal_rexml(<<-eoxml) eoxml - end + end - def test_single_node_with_content_as_hash - assert_equal_rexml(<<-eoxml) + def test_single_node_with_content_as_hash + assert_equal_rexml(<<-eoxml) hello world eoxml - end + end - def test_children_with_children - assert_equal_rexml(<<-eoxml) + def test_children_with_children + assert_equal_rexml(<<-eoxml) eoxml - end + end - def test_children_with_text - assert_equal_rexml(<<-eoxml) + def test_children_with_text + assert_equal_rexml(<<-eoxml) hello everyone eoxml - end + end - def test_children_with_non_adjacent_text - assert_equal_rexml(<<-eoxml) + def test_children_with_non_adjacent_text + assert_equal_rexml(<<-eoxml) good @@ -141,10 +141,10 @@ class NokogiriEngineTest < ActiveSupport::TestCase morning eoxml - end + end - def test_parse_from_io - io = StringIO.new(<<-eoxml) + def test_parse_from_io + io = StringIO.new(<<-eoxml) good @@ -153,31 +153,31 @@ class NokogiriEngineTest < ActiveSupport::TestCase morning eoxml - assert_equal_rexml(io) - end + assert_equal_rexml(io) + end - def test_children_with_simple_cdata - assert_equal_rexml(<<-eoxml) + def test_children_with_simple_cdata + assert_equal_rexml(<<-eoxml) eoxml - end + end - def test_children_with_multiple_cdata - assert_equal_rexml(<<-eoxml) + def test_children_with_multiple_cdata + assert_equal_rexml(<<-eoxml) eoxml - end + end - def test_children_with_text_and_cdata - assert_equal_rexml(<<-eoxml) + def test_children_with_text_and_cdata + assert_equal_rexml(<<-eoxml) hello @@ -185,31 +185,31 @@ class NokogiriEngineTest < ActiveSupport::TestCase eoxml - end + end - def test_children_with_blank_text - assert_equal_rexml(<<-eoxml) + def test_children_with_blank_text + assert_equal_rexml(<<-eoxml) eoxml - end + end - def test_children_with_blank_text_and_attribute - assert_equal_rexml(<<-eoxml) + def test_children_with_blank_text_and_attribute + assert_equal_rexml(<<-eoxml) eoxml - end - - private - def assert_equal_rexml(xml) - parsed_xml = ActiveSupport::XmlMini.parse(xml) - xml.rewind if xml.respond_to?(:rewind) - hash = ActiveSupport::XmlMini.with_backend("REXML") { ActiveSupport::XmlMini.parse(xml) } - assert_equal(hash, parsed_xml) end -end + + private + def assert_equal_rexml(xml) + parsed_xml = ActiveSupport::XmlMini.parse(xml) + xml.rewind if xml.respond_to?(:rewind) + hash = ActiveSupport::XmlMini.with_backend("REXML") { ActiveSupport::XmlMini.parse(xml) } + assert_equal(hash, parsed_xml) + end + end end diff --git a/activesupport/test/xml_mini/nokogirisax_engine_test.rb b/activesupport/test/xml_mini/nokogirisax_engine_test.rb index 9a2bcc3f7e..24b35cadf6 100644 --- a/activesupport/test/xml_mini/nokogirisax_engine_test.rb +++ b/activesupport/test/xml_mini/nokogirisax_engine_test.rb @@ -3,38 +3,38 @@ begin rescue LoadError # Skip nokogiri tests else -require "abstract_unit" -require "active_support/xml_mini" -require "active_support/core_ext/hash/conversions" - -class NokogiriSAXEngineTest < ActiveSupport::TestCase - def setup - @default_backend = ActiveSupport::XmlMini.backend - ActiveSupport::XmlMini.backend = "NokogiriSAX" - end + require "abstract_unit" + require "active_support/xml_mini" + require "active_support/core_ext/hash/conversions" + + class NokogiriSAXEngineTest < ActiveSupport::TestCase + def setup + @default_backend = ActiveSupport::XmlMini.backend + ActiveSupport::XmlMini.backend = "NokogiriSAX" + end - def teardown - ActiveSupport::XmlMini.backend = @default_backend - end + def teardown + ActiveSupport::XmlMini.backend = @default_backend + end - def test_file_from_xml - hash = Hash.from_xml(<<-eoxml) + def test_file_from_xml + hash = Hash.from_xml(<<-eoxml) eoxml - assert hash.has_key?("blog") - assert hash["blog"].has_key?("logo") + assert hash.has_key?("blog") + assert hash["blog"].has_key?("logo") - file = hash["blog"]["logo"] - assert_equal "logo.png", file.original_filename - assert_equal "image/png", file.content_type - end + file = hash["blog"]["logo"] + assert_equal "logo.png", file.original_filename + assert_equal "image/png", file.content_type + end - def test_exception_thrown_on_expansion_attack - assert_raise RuntimeError do - attack_xml = <<-EOT + def test_exception_thrown_on_expansion_attack + assert_raise RuntimeError do + attack_xml = <<-EOT @@ -50,22 +50,22 @@ class NokogiriSAXEngineTest < ActiveSupport::TestCase EOT - Hash.from_xml(attack_xml) + Hash.from_xml(attack_xml) + end end - end - def test_setting_nokogirisax_as_backend - ActiveSupport::XmlMini.backend = "NokogiriSAX" - assert_equal ActiveSupport::XmlMini_NokogiriSAX, ActiveSupport::XmlMini.backend - end + def test_setting_nokogirisax_as_backend + ActiveSupport::XmlMini.backend = "NokogiriSAX" + assert_equal ActiveSupport::XmlMini_NokogiriSAX, ActiveSupport::XmlMini.backend + end - def test_blank_returns_empty_hash - assert_equal({}, ActiveSupport::XmlMini.parse(nil)) - assert_equal({}, ActiveSupport::XmlMini.parse("")) - end + def test_blank_returns_empty_hash + assert_equal({}, ActiveSupport::XmlMini.parse(nil)) + assert_equal({}, ActiveSupport::XmlMini.parse("")) + end - def test_array_type_makes_an_array - assert_equal_rexml(<<-eoxml) + def test_array_type_makes_an_array + assert_equal_rexml(<<-eoxml) a post @@ -73,67 +73,67 @@ class NokogiriSAXEngineTest < ActiveSupport::TestCase eoxml - end + end - def test_one_node_document_as_hash - assert_equal_rexml(<<-eoxml) - - eoxml - end + def test_one_node_document_as_hash + assert_equal_rexml(<<-eoxml) + + eoxml + end - def test_one_node_with_attributes_document_as_hash - assert_equal_rexml(<<-eoxml) - - eoxml - end + def test_one_node_with_attributes_document_as_hash + assert_equal_rexml(<<-eoxml) + + eoxml + end - def test_products_node_with_book_node_as_hash - assert_equal_rexml(<<-eoxml) + def test_products_node_with_book_node_as_hash + assert_equal_rexml(<<-eoxml) eoxml - end + end - def test_products_node_with_two_book_nodes_as_hash - assert_equal_rexml(<<-eoxml) + def test_products_node_with_two_book_nodes_as_hash + assert_equal_rexml(<<-eoxml) eoxml - end + end - def test_single_node_with_content_as_hash - assert_equal_rexml(<<-eoxml) + def test_single_node_with_content_as_hash + assert_equal_rexml(<<-eoxml) hello world eoxml - end + end - def test_children_with_children - assert_equal_rexml(<<-eoxml) + def test_children_with_children + assert_equal_rexml(<<-eoxml) eoxml - end + end - def test_children_with_text - assert_equal_rexml(<<-eoxml) + def test_children_with_text + assert_equal_rexml(<<-eoxml) hello everyone eoxml - end + end - def test_children_with_non_adjacent_text - assert_equal_rexml(<<-eoxml) + def test_children_with_non_adjacent_text + assert_equal_rexml(<<-eoxml) good @@ -142,10 +142,10 @@ class NokogiriSAXEngineTest < ActiveSupport::TestCase morning eoxml - end + end - def test_parse_from_io - io = StringIO.new(<<-eoxml) + def test_parse_from_io + io = StringIO.new(<<-eoxml) good @@ -154,31 +154,31 @@ class NokogiriSAXEngineTest < ActiveSupport::TestCase morning eoxml - assert_equal_rexml(io) - end + assert_equal_rexml(io) + end - def test_children_with_simple_cdata - assert_equal_rexml(<<-eoxml) + def test_children_with_simple_cdata + assert_equal_rexml(<<-eoxml) eoxml - end + end - def test_children_with_multiple_cdata - assert_equal_rexml(<<-eoxml) + def test_children_with_multiple_cdata + assert_equal_rexml(<<-eoxml) eoxml - end + end - def test_children_with_text_and_cdata - assert_equal_rexml(<<-eoxml) + def test_children_with_text_and_cdata + assert_equal_rexml(<<-eoxml) hello @@ -186,31 +186,31 @@ class NokogiriSAXEngineTest < ActiveSupport::TestCase eoxml - end + end - def test_children_with_blank_text - assert_equal_rexml(<<-eoxml) + def test_children_with_blank_text + assert_equal_rexml(<<-eoxml) eoxml - end + end - def test_children_with_blank_text_and_attribute - assert_equal_rexml(<<-eoxml) + def test_children_with_blank_text_and_attribute + assert_equal_rexml(<<-eoxml) eoxml - end - - private - def assert_equal_rexml(xml) - parsed_xml = ActiveSupport::XmlMini.parse(xml) - xml.rewind if xml.respond_to?(:rewind) - hash = ActiveSupport::XmlMini.with_backend("REXML") { ActiveSupport::XmlMini.parse(xml) } - assert_equal(hash, parsed_xml) end -end + + private + def assert_equal_rexml(xml) + parsed_xml = ActiveSupport::XmlMini.parse(xml) + xml.rewind if xml.respond_to?(:rewind) + hash = ActiveSupport::XmlMini.with_backend("REXML") { ActiveSupport::XmlMini.parse(xml) } + assert_equal(hash, parsed_xml) + end + end end diff --git a/activesupport/test/xml_mini/rexml_engine_test.rb b/activesupport/test/xml_mini/rexml_engine_test.rb index 2af98f7fe2..a3bae7a89c 100644 --- a/activesupport/test/xml_mini/rexml_engine_test.rb +++ b/activesupport/test/xml_mini/rexml_engine_test.rb @@ -26,8 +26,8 @@ class REXMLEngineTest < ActiveSupport::TestCase assert hash.has_key?("root") assert hash["root"].has_key?("products") assert_match "good", hash["root"]["__content__"] - products = hash["root"]["products"] - assert products.has_key?("__content__") + products = hash["root"]["products"] + assert products.has_key?("__content__") assert_match "hello everyone", products["__content__"] end diff --git a/ci/travis.rb b/ci/travis.rb index ddbc8520e6..1d658bae47 100755 --- a/ci/travis.rb +++ b/ci/travis.rb @@ -137,8 +137,8 @@ class Build end if ENV["GEM"]=="aj:integration" - ENV["QC_DATABASE_URL"] = "postgres://postgres@localhost/active_jobs_qc_int_test" - ENV["QUE_DATABASE_URL"] = "postgres://postgres@localhost/active_jobs_que_int_test" + ENV["QC_DATABASE_URL"] = "postgres://postgres@localhost/active_jobs_qc_int_test" + ENV["QUE_DATABASE_URL"] = "postgres://postgres@localhost/active_jobs_que_int_test" end results = {} diff --git a/guides/Rakefile b/guides/Rakefile index 0c7d112842..353966fc55 100644 --- a/guides/Rakefile +++ b/guides/Rakefile @@ -16,7 +16,7 @@ namespace :guides do unless `kindlerb -v 2> /dev/null` =~ /kindlerb 0.1.1/ abort "Please `gem install kindlerb` and make sure you have `kindlegen` in your PATH" end - unless `convert` =~ /convert/ + unless `convert` =~ /convert/ abort "Please install ImageMagick`" end ENV["KINDLE"] = "1" diff --git a/guides/rails_guides/generator.rb b/guides/rails_guides/generator.rb index 881bf2174b..39a57191eb 100644 --- a/guides/rails_guides/generator.rb +++ b/guides/rails_guides/generator.rb @@ -102,148 +102,148 @@ module RailsGuides private - def kindle? - @kindle - end + def kindle? + @kindle + end - def check_for_kindlegen - if `which kindlegen`.blank? - raise "Can't create a kindle version without `kindlegen`." + def check_for_kindlegen + if `which kindlegen`.blank? + raise "Can't create a kindle version without `kindlegen`." + end end - end - def generate_mobi - require "rails_guides/kindle" - out = "#{output_dir}/kindlegen.out" - Kindle.generate(output_dir, mobi, out) - puts "(kindlegen log at #{out})." - end + def generate_mobi + require "rails_guides/kindle" + out = "#{output_dir}/kindlegen.out" + Kindle.generate(output_dir, mobi, out) + puts "(kindlegen log at #{out})." + end - def mobi - "ruby_on_rails_guides_#@version%s.mobi" % (@lang.present? ? ".#@lang" : "") - end + def mobi + "ruby_on_rails_guides_#@version%s.mobi" % (@lang.present? ? ".#@lang" : "") + end - def initialize_dirs(output) - @guides_dir = File.join(File.dirname(__FILE__), "..") - @source_dir = "#@guides_dir/source/#@lang" - @output_dir = if output - output - elsif kindle? - "#@guides_dir/output/kindle/#@lang" - else - "#@guides_dir/output/#@lang" - end.sub(%r, "") - end + def initialize_dirs(output) + @guides_dir = File.join(File.dirname(__FILE__), "..") + @source_dir = "#@guides_dir/source/#@lang" + @output_dir = if output + output + elsif kindle? + "#@guides_dir/output/kindle/#@lang" + else + "#@guides_dir/output/#@lang" + end.sub(%r, "") + end - def create_output_dir_if_needed - FileUtils.mkdir_p(output_dir) - end + def create_output_dir_if_needed + FileUtils.mkdir_p(output_dir) + end - def generate_guides - guides_to_generate.each do |guide| - output_file = output_file_for(guide) - generate_guide(guide, output_file) if generate?(guide, output_file) + def generate_guides + guides_to_generate.each do |guide| + output_file = output_file_for(guide) + generate_guide(guide, output_file) if generate?(guide, output_file) + end end - end - def guides_to_generate - guides = Dir.entries(source_dir).grep(GUIDES_RE) + def guides_to_generate + guides = Dir.entries(source_dir).grep(GUIDES_RE) - if kindle? - Dir.entries("#{source_dir}/kindle").grep(GUIDES_RE).map do |entry| - next if entry == "KINDLE.md" - guides << "kindle/#{entry}" + if kindle? + Dir.entries("#{source_dir}/kindle").grep(GUIDES_RE).map do |entry| + next if entry == "KINDLE.md" + guides << "kindle/#{entry}" + end end + + ENV.key?("ONLY") ? select_only(guides) : guides end - ENV.key?("ONLY") ? select_only(guides) : guides - end + def select_only(guides) + prefixes = ENV["ONLY"].split(",").map(&:strip) + guides.select do |guide| + guide.start_with?("kindle".freeze, *prefixes) + end + end - def select_only(guides) - prefixes = ENV["ONLY"].split(",").map(&:strip) - guides.select do |guide| - guide.start_with?("kindle".freeze, *prefixes) + def copy_assets + FileUtils.cp_r(Dir.glob("#{guides_dir}/assets/*"), output_dir) end - end - def copy_assets - FileUtils.cp_r(Dir.glob("#{guides_dir}/assets/*"), output_dir) - end + def output_file_for(guide) + if guide.end_with?(".md") + guide.sub(/md\z/, "html") + else + guide.sub(/\.erb\z/, "") + end + end - def output_file_for(guide) - if guide.end_with?(".md") - guide.sub(/md\z/, "html") - else - guide.sub(/\.erb\z/, "") + def output_path_for(output_file) + File.join(output_dir, File.basename(output_file)) end - end - def output_path_for(output_file) - File.join(output_dir, File.basename(output_file)) - end + def generate?(source_file, output_file) + fin = File.join(source_dir, source_file) + fout = output_path_for(output_file) + all || !File.exist?(fout) || File.mtime(fout) < File.mtime(fin) + end - def generate?(source_file, output_file) - fin = File.join(source_dir, source_file) - fout = output_path_for(output_file) - all || !File.exist?(fout) || File.mtime(fout) < File.mtime(fin) - end + def generate_guide(guide, output_file) + output_path = output_path_for(output_file) + puts "Generating #{guide} as #{output_file}" + layout = kindle? ? "kindle/layout" : "layout" - def generate_guide(guide, output_file) - output_path = output_path_for(output_file) - puts "Generating #{guide} as #{output_file}" - layout = kindle? ? "kindle/layout" : "layout" + File.open(output_path, "w") do |f| + view = ActionView::Base.new(source_dir, edge: @edge, version: @version, mobi: "kindle/#{mobi}", lang: @lang) + view.extend(Helpers) - File.open(output_path, "w") do |f| - view = ActionView::Base.new(source_dir, edge: @edge, version: @version, mobi: "kindle/#{mobi}", lang: @lang) - view.extend(Helpers) + if guide =~ /\.(\w+)\.erb$/ + # Generate the special pages like the home. + # Passing a template handler in the template name is deprecated. So pass the file name without the extension. + result = view.render(layout: layout, formats: [$1], file: $`) + else + body = File.read(File.join(source_dir, guide)) + result = RailsGuides::Markdown.new(view, layout).render(body) - if guide =~ /\.(\w+)\.erb$/ - # Generate the special pages like the home. - # Passing a template handler in the template name is deprecated. So pass the file name without the extension. - result = view.render(layout: layout, formats: [$1], file: $`) - else - body = File.read(File.join(source_dir, guide)) - result = RailsGuides::Markdown.new(view, layout).render(body) + warn_about_broken_links(result) if @warnings + end - warn_about_broken_links(result) if @warnings + f.write(result) end - - f.write(result) end - end - def warn_about_broken_links(html) - anchors = extract_anchors(html) - check_fragment_identifiers(html, anchors) - end + def warn_about_broken_links(html) + anchors = extract_anchors(html) + check_fragment_identifiers(html, anchors) + end - def extract_anchors(html) - # Markdown generates headers with IDs computed from titles. - anchors = Set.new - html.scan(/ Levenshtein.distance(fragment_identifier, b) - } - puts "*** BROKEN LINK: ##{fragment_identifier}, perhaps you meant ##{guess}." + def check_fragment_identifiers(html, anchors) + html.scan(/ Levenshtein.distance(fragment_identifier, b) + } + puts "*** BROKEN LINK: ##{fragment_identifier}, perhaps you meant ##{guess}." + end end end - end end end diff --git a/guides/rails_guides/indexer.rb b/guides/rails_guides/indexer.rb index 1550ceedac..56df6a5842 100644 --- a/guides/rails_guides/indexer.rb +++ b/guides/rails_guides/indexer.rb @@ -17,52 +17,52 @@ module RailsGuides private - def process(string, current_level=3, counters=[1]) - s = StringScanner.new(string) + def process(string, current_level=3, counters=[1]) + s = StringScanner.new(string) - level_hash = {} + level_hash = {} - while !s.eos? - re = %r{^h(\d)(?:\((#.*?)\))?\s*\.\s*(.*)$} - s.match?(re) - if matched = s.matched - matched =~ re - level, idx, title = $1.to_i, $2, $3.strip + while !s.eos? + re = %r{^h(\d)(?:\((#.*?)\))?\s*\.\s*(.*)$} + s.match?(re) + if matched = s.matched + matched =~ re + level, idx, title = $1.to_i, $2, $3.strip - if level < current_level - # This is needed. Go figure. - return level_hash - elsif level == current_level - index = counters.join(".") - idx ||= "#" + title_to_idx(title) + if level < current_level + # This is needed. Go figure. + return level_hash + elsif level == current_level + index = counters.join(".") + idx ||= "#" + title_to_idx(title) - raise "Parsing Fail" unless @result.sub!(matched, "h#{level}(#{idx}). #{index} #{title}") + raise "Parsing Fail" unless @result.sub!(matched, "h#{level}(#{idx}). #{index} #{title}") - key = { - title: title, - id: idx - } - # Recurse - counters << 1 - level_hash[key] = process(s.post_match, current_level + 1, counters) - counters.pop + key = { + title: title, + id: idx + } + # Recurse + counters << 1 + level_hash[key] = process(s.post_match, current_level + 1, counters) + counters.pop - # Increment the current level - last = counters.pop - counters << last + 1 + # Increment the current level + last = counters.pop + counters << last + 1 + end end + s.getch end - s.getch + level_hash end - level_hash - end - def title_to_idx(title) - idx = title.strip.parameterize.sub(/^\d+/, "") - if warnings && idx.blank? - puts "BLANK ID: please put an explicit ID for section #{title}, as in h5(#my-id)" + def title_to_idx(title) + idx = title.strip.parameterize.sub(/^\d+/, "") + if warnings && idx.blank? + puts "BLANK ID: please put an explicit ID for section #{title}, as in h5(#my-id)" + end + idx end - idx - end end end diff --git a/guides/rails_guides/kindle.rb b/guides/rails_guides/kindle.rb index 3686e195e0..675df8e55b 100644 --- a/guides/rails_guides/kindle.rb +++ b/guides/rails_guides/kindle.rb @@ -1,6 +1,6 @@ #!/usr/bin/env ruby -unless `which kindlerb` +unless `which kindlerb` abort "Please gem install kindlerb" end @@ -14,13 +14,13 @@ module Kindle def generate(output_dir, mobi_outfile, logfile) output_dir = File.absolute_path(output_dir) - Dir.chdir output_dir do + Dir.chdir output_dir do puts "=> Using output dir: #{output_dir}" 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 - + generate_front_matter(html_pages) generate_sections(html_pages) @@ -37,7 +37,7 @@ 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 @@ -51,7 +51,7 @@ module Kindle fdoc.search("h3").each do |h3| h3.name = "h4" end - fdoc.search("h2").each do |h2| + fdoc.search("h2").each do |h2| h2.name = "h3" h2["id"] = h2.inner_text.gsub(/\s/, "-") end @@ -72,7 +72,7 @@ module Kindle subsection = h3.inner_text 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] + 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']}" diff --git a/guides/w3c_validator.rb b/guides/w3c_validator.rb index 6eddd08906..aad9ac2608 100644 --- a/guides/w3c_validator.rb +++ b/guides/w3c_validator.rb @@ -57,39 +57,39 @@ module RailsGuides end private - def guides_to_validate - guides = Dir["./output/*.html"] - guides.delete("./output/layout.html") - guides.delete("./output/_license.html") - guides.delete("./output/_welcome.html") - ENV.key?("ONLY") ? select_only(guides) : guides - end + def guides_to_validate + guides = Dir["./output/*.html"] + guides.delete("./output/layout.html") + guides.delete("./output/_license.html") + guides.delete("./output/_welcome.html") + ENV.key?("ONLY") ? select_only(guides) : guides + end - def select_only(guides) - prefixes = ENV["ONLY"].split(",").map(&:strip) - guides.select do |guide| - prefixes.any? {|p| guide.start_with?("./output/#{p}")} + def select_only(guides) + prefixes = ENV["ONLY"].split(",").map(&:strip) + guides.select do |guide| + prefixes.any? {|p| guide.start_with?("./output/#{p}")} + end end - end - def show_results(error_list) - if error_list.size == 0 - puts "\n\nAll checked guides validate OK!" - else - error_summary = error_detail = "" + def show_results(error_list) + if error_list.size == 0 + puts "\n\nAll checked guides validate OK!" + else + error_summary = error_detail = "" - error_list.each_pair do |name, errors| - error_summary += "\n #{name}" - error_detail += "\n\n #{name} has #{errors.size} validation error(s):\n" - errors.each do |error| - error_detail += "\n "+error.to_s.delete("\n") + error_list.each_pair do |name, errors| + error_summary += "\n #{name}" + error_detail += "\n\n #{name} has #{errors.size} validation error(s):\n" + errors.each do |error| + error_detail += "\n "+error.to_s.delete("\n") + end end - end - puts "\n\nThere are #{error_list.size} guides with validation errors:\n" + error_summary - puts "\nHere are the detailed errors for each guide:" + error_detail + puts "\n\nThere are #{error_list.size} guides with validation errors:\n" + error_summary + puts "\nHere are the detailed errors for each guide:" + error_detail + end end - end end end diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb index 6178147ee4..9c150965bf 100644 --- a/railties/lib/rails/application.rb +++ b/railties/lib/rails/application.rb @@ -522,15 +522,15 @@ module Rails private - def build_request(env) - req = super - env["ORIGINAL_FULLPATH"] = req.fullpath - env["ORIGINAL_SCRIPT_NAME"] = req.script_name - req - end + def build_request(env) + req = super + env["ORIGINAL_FULLPATH"] = req.fullpath + env["ORIGINAL_SCRIPT_NAME"] = req.script_name + req + end - def build_middleware - config.app_middleware + super - end + def build_middleware + config.app_middleware + super + end end end diff --git a/railties/lib/rails/application_controller.rb b/railties/lib/rails/application_controller.rb index b0f3c3946d..f8394b8e0a 100644 --- a/railties/lib/rails/application_controller.rb +++ b/railties/lib/rails/application_controller.rb @@ -4,13 +4,13 @@ class Rails::ApplicationController < ActionController::Base # :nodoc: protected - def require_local! - unless local_request? - render html: "

For security purposes, this information is only available to local requests.

".html_safe, status: :forbidden + def require_local! + unless local_request? + render html: "

For security purposes, this information is only available to local requests.

".html_safe, status: :forbidden + end end - end - def local_request? - Rails.application.config.consider_all_requests_local || request.local? - end + def local_request? + Rails.application.config.consider_all_requests_local || request.local? + end end diff --git a/railties/lib/rails/commands/console_helper.rb b/railties/lib/rails/commands/console_helper.rb index 48c489740e..0b7f1c4249 100644 --- a/railties/lib/rails/commands/console_helper.rb +++ b/railties/lib/rails/commands/console_helper.rb @@ -8,7 +8,7 @@ module Rails def start(*args) new(*args).start end - + private def set_options_env(arguments, options) if arguments.first && arguments.first[0] != "-" @@ -24,11 +24,11 @@ module Rails def available_environments Dir["config/environments/*.rb"].map { |fname| File.basename(fname, ".*") } - end + end end def environment ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development" end end -end \ No newline at end of file +end diff --git a/railties/lib/rails/commands/dbconsole.rb b/railties/lib/rails/commands/dbconsole.rb index 95cd1fe528..d79a88b025 100644 --- a/railties/lib/rails/commands/dbconsole.rb +++ b/railties/lib/rails/commands/dbconsole.rb @@ -21,7 +21,7 @@ module Rails opt.on("--mode [MODE]", ["html", "list", "line", "column"], "Automatically put the sqlite3 database in the specified mode (html, list, line, column).") do |mode| - options["mode"] = mode + options["mode"] = mode end opt.on("--header") do |h| diff --git a/railties/lib/rails/commands/plugin.rb b/railties/lib/rails/commands/plugin.rb index ee5abdf880..6404748fca 100644 --- a/railties/lib/rails/commands/plugin.rb +++ b/railties/lib/rails/commands/plugin.rb @@ -5,7 +5,7 @@ else unless ARGV.delete("--no-rc") customrc = ARGV.index{ |x| x.include?("--rc=") } railsrc = if customrc - File.expand_path(ARGV.delete_at(customrc).gsub(/--rc=/, "")) + File.expand_path(ARGV.delete_at(customrc).gsub(/--rc=/, "")) else File.join(File.expand_path("~"), ".railsrc") end diff --git a/railties/lib/rails/commands/runner.rb b/railties/lib/rails/commands/runner.rb index 38c749151c..11ef1d10e2 100644 --- a/railties/lib/rails/commands/runner.rb +++ b/railties/lib/rails/commands/runner.rb @@ -22,14 +22,14 @@ ARGV.clone.options do |opts| opts.on("-h", "--help", "Show this help message.") { $stdout.puts opts; exit } - opts.separator "" - opts.separator "Examples: " + opts.separator "" + opts.separator "Examples: " - opts.separator " rails runner 'puts Rails.env'" - opts.separator " This runs the code `puts Rails.env` after loading the app" - opts.separator "" - opts.separator " rails runner path/to/filename.rb" - opts.separator " This runs the Ruby file located at `path/to/filename.rb` after loading the app" + opts.separator " rails runner 'puts Rails.env'" + opts.separator " This runs the code `puts Rails.env` after loading the app" + opts.separator "" + opts.separator " rails runner path/to/filename.rb" + opts.separator " This runs the Ruby file located at `path/to/filename.rb` after loading the app" if RbConfig::CONFIG["host_os"] !~ /mswin|mingw/ opts.separator "" diff --git a/railties/lib/rails/commands/server.rb b/railties/lib/rails/commands/server.rb index 28941fd704..bf8ae0a5ee 100644 --- a/railties/lib/rails/commands/server.rb +++ b/railties/lib/rails/commands/server.rb @@ -21,31 +21,31 @@ module Rails private - def option_parser(options) - OptionParser.new do |opts| - opts.banner = "Usage: rails server [mongrel, thin etc] [options]" - opts.on("-p", "--port=port", Integer, - "Runs Rails on the specified port.", "Default: 3000") { |v| options[:Port] = v } - opts.on("-b", "--binding=IP", String, - "Binds Rails to the specified IP.", "Default: localhost") { |v| options[:Host] = v } - opts.on("-c", "--config=file", String, - "Uses a custom rackup configuration.") { |v| options[:config] = v } - opts.on("-d", "--daemon", "Runs server as a Daemon.") { options[:daemonize] = true } - opts.on("-e", "--environment=name", String, - "Specifies the environment to run this server under (test/development/production).", - "Default: development") { |v| options[:environment] = v } - opts.on("-P", "--pid=pid", String, - "Specifies the PID file.", - "Default: tmp/pids/server.pid") { |v| options[:pid] = v } - opts.on("-C", "--[no-]dev-caching", - "Specifies whether to perform caching in development.", - "true or false") { |v| options[:caching] = v } - - opts.separator "" - - opts.on("-h", "--help", "Shows this help message.") { puts opts; exit } + def option_parser(options) + OptionParser.new do |opts| + opts.banner = "Usage: rails server [mongrel, thin etc] [options]" + opts.on("-p", "--port=port", Integer, + "Runs Rails on the specified port.", "Default: 3000") { |v| options[:Port] = v } + opts.on("-b", "--binding=IP", String, + "Binds Rails to the specified IP.", "Default: localhost") { |v| options[:Host] = v } + opts.on("-c", "--config=file", String, + "Uses a custom rackup configuration.") { |v| options[:config] = v } + opts.on("-d", "--daemon", "Runs server as a Daemon.") { options[:daemonize] = true } + opts.on("-e", "--environment=name", String, + "Specifies the environment to run this server under (test/development/production).", + "Default: development") { |v| options[:environment] = v } + opts.on("-P", "--pid=pid", String, + "Specifies the PID file.", + "Default: tmp/pids/server.pid") { |v| options[:pid] = v } + opts.on("-C", "--[no-]dev-caching", + "Specifies whether to perform caching in development.", + "true or false") { |v| options[:caching] = v } + + opts.separator "" + + opts.on("-h", "--help", "Shows this help message.") { puts opts; exit } + end end - end end def initialize(*) diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb index b8a9cac6d0..bcd1a66921 100644 --- a/railties/lib/rails/engine.rb +++ b/railties/lib/rails/engine.rb @@ -643,62 +643,62 @@ module Rails protected - def load_config_initializer(initializer) - ActiveSupport::Notifications.instrument("load_config_initializer.railties", initializer: initializer) do - load(initializer) + def load_config_initializer(initializer) + ActiveSupport::Notifications.instrument("load_config_initializer.railties", initializer: initializer) do + load(initializer) + end end - end - def run_tasks_blocks(*) #:nodoc: - super - paths["lib/tasks"].existent.sort.each { |ext| load(ext) } - end + def run_tasks_blocks(*) #:nodoc: + super + paths["lib/tasks"].existent.sort.each { |ext| load(ext) } + end - def has_migrations? #:nodoc: - paths["db/migrate"].existent.any? - end + def has_migrations? #:nodoc: + paths["db/migrate"].existent.any? + end - def self.find_root_with_flag(flag, root_path, default=nil) #:nodoc: + def self.find_root_with_flag(flag, root_path, default=nil) #:nodoc: - while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}") - parent = File.dirname(root_path) - root_path = parent != root_path && parent - end + while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}") + parent = File.dirname(root_path) + root_path = parent != root_path && parent + end - root = File.exist?("#{root_path}/#{flag}") ? root_path : default - raise "Could not find root path for #{self}" unless root + root = File.exist?("#{root_path}/#{flag}") ? root_path : default + raise "Could not find root path for #{self}" unless root - Pathname.new File.realpath root - end + Pathname.new File.realpath root + end - def default_middleware_stack #:nodoc: - ActionDispatch::MiddlewareStack.new - end + def default_middleware_stack #:nodoc: + ActionDispatch::MiddlewareStack.new + end - def _all_autoload_once_paths #:nodoc: - config.autoload_once_paths - end + def _all_autoload_once_paths #:nodoc: + config.autoload_once_paths + end - def _all_autoload_paths #:nodoc: - @_all_autoload_paths ||= (config.autoload_paths + config.eager_load_paths + config.autoload_once_paths).uniq - end + def _all_autoload_paths #:nodoc: + @_all_autoload_paths ||= (config.autoload_paths + config.eager_load_paths + config.autoload_once_paths).uniq + end - def _all_load_paths #:nodoc: - @_all_load_paths ||= (config.paths.load_paths + _all_autoload_paths).uniq - end + def _all_load_paths #:nodoc: + @_all_load_paths ||= (config.paths.load_paths + _all_autoload_paths).uniq + end private - def build_request(env) - env.merge!(env_config) - req = ActionDispatch::Request.new env - req.routes = routes - req.engine_script_name = req.script_name - req - end + def build_request(env) + env.merge!(env_config) + req = ActionDispatch::Request.new env + req.routes = routes + req.engine_script_name = req.script_name + req + end - def build_middleware - config.middleware - end + def build_middleware + config.middleware + end end end diff --git a/railties/lib/rails/generators/actions/create_migration.rb b/railties/lib/rails/generators/actions/create_migration.rb index a5e624b5d1..46f376a38e 100644 --- a/railties/lib/rails/generators/actions/create_migration.rb +++ b/railties/lib/rails/generators/actions/create_migration.rb @@ -40,30 +40,30 @@ module Rails protected - def on_conflict_behavior - options = base.options.merge(config) - if identical? - say_status :identical, :blue, relative_existing_migration - elsif options[:force] - say_status :remove, :green, relative_existing_migration - say_status :create, :green - unless pretend? - ::FileUtils.rm_rf(existing_migration) - yield + def on_conflict_behavior + options = base.options.merge(config) + if identical? + say_status :identical, :blue, relative_existing_migration + elsif options[:force] + say_status :remove, :green, relative_existing_migration + say_status :create, :green + unless pretend? + ::FileUtils.rm_rf(existing_migration) + yield + end + elsif options[:skip] + say_status :skip, :yellow + else + say_status :conflict, :red + raise Error, "Another migration is already named #{migration_file_name}: " + + "#{existing_migration}. Use --force to replace this migration " + + "or --skip to ignore conflicted file." end - elsif options[:skip] - say_status :skip, :yellow - else - say_status :conflict, :red - raise Error, "Another migration is already named #{migration_file_name}: " + - "#{existing_migration}. Use --force to replace this migration " + - "or --skip to ignore conflicted file." end - end - def say_status(status, color, message = relative_destination) - base.shell.say_status(status, message, color) if config[:verbose] - end + def say_status(status, color, message = relative_destination) + base.shell.say_status(status, message, color) if config[:verbose] + end end end end diff --git a/railties/lib/rails/generators/erb.rb b/railties/lib/rails/generators/erb.rb index 99d8a0b786..d01502002f 100644 --- a/railties/lib/rails/generators/erb.rb +++ b/railties/lib/rails/generators/erb.rb @@ -5,21 +5,21 @@ module Erb # :nodoc: class Base < Rails::Generators::NamedBase #:nodoc: protected - def formats - [format] - end + def formats + [format] + end - def format - :html - end + def format + :html + end - def handler - :erb - end + def handler + :erb + end - def filename_with_extensions(name, format = self.format) - [name, format, handler].compact.join(".") - end + def filename_with_extensions(name, format = self.format) + [name, format, handler].compact.join(".") + end end end end diff --git a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb index 1207cdad69..f150240908 100644 --- a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb +++ b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb @@ -28,13 +28,13 @@ module Erb # :nodoc: protected - def formats - [:text, :html] - end + def formats + [:text, :html] + end - def file_name - @_file_name ||= super.gsub(/_mailer/i, "") - end + def file_name + @_file_name ||= super.gsub(/_mailer/i, "") + end end end end diff --git a/railties/lib/rails/generators/rails/assets/assets_generator.rb b/railties/lib/rails/generators/rails/assets/assets_generator.rb index 6f4b86e708..265dada2ca 100644 --- a/railties/lib/rails/generators/rails/assets/assets_generator.rb +++ b/railties/lib/rails/generators/rails/assets/assets_generator.rb @@ -9,17 +9,17 @@ module Rails protected - def asset_name - file_name - end + def asset_name + file_name + end - hook_for :javascript_engine do |javascript_engine| - invoke javascript_engine, [name] if options[:javascripts] - end + hook_for :javascript_engine do |javascript_engine| + invoke javascript_engine, [name] if options[:javascripts] + end - hook_for :stylesheet_engine do |stylesheet_engine| - invoke stylesheet_engine, [name] if options[:stylesheets] - end + hook_for :stylesheet_engine do |stylesheet_engine| + invoke stylesheet_engine, [name] if options[:stylesheets] + end end end end diff --git a/railties/lib/rails/info.rb b/railties/lib/rails/info.rb index 5cc747592d..d69cbbc001 100644 --- a/railties/lib/rails/info.rb +++ b/railties/lib/rails/info.rb @@ -42,7 +42,7 @@ module Rails properties.each do |(name, value)| table << %(#{CGI.escapeHTML(name.to_s)}) formatted_value = if value.kind_of?(Array) - "
    " + value.map { |v| "
  • #{CGI.escapeHTML(v.to_s)}
  • " }.join + "
" + "
    " + value.map { |v| "
  • #{CGI.escapeHTML(v.to_s)}
  • " }.join + "
" else CGI.escapeHTML(value.to_s) end diff --git a/railties/lib/rails/info_controller.rb b/railties/lib/rails/info_controller.rb index db9a32c9c2..f5aa074703 100644 --- a/railties/lib/rails/info_controller.rb +++ b/railties/lib/rails/info_controller.rb @@ -32,13 +32,13 @@ class Rails::InfoController < Rails::ApplicationController # :nodoc: private - def match_route - _routes.routes.select {|route| - yield route.path - }.map {|route| route.path.spec.to_s } - end + def match_route + _routes.routes.select {|route| + yield route.path + }.map {|route| route.path.spec.to_s } + end - def with_leading_slash(path) - ("/" + path).squeeze("/") - end + def with_leading_slash(path) + ("/" + path).squeeze("/") + end end diff --git a/railties/lib/rails/rack/logger.rb b/railties/lib/rails/rack/logger.rb index b8684971fc..e3fee75603 100644 --- a/railties/lib/rails/rack/logger.rb +++ b/railties/lib/rails/rack/logger.rb @@ -67,14 +67,14 @@ module Rails private - def finish(request) - instrumenter = ActiveSupport::Notifications.instrumenter - instrumenter.finish "request.action_dispatch", request: request - end + def finish(request) + instrumenter = ActiveSupport::Notifications.instrumenter + instrumenter.finish "request.action_dispatch", request: request + end - def logger - Rails.logger - end + def logger + Rails.logger + end end end end diff --git a/railties/lib/rails/railtie.rb b/railties/lib/rails/railtie.rb index 8718f6db2d..eb3f5d4ee9 100644 --- a/railties/lib/rails/railtie.rb +++ b/railties/lib/rails/railtie.rb @@ -222,31 +222,31 @@ module Rails protected - def run_console_blocks(app) #:nodoc: - each_registered_block(:console) { |block| block.call(app) } - end + def run_console_blocks(app) #:nodoc: + each_registered_block(:console) { |block| block.call(app) } + end - def run_generators_blocks(app) #:nodoc: - each_registered_block(:generators) { |block| block.call(app) } - end + def run_generators_blocks(app) #:nodoc: + each_registered_block(:generators) { |block| block.call(app) } + end - def run_runner_blocks(app) #:nodoc: - each_registered_block(:runner) { |block| block.call(app) } - end + def run_runner_blocks(app) #:nodoc: + each_registered_block(:runner) { |block| block.call(app) } + end - def run_tasks_blocks(app) #:nodoc: - extend Rake::DSL - each_registered_block(:rake_tasks) { |block| instance_exec(app, &block) } - end + def run_tasks_blocks(app) #:nodoc: + extend Rake::DSL + each_registered_block(:rake_tasks) { |block| instance_exec(app, &block) } + end private - def each_registered_block(type, &block) - klass = self.class - while klass.respond_to?(type) - klass.public_send(type).each(&block) - klass = klass.superclass + def each_registered_block(type, &block) + klass = self.class + while klass.respond_to?(type) + klass.public_send(type).each(&block) + klass = klass.superclass + end end - end end end diff --git a/railties/lib/rails/railtie/configurable.rb b/railties/lib/rails/railtie/configurable.rb index 257c4df894..d6040785a0 100644 --- a/railties/lib/rails/railtie/configurable.rb +++ b/railties/lib/rails/railtie/configurable.rb @@ -26,9 +26,9 @@ module Rails protected - def method_missing(*args, &block) - instance.send(*args, &block) - end + def method_missing(*args, &block) + instance.send(*args, &block) + end end end end diff --git a/railties/lib/rails/tasks/annotations.rake b/railties/lib/rails/tasks/annotations.rake index 61dd4a1a37..9a69eb9934 100644 --- a/railties/lib/rails/tasks/annotations.rake +++ b/railties/lib/rails/tasks/annotations.rake @@ -17,4 +17,4 @@ namespace :notes do task :custom do SourceAnnotationExtractor.enumerate ENV["ANNOTATION"] end -end \ No newline at end of file +end diff --git a/railties/lib/rails/tasks/log.rake b/railties/lib/rails/tasks/log.rake index 31acbdcb84..c376234fee 100644 --- a/railties/lib/rails/tasks/log.rake +++ b/railties/lib/rails/tasks/log.rake @@ -1,8 +1,8 @@ namespace :log do - - ## + + ## # Truncates all/specified log files - # ENV['LOGS'] + # ENV['LOGS'] # - defaults to standard environment log files i.e. 'development,test,production' # - ENV['LOGS']=all truncates all files i.e. log/*.log # - ENV['LOGS']='test,development' truncates only specified files @@ -28,7 +28,7 @@ namespace :log do .map { |file| "log/#{file.strip}.log" } .select { |file| File.exist?(file) } end - + def clear_log_file(file) f = File.open(file, "w") f.close diff --git a/railties/lib/rails/test_unit/testing.rake b/railties/lib/rails/test_unit/testing.rake index d172106302..91ff7f4be7 100644 --- a/railties/lib/rails/test_unit/testing.rake +++ b/railties/lib/rails/test_unit/testing.rake @@ -8,7 +8,7 @@ desc "Runs all tests in test folder" task :test do $: << "test" pattern = if ENV.key?("TEST") - ENV["TEST"] + ENV["TEST"] else "test" end diff --git a/railties/test/application/assets_test.rb b/railties/test/application/assets_test.rb index 9396e2cff7..e84e01a41b 100644 --- a/railties/test/application/assets_test.rb +++ b/railties/test/application/assets_test.rb @@ -507,16 +507,16 @@ module ApplicationTests private - def app_with_assets_in_view - app_file "app/assets/javascripts/application.js", "//= require_tree ." - app_file "app/assets/javascripts/xmlhr.js", "function f1() { alert(); }" - app_file "app/views/posts/index.html.erb", "<%= javascript_include_tag 'application' %>" + def app_with_assets_in_view + app_file "app/assets/javascripts/application.js", "//= require_tree ." + app_file "app/assets/javascripts/xmlhr.js", "function f1() { alert(); }" + app_file "app/views/posts/index.html.erb", "<%= javascript_include_tag 'application' %>" - app_file "config/routes.rb", <<-RUBY + app_file "config/routes.rb", <<-RUBY Rails.application.routes.draw do get '/posts', :to => "posts#index" end RUBY - end + end end end diff --git a/railties/test/application/loading_test.rb b/railties/test/application/loading_test.rb index 18f8c89790..d57384d256 100644 --- a/railties/test/application/loading_test.rb +++ b/railties/test/application/loading_test.rb @@ -359,13 +359,13 @@ class LoadingTest < ActiveSupport::TestCase protected - def setup_ar! - ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") - ActiveRecord::Migration.verbose = false - ActiveRecord::Schema.define(version: 1) do - create_table :posts do |t| - t.string :title + def setup_ar! + ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") + ActiveRecord::Migration.verbose = false + ActiveRecord::Schema.define(version: 1) do + create_table :posts do |t| + t.string :title + end end end - end end diff --git a/railties/test/application/middleware/static_test.rb b/railties/test/application/middleware/static_test.rb index 8a06e91297..5cd3e4325e 100644 --- a/railties/test/application/middleware/static_test.rb +++ b/railties/test/application/middleware/static_test.rb @@ -46,11 +46,11 @@ module ApplicationTests test "public_file_server.index_name defaults to 'index'" do app_file "public/index.html", "/index.html" - + require "#{app_path}/config/environment" get "/" - + assert_equal "/index.html\n", last_response.body end diff --git a/railties/test/application/rake/migrations_test.rb b/railties/test/application/rake/migrations_test.rb index b3e95769fa..d608fa1976 100644 --- a/railties/test/application/rake/migrations_test.rb +++ b/railties/test/application/rake/migrations_test.rb @@ -42,17 +42,17 @@ module ApplicationTests `bin/rails generate model user username:string password:string; bin/rails generate migration add_email_to_users email:string` - output = `bin/rails db:migrate` - assert_match(/create_table\(:users\)/, output) - assert_match(/CreateUsers: migrated/, output) - assert_match(/add_column\(:users, :email, :string\)/, output) - assert_match(/AddEmailToUsers: migrated/, output) - - output = `bin/rails db:rollback STEP=2` - assert_match(/drop_table\(:users\)/, output) - assert_match(/CreateUsers: reverted/, output) - assert_match(/remove_column\(:users, :email, :string\)/, output) - assert_match(/AddEmailToUsers: reverted/, output) + output = `bin/rails db:migrate` + assert_match(/create_table\(:users\)/, output) + assert_match(/CreateUsers: migrated/, output) + assert_match(/add_column\(:users, :email, :string\)/, output) + assert_match(/AddEmailToUsers: migrated/, output) + + output = `bin/rails db:rollback STEP=2` + assert_match(/drop_table\(:users\)/, output) + assert_match(/CreateUsers: reverted/, output) + assert_match(/remove_column\(:users, :email, :string\)/, output) + assert_match(/AddEmailToUsers: reverted/, output) end end @@ -107,22 +107,22 @@ module ApplicationTests bin/rails generate migration add_email_to_users email:string; bin/rails db:migrate` - output = `bin/rails db:migrate:status` + output = `bin/rails db:migrate:status` - assert_match(/up\s+\d{14}\s+Create users/, output) - assert_match(/up\s+\d{14}\s+Add email to users/, output) + assert_match(/up\s+\d{14}\s+Create users/, output) + assert_match(/up\s+\d{14}\s+Add email to users/, output) - `bin/rails db:rollback STEP=2` - output = `bin/rails db:migrate:status` + `bin/rails db:rollback STEP=2` + output = `bin/rails db:migrate:status` - assert_match(/down\s+\d{14}\s+Create users/, output) - assert_match(/down\s+\d{14}\s+Add email to users/, output) + assert_match(/down\s+\d{14}\s+Create users/, output) + assert_match(/down\s+\d{14}\s+Add email to users/, output) - `bin/rails db:migrate:redo` - output = `bin/rails db:migrate:status` + `bin/rails db:migrate:redo` + output = `bin/rails db:migrate:status` - assert_match(/up\s+\d{14}\s+Create users/, output) - assert_match(/up\s+\d{14}\s+Add email to users/, output) + assert_match(/up\s+\d{14}\s+Create users/, output) + assert_match(/up\s+\d{14}\s+Add email to users/, output) end end @@ -134,22 +134,22 @@ module ApplicationTests bin/rails generate migration add_email_to_users email:string; bin/rails db:migrate` - output = `bin/rails db:migrate:status` + output = `bin/rails db:migrate:status` - assert_match(/up\s+\d{3,}\s+Create users/, output) - assert_match(/up\s+\d{3,}\s+Add email to users/, output) + assert_match(/up\s+\d{3,}\s+Create users/, output) + assert_match(/up\s+\d{3,}\s+Add email to users/, output) - `bin/rails db:rollback STEP=2` - output = `bin/rails db:migrate:status` + `bin/rails db:rollback STEP=2` + output = `bin/rails db:migrate:status` - assert_match(/down\s+\d{3,}\s+Create users/, output) - assert_match(/down\s+\d{3,}\s+Add email to users/, output) + assert_match(/down\s+\d{3,}\s+Create users/, output) + assert_match(/down\s+\d{3,}\s+Add email to users/, output) - `bin/rails db:migrate:redo` - output = `bin/rails db:migrate:status` + `bin/rails db:migrate:redo` + output = `bin/rails db:migrate:status` - assert_match(/up\s+\d{3,}\s+Create users/, output) - assert_match(/up\s+\d{3,}\s+Add email to users/, output) + assert_match(/up\s+\d{3,}\s+Create users/, output) + assert_match(/up\s+\d{3,}\s+Add email to users/, output) end end @@ -168,10 +168,10 @@ module ApplicationTests `bin/rails db:migrate` - output = `bin/rails db:migrate:status` + output = `bin/rails db:migrate:status` - assert_match(/up\s+001\s+One migration/, output) - assert_match(/up\s+002\s+Two migration/, output) + assert_match(/up\s+001\s+One migration/, output) + assert_match(/up\s+002\s+Two migration/, output) end end diff --git a/railties/test/application/rake/notes_test.rb b/railties/test/application/rake/notes_test.rb index c0ff3af193..b3f379d707 100644 --- a/railties/test/application/rake/notes_test.rb +++ b/railties/test/application/rake/notes_test.rb @@ -140,29 +140,29 @@ module ApplicationTests private - def run_rake_notes(command = "bin/rails notes") - boot_rails - load_tasks + def run_rake_notes(command = "bin/rails notes") + boot_rails + load_tasks - Dir.chdir(app_path) do - output = `#{command}` - lines = output.scan(/\[([0-9\s]+)\]\s/).flatten + Dir.chdir(app_path) do + output = `#{command}` + lines = output.scan(/\[([0-9\s]+)\]\s/).flatten - yield output, lines + yield output, lines + end end - end - def load_tasks - require "rake" - require "rdoc/task" - require "rake/testtask" + def load_tasks + require "rake" + require "rdoc/task" + require "rake/testtask" - Rails.application.load_tasks - end + Rails.application.load_tasks + end - def boot_rails - require "#{app_path}/config/environment" - end + def boot_rails + require "#{app_path}/config/environment" + end end end end diff --git a/railties/test/commands/console_test.rb b/railties/test/commands/console_test.rb index 3f75dc8d58..b3343d9b7f 100644 --- a/railties/test/commands/console_test.rb +++ b/railties/test/commands/console_test.rb @@ -117,38 +117,38 @@ class Rails::ConsoleTest < ActiveSupport::TestCase private - def start(argv = []) - rails_console = Rails::Console.new(app, parse_arguments(argv)) - @output = capture(:stdout) { rails_console.start } - end + def start(argv = []) + rails_console = Rails::Console.new(app, parse_arguments(argv)) + @output = capture(:stdout) { rails_console.start } + end - def app - @app ||= build_app(FakeConsole) - end + def app + @app ||= build_app(FakeConsole) + end - def build_app(console) - mocked_console = Class.new do - attr_reader :sandbox, :console + def build_app(console) + mocked_console = Class.new do + attr_reader :sandbox, :console - def initialize(console) - @console = console - end + def initialize(console) + @console = console + end - def config - self - end + def config + self + end - def sandbox=(arg) - @sandbox = arg - end + def sandbox=(arg) + @sandbox = arg + end - def load_console + def load_console + end end + mocked_console.new(console) end - mocked_console.new(console) - end - def parse_arguments(args) - Rails::Console.parse_arguments(args) - end + def parse_arguments(args) + Rails::Console.parse_arguments(args) + end end diff --git a/railties/test/commands/dbconsole_test.rb b/railties/test/commands/dbconsole_test.rb index 128b930528..5304790c92 100644 --- a/railties/test/commands/dbconsole_test.rb +++ b/railties/test/commands/dbconsole_test.rb @@ -226,39 +226,39 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase private - def app_db_config(results) - Rails.application.config.stub(:database_configuration, results || {}) do - yield + def app_db_config(results) + Rails.application.config.stub(:database_configuration, results || {}) do + yield + end end - end - def dbconsole - @dbconsole ||= Class.new(Rails::DBConsole) do - attr_reader :find_cmd_and_exec_args + def dbconsole + @dbconsole ||= Class.new(Rails::DBConsole) do + attr_reader :find_cmd_and_exec_args - def find_cmd_and_exec(*args) - @find_cmd_and_exec_args = args - end - end.new(nil) - end + def find_cmd_and_exec(*args) + @find_cmd_and_exec_args = args + end + end.new(nil) + end - def start(config = {}, argv = []) - dbconsole.stub(:config, config.stringify_keys) do - dbconsole.stub(:arguments, argv) do - capture_abort { dbconsole.start } + def start(config = {}, argv = []) + dbconsole.stub(:config, config.stringify_keys) do + dbconsole.stub(:arguments, argv) do + capture_abort { dbconsole.start } + end end end - end - def capture_abort - @aborted = false - @output = capture(:stderr) do - begin - yield - rescue SystemExit - @aborted = true + def capture_abort + @aborted = false + @output = capture(:stderr) do + begin + yield + rescue SystemExit + @aborted = true + end end end - end end diff --git a/railties/test/configuration/middleware_stack_proxy_test.rb b/railties/test/configuration/middleware_stack_proxy_test.rb index 586982c8dc..559ce72693 100644 --- a/railties/test/configuration/middleware_stack_proxy_test.rb +++ b/railties/test/configuration/middleware_stack_proxy_test.rb @@ -50,12 +50,12 @@ module Rails private - def assert_playback(msg_name, args) - mock = Minitest::Mock.new - mock.expect :send, nil, [msg_name, args] - @stack.merge_into(mock) - mock.verify - end + def assert_playback(msg_name, args) + mock = Minitest::Mock.new + mock.expect :send, nil, [msg_name, args] + @stack.merge_into(mock) + mock.verify + end end end end diff --git a/railties/test/env_helpers.rb b/railties/test/env_helpers.rb index 68366b336f..1f64d5fda3 100644 --- a/railties/test/env_helpers.rb +++ b/railties/test/env_helpers.rb @@ -3,28 +3,28 @@ require "rails" module EnvHelpers private - def with_rails_env(env) - Rails.instance_variable_set :@_env, nil - switch_env "RAILS_ENV", env do - switch_env "RACK_ENV", nil do - yield + def with_rails_env(env) + Rails.instance_variable_set :@_env, nil + switch_env "RAILS_ENV", env do + switch_env "RACK_ENV", nil do + yield + end end end - end - def with_rack_env(env) - Rails.instance_variable_set :@_env, nil - switch_env "RACK_ENV", env do - switch_env "RAILS_ENV", nil do - yield + def with_rack_env(env) + Rails.instance_variable_set :@_env, nil + switch_env "RACK_ENV", env do + switch_env "RAILS_ENV", nil do + yield + end end end - end - def switch_env(key, value) - old, ENV[key] = ENV[key], value - yield - ensure - ENV[key] = old - end + def switch_env(key, value) + old, ENV[key] = ENV[key], value + yield + ensure + ENV[key] = old + end end diff --git a/railties/test/fixtures/about_yml_plugins/bad_about_yml/init.rb b/railties/test/fixtures/about_yml_plugins/bad_about_yml/init.rb index d4262f8971..636bc1a8ab 100644 --- a/railties/test/fixtures/about_yml_plugins/bad_about_yml/init.rb +++ b/railties/test/fixtures/about_yml_plugins/bad_about_yml/init.rb @@ -1 +1 @@ -# intentionally empty \ No newline at end of file +# intentionally empty diff --git a/railties/test/fixtures/about_yml_plugins/plugin_without_about_yml/init.rb b/railties/test/fixtures/about_yml_plugins/plugin_without_about_yml/init.rb index d4262f8971..636bc1a8ab 100644 --- a/railties/test/fixtures/about_yml_plugins/plugin_without_about_yml/init.rb +++ b/railties/test/fixtures/about_yml_plugins/plugin_without_about_yml/init.rb @@ -1 +1 @@ -# intentionally empty \ No newline at end of file +# intentionally empty diff --git a/railties/test/fixtures/lib/generators/model_generator.rb b/railties/test/fixtures/lib/generators/model_generator.rb index 9098a8a354..0905fa9631 100644 --- a/railties/test/fixtures/lib/generators/model_generator.rb +++ b/railties/test/fixtures/lib/generators/model_generator.rb @@ -1 +1 @@ -raise "I should never be loaded" \ No newline at end of file +raise "I should never be loaded" diff --git a/railties/test/generators/api_app_generator_test.rb b/railties/test/generators/api_app_generator_test.rb index 614ff28da1..bbb814ef4e 100644 --- a/railties/test/generators/api_app_generator_test.rb +++ b/railties/test/generators/api_app_generator_test.rb @@ -73,50 +73,50 @@ class ApiAppGeneratorTest < Rails::Generators::TestCase private - def default_files - files = %W( - .gitignore - Gemfile - Rakefile - config.ru - app/controllers - app/mailers - app/models - app/views/layouts/mailer.html.erb - app/views/layouts/mailer.text.erb - config/environments - config/initializers - config/locales - db - lib - lib/tasks - log - test/fixtures - test/controllers - test/integration - test/models - tmp - vendor - ) - files.concat %w(bin/bundle bin/rails bin/rake) - files - end + def default_files + files = %W( + .gitignore + Gemfile + Rakefile + config.ru + app/controllers + app/mailers + app/models + app/views/layouts/mailer.html.erb + app/views/layouts/mailer.text.erb + config/environments + config/initializers + config/locales + db + lib + lib/tasks + log + test/fixtures + test/controllers + test/integration + test/models + tmp + vendor + ) + files.concat %w(bin/bundle bin/rails bin/rake) + files + end - def skipped_files - %w(app/assets - app/helpers - app/views/layouts/application.html.erb - config/initializers/assets.rb - config/initializers/cookies_serializer.rb - lib/assets - vendor/assets - test/helpers - tmp/cache/assets - public/404.html - public/422.html - public/500.html - public/apple-touch-icon-precomposed.png - public/apple-touch-icon.png - public/favicon.ico) - end + def skipped_files + %w(app/assets + app/helpers + app/views/layouts/application.html.erb + config/initializers/assets.rb + config/initializers/cookies_serializer.rb + lib/assets + vendor/assets + test/helpers + tmp/cache/assets + public/404.html + public/422.html + public/500.html + public/apple-touch-icon-precomposed.png + public/apple-touch-icon.png + public/favicon.ico) + end end diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb index 54c5115fd9..969c2df718 100644 --- a/railties/test/generators/app_generator_test.rb +++ b/railties/test/generators/app_generator_test.rb @@ -745,7 +745,7 @@ class AppGeneratorTest < Rails::Generators::TestCase end sequence = ["install", "exec spring binstub --all", "echo ran after_bundle"] - @sequence_step ||= 0 + @sequence_step ||= 0 ensure_bundler_first = -> command do assert_equal sequence[@sequence_step], command, "commands should be called in sequence #{sequence}" @sequence_step += 1 diff --git a/railties/test/generators/model_generator_test.rb b/railties/test/generators/model_generator_test.rb index d10671a7b4..6451aa75c9 100644 --- a/railties/test/generators/model_generator_test.rb +++ b/railties/test/generators/model_generator_test.rb @@ -6,13 +6,13 @@ class ModelGeneratorTest < Rails::Generators::TestCase include GeneratorsTestHelper arguments %w(Account name:string age:integer) - def test_application_record_skeleton_is_created - run_generator - assert_file "app/models/application_record.rb" do |record| - assert_match(/class ApplicationRecord < ActiveRecord::Base/, record) - assert_match(/self.abstract_class = true/, record) - end - end + def test_application_record_skeleton_is_created + run_generator + assert_file "app/models/application_record.rb" do |record| + assert_match(/class ApplicationRecord < ActiveRecord::Base/, record) + assert_match(/self.abstract_class = true/, record) + end + end def test_help_shows_invoked_generators_options content = run_generator ["--help"] diff --git a/railties/test/railties/mounted_engine_test.rb b/railties/test/railties/mounted_engine_test.rb index 90439fe778..37036db16d 100644 --- a/railties/test/railties/mounted_engine_test.rb +++ b/railties/test/railties/mounted_engine_test.rb @@ -2,9 +2,9 @@ require "isolation/abstract_unit" module ApplicationTests class ApplicationRoutingTest < ActiveSupport::TestCase - require "rack/test" - include Rack::Test::Methods - include ActiveSupport::Testing::Isolation + require "rack/test" + include Rack::Test::Methods + include ActiveSupport::Testing::Isolation def setup build_app diff --git a/railties/test/test_unit/reporter_test.rb b/railties/test/test_unit/reporter_test.rb index 875bc954eb..e22c939981 100644 --- a/railties/test/test_unit/reporter_test.rb +++ b/railties/test/test_unit/reporter_test.rb @@ -156,38 +156,38 @@ class TestUnitReporterTest < ActiveSupport::TestCase end private - def assert_rerun_snippet_count(snippet_count) - assert_equal snippet_count, @output.string.scan(%r{^bin/rails test }).size - end + def assert_rerun_snippet_count(snippet_count) + assert_equal snippet_count, @output.string.scan(%r{^bin/rails test }).size + end - def failed_test - ft = ExampleTest.new(:woot) - ft.failures << begin - raise Minitest::Assertion, "boo" - rescue Minitest::Assertion => e - e - end - ft - end + def failed_test + ft = ExampleTest.new(:woot) + ft.failures << begin + raise Minitest::Assertion, "boo" + rescue Minitest::Assertion => e + e + end + ft + end - def errored_test - et = ExampleTest.new(:woot) - et.failures << Minitest::UnexpectedError.new(ArgumentError.new("wups")) - et - end + def errored_test + et = ExampleTest.new(:woot) + et.failures << Minitest::UnexpectedError.new(ArgumentError.new("wups")) + et + end - def passing_test - ExampleTest.new(:woot) - end + def passing_test + ExampleTest.new(:woot) + end - def skipped_test - st = ExampleTest.new(:woot) - st.failures << begin - raise Minitest::Skip, "skipchurches, misstemples" - rescue Minitest::Assertion => e - e - end - st.time = 10 - st - end + def skipped_test + st = ExampleTest.new(:woot) + st.failures << begin + raise Minitest::Skip, "skipchurches, misstemples" + rescue Minitest::Assertion => e + e + end + st.time = 10 + st + end end diff --git a/tools/profile b/tools/profile index a30369fafe..0fec570875 100755 --- a/tools/profile +++ b/tools/profile @@ -67,36 +67,36 @@ module CodeTools private - def assert_ruby_file_exists(path) - 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/] - fail Error.new("Not a ruby file") unless ruby_extension or ruby_executable - end + def assert_ruby_file_exists(path) + 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/] + fail Error.new("Not a ruby file") unless ruby_extension or ruby_executable + end - module RequireProfiler - private - def require(file, *args) RequireProfiler.profile(file) { super } end - def load(file, *args) RequireProfiler.profile(file) { super } end + module RequireProfiler + private + def require(file, *args) RequireProfiler.profile(file) { super } end + def load(file, *args) RequireProfiler.profile(file) { super } end - @depth, @stats = 0, [] - class << self - attr_accessor :depth - attr_accessor :stats + @depth, @stats = 0, [] + class << self + attr_accessor :depth + attr_accessor :stats - def profile(file) - stats << [file, depth] - self.depth += 1 - result = nil - elapsed = Benchmark.realtime { result = yield } - self.depth -= 1 - stats.pop if stats.last.first == file - stats << [file, depth, elapsed] if result - result - end + def profile(file) + stats << [file, depth] + self.depth += 1 + result = nil + elapsed = Benchmark.realtime { result = yield } + self.depth -= 1 + stats.pop if stats.last.first == file + stats << [file, depth, elapsed] if result + result + end + end end - end end end # ruby-prof printer name causes the third arg to be sent :classify -- cgit v1.2.3