aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorVijay Dev <vijaydev.cse@gmail.com>2014-11-30 10:28:16 +0000
committerVijay Dev <vijaydev.cse@gmail.com>2014-11-30 10:28:16 +0000
commit079ac4a0584b24625266a0e9448503d1b96c2b7f (patch)
tree6a28edeb393cd095de252335f9e3c9cec7c78d13
parentbd9ffa7e1fb433f359ee096a2afd924a652d1912 (diff)
parent6874133f9e5ca79f30f43632da4338d7b82ddeff (diff)
downloadrails-079ac4a0584b24625266a0e9448503d1b96c2b7f.tar.gz
rails-079ac4a0584b24625266a0e9448503d1b96c2b7f.tar.bz2
rails-079ac4a0584b24625266a0e9448503d1b96c2b7f.zip
Merge branch 'master' of github.com:rails/rails
-rw-r--r--.travis.yml11
-rw-r--r--Gemfile10
-rw-r--r--RAILS_VERSION2
-rw-r--r--RELEASING_RAILS.rdoc4
-rw-r--r--actionmailer/CHANGELOG.md51
-rw-r--r--actionmailer/actionmailer.gemspec4
-rw-r--r--actionmailer/lib/action_mailer/base.rb37
-rw-r--r--actionmailer/lib/action_mailer/gem_version.rb6
-rw-r--r--actionmailer/lib/rails/generators/mailer/mailer_generator.rb1
-rw-r--r--actionmailer/lib/rails/generators/mailer/templates/application_mailer.rb4
-rw-r--r--actionmailer/lib/rails/generators/mailer/templates/mailer.rb3
-rw-r--r--actionmailer/test/fixtures/url_test_mailer/exercise_url_for.erb1
-rw-r--r--actionmailer/test/url_test.rb60
-rw-r--r--actionpack/CHANGELOG.md397
-rw-r--r--actionpack/actionpack.gemspec6
-rw-r--r--actionpack/lib/abstract_controller/base.rb2
-rw-r--r--actionpack/lib/action_controller/base.rb2
-rw-r--r--actionpack/lib/action_controller/log_subscriber.rb1
-rw-r--r--actionpack/lib/action_controller/metal/etag_with_template_digest.rb4
-rw-r--r--actionpack/lib/action_controller/metal/http_authentication.rb17
-rw-r--r--actionpack/lib/action_controller/metal/instrumentation.rb2
-rw-r--r--actionpack/lib/action_controller/metal/mime_responds.rb20
-rw-r--r--actionpack/lib/action_controller/metal/renderers.rb3
-rw-r--r--actionpack/lib/action_controller/metal/testing.rb2
-rw-r--r--actionpack/lib/action_controller/test_case.rb26
-rw-r--r--actionpack/lib/action_dispatch/http/mime_type.rb2
-rw-r--r--actionpack/lib/action_dispatch/http/url.rb4
-rw-r--r--actionpack/lib/action_dispatch/journey/formatter.rb15
-rw-r--r--actionpack/lib/action_dispatch/journey/nfa/transition_table.rb2
-rw-r--r--actionpack/lib/action_dispatch/journey/path/pattern.rb4
-rw-r--r--actionpack/lib/action_dispatch/journey/route.rb6
-rw-r--r--actionpack/lib/action_dispatch/journey/router.rb4
-rw-r--r--actionpack/lib/action_dispatch/journey/visualizer/fsm.css4
-rw-r--r--actionpack/lib/action_dispatch/middleware/callbacks.rb2
-rw-r--r--actionpack/lib/action_dispatch/middleware/cookies.rb12
-rw-r--r--actionpack/lib/action_dispatch/middleware/debug_exceptions.rb34
-rw-r--r--actionpack/lib/action_dispatch/middleware/exception_wrapper.rb40
-rw-r--r--actionpack/lib/action_dispatch/middleware/flash.rb11
-rw-r--r--actionpack/lib/action_dispatch/middleware/params_parser.rb2
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/rescues/_source.erb40
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/rescues/missing_template.html.erb4
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb2
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb2
-rw-r--r--actionpack/lib/action_dispatch/routing/inspector.rb4
-rw-r--r--actionpack/lib/action_dispatch/routing/mapper.rb22
-rw-r--r--actionpack/lib/action_dispatch/routing/route_set.rb32
-rw-r--r--actionpack/lib/action_dispatch/routing/url_for.rb6
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions.rb2
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/routing.rb6
-rw-r--r--actionpack/lib/action_dispatch/testing/integration.rb16
-rw-r--r--actionpack/lib/action_dispatch/testing/test_request.rb2
-rw-r--r--actionpack/lib/action_pack/gem_version.rb6
-rw-r--r--actionpack/test/abstract_unit.rb3
-rw-r--r--actionpack/test/controller/filters_test.rb2
-rw-r--r--actionpack/test/controller/flash_hash_test.rb9
-rw-r--r--actionpack/test/controller/http_token_authentication_test.rb23
-rw-r--r--actionpack/test/controller/integration_test.rb42
-rw-r--r--actionpack/test/controller/routing_test.rb13
-rw-r--r--actionpack/test/controller/test_case_test.rb85
-rw-r--r--actionpack/test/controller/url_for_test.rb26
-rw-r--r--actionpack/test/controller/webservice_test.rb10
-rw-r--r--actionpack/test/dispatch/debug_exceptions_test.rb27
-rw-r--r--actionpack/test/dispatch/exception_wrapper_test.rb97
-rw-r--r--actionpack/test/dispatch/mime_type_test.rb4
-rw-r--r--actionpack/test/dispatch/routing/inspector_test.rb2
-rw-r--r--actionpack/test/dispatch/routing/route_set_test.rb20
-rw-r--r--actionpack/test/dispatch/template_assertions_test.rb14
-rw-r--r--actionpack/test/journey/router_test.rb2
-rw-r--r--actionview/CHANGELOG.md200
-rw-r--r--actionview/actionview.gemspec4
-rw-r--r--actionview/lib/action_view/base.rb4
-rw-r--r--actionview/lib/action_view/gem_version.rb6
-rw-r--r--actionview/lib/action_view/helpers/date_helper.rb4
-rw-r--r--actionview/lib/action_view/helpers/form_helper.rb18
-rw-r--r--actionview/lib/action_view/helpers/form_options_helper.rb4
-rw-r--r--actionview/lib/action_view/helpers/form_tag_helper.rb4
-rw-r--r--actionview/lib/action_view/helpers/tag_helper.rb2
-rw-r--r--actionview/lib/action_view/layouts.rb2
-rw-r--r--actionview/lib/action_view/renderer/partial_renderer.rb4
-rw-r--r--actionview/lib/action_view/rendering.rb4
-rw-r--r--actionview/lib/action_view/routing_url_for.rb33
-rw-r--r--actionview/lib/action_view/template/error.rb2
-rw-r--r--actionview/lib/action_view/template/handlers.rb4
-rw-r--r--actionview/lib/action_view/template/handlers/erb.rb2
-rw-r--r--actionview/lib/action_view/template/resolver.rb2
-rw-r--r--actionview/lib/action_view/template/types.rb2
-rw-r--r--actionview/lib/action_view/test_case.rb3
-rw-r--r--actionview/test/abstract_unit.rb2
-rw-r--r--actionview/test/actionpack/controller/view_paths_test.rb2
-rw-r--r--actionview/test/activerecord/debug_helper_test.rb (renamed from actionview/test/template/debug_helper_test.rb)0
-rw-r--r--actionview/test/fixtures/test/_label_with_block.erb2
-rw-r--r--actionview/test/template/date_helper_test.rb2
-rw-r--r--actionview/test/template/erb_util_test.rb2
-rw-r--r--actionview/test/template/form_helper_test.rb36
-rw-r--r--actionview/test/template/form_tag_helper_test.rb6
-rw-r--r--actionview/test/template/render_test.rb2
-rw-r--r--activejob/CHANGELOG.md2
-rw-r--r--activejob/README.md9
-rw-r--r--activejob/activejob.gemspec2
-rw-r--r--activejob/lib/active_job/base.rb2
-rw-r--r--activejob/lib/active_job/gem_version.rb6
-rw-r--r--activejob/lib/active_job/queue_adapters.rb1
-rw-r--r--activejob/lib/active_job/test_helper.rb36
-rw-r--r--activejob/test/cases/test_helper_test.rb36
-rw-r--r--activejob/test/support/delayed_job/delayed/backend/test.rb4
-rw-r--r--activejob/test/support/integration/adapters/sidekiq.rb2
-rw-r--r--activemodel/CHANGELOG.md62
-rw-r--r--activemodel/activemodel.gemspec2
-rw-r--r--activemodel/lib/active_model/dirty.rb2
-rw-r--r--activemodel/lib/active_model/gem_version.rb6
-rw-r--r--activemodel/lib/active_model/serializers/json.rb8
-rw-r--r--activemodel/test/cases/validations/numericality_validation_test.rb4
-rw-r--r--activemodel/test/cases/validations_test.rb2
-rw-r--r--activerecord/CHANGELOG.md1274
-rw-r--r--activerecord/activerecord.gemspec4
-rw-r--r--activerecord/examples/performance.rb4
-rw-r--r--activerecord/lib/active_record/aggregations.rb4
-rw-r--r--activerecord/lib/active_record/associations.rb4
-rw-r--r--activerecord/lib/active_record/associations/alias_tracker.rb15
-rw-r--r--activerecord/lib/active_record/associations/association_scope.rb3
-rw-r--r--activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb4
-rw-r--r--activerecord/lib/active_record/associations/collection_association.rb45
-rw-r--r--activerecord/lib/active_record/associations/has_many_association.rb2
-rw-r--r--activerecord/lib/active_record/associations/has_many_through_association.rb8
-rw-r--r--activerecord/lib/active_record/associations/join_dependency.rb4
-rw-r--r--activerecord/lib/active_record/associations/join_dependency/join_association.rb2
-rw-r--r--activerecord/lib/active_record/associations/preloader.rb1
-rw-r--r--activerecord/lib/active_record/associations/preloader/association.rb11
-rw-r--r--activerecord/lib/active_record/associations/preloader/has_many_through.rb2
-rw-r--r--activerecord/lib/active_record/associations/singular_association.rb3
-rw-r--r--activerecord/lib/active_record/attribute_assignment.rb2
-rw-r--r--activerecord/lib/active_record/attribute_methods.rb4
-rw-r--r--activerecord/lib/active_record/attribute_methods/dirty.rb2
-rw-r--r--activerecord/lib/active_record/attribute_methods/primary_key.rb3
-rw-r--r--activerecord/lib/active_record/attribute_methods/read.rb18
-rw-r--r--activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb2
-rw-r--r--activerecord/lib/active_record/attribute_set.rb18
-rw-r--r--activerecord/lib/active_record/attribute_set/builder.rb83
-rw-r--r--activerecord/lib/active_record/autosave_association.rb6
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb4
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb4
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb8
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb49
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb14
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract_adapter.rb7
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb42
-rw-r--r--activerecord/lib/active_record/connection_adapters/connection_specification.rb2
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb6
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql_adapter.rb10
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb4
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb22
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb35
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql/utils.rb19
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb11
-rw-r--r--activerecord/lib/active_record/connection_adapters/schema_cache.rb4
-rw-r--r--activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb20
-rw-r--r--activerecord/lib/active_record/core.rb4
-rw-r--r--activerecord/lib/active_record/enum.rb2
-rw-r--r--activerecord/lib/active_record/errors.rb21
-rw-r--r--activerecord/lib/active_record/fixtures.rb10
-rw-r--r--activerecord/lib/active_record/gem_version.rb6
-rw-r--r--activerecord/lib/active_record/inheritance.rb2
-rw-r--r--activerecord/lib/active_record/locking/optimistic.rb2
-rw-r--r--activerecord/lib/active_record/migration.rb15
-rw-r--r--activerecord/lib/active_record/model_schema.rb4
-rw-r--r--activerecord/lib/active_record/persistence.rb10
-rw-r--r--activerecord/lib/active_record/railtie.rb2
-rw-r--r--activerecord/lib/active_record/railties/databases.rake12
-rw-r--r--activerecord/lib/active_record/readonly_attributes.rb2
-rw-r--r--activerecord/lib/active_record/reflection.rb6
-rw-r--r--activerecord/lib/active_record/relation.rb31
-rw-r--r--activerecord/lib/active_record/relation/finder_methods.rb10
-rw-r--r--activerecord/lib/active_record/relation/merger.rb12
-rw-r--r--activerecord/lib/active_record/relation/predicate_builder.rb4
-rw-r--r--activerecord/lib/active_record/relation/query_methods.rb25
-rw-r--r--activerecord/lib/active_record/sanitization.rb2
-rw-r--r--activerecord/lib/active_record/schema_dumper.rb7
-rw-r--r--activerecord/lib/active_record/scoping/named.rb2
-rw-r--r--activerecord/lib/active_record/serialization.rb2
-rw-r--r--activerecord/lib/active_record/statement_cache.rb33
-rw-r--r--activerecord/lib/active_record/tasks/mysql_database_tasks.rb1
-rw-r--r--activerecord/lib/active_record/type/hash_lookup_type_map.rb12
-rw-r--r--activerecord/lib/active_record/type/integer.rb7
-rw-r--r--activerecord/lib/active_record/type/serialized.rb2
-rw-r--r--activerecord/lib/active_record/type/string.rb8
-rw-r--r--activerecord/lib/active_record/type/type_map.rb30
-rw-r--r--activerecord/lib/active_record/validations.rb7
-rw-r--r--activerecord/lib/active_record/validations/presence.rb2
-rw-r--r--activerecord/lib/active_record/validations/uniqueness.rb2
-rw-r--r--activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb3
-rw-r--r--activerecord/lib/rails/generators/active_record/migration/templates/migration.rb6
-rw-r--r--activerecord/test/cases/adapters/mysql/active_schema_test.rb2
-rw-r--r--activerecord/test/cases/adapters/mysql/connection_test.rb8
-rw-r--r--activerecord/test/cases/adapters/mysql/reserved_word_test.rb4
-rw-r--r--activerecord/test/cases/adapters/mysql/schema_test.rb2
-rw-r--r--activerecord/test/cases/adapters/mysql2/active_schema_test.rb2
-rw-r--r--activerecord/test/cases/adapters/mysql2/connection_test.rb4
-rw-r--r--activerecord/test/cases/adapters/mysql2/explain_test.rb1
-rw-r--r--activerecord/test/cases/adapters/mysql2/reserved_word_test.rb4
-rw-r--r--activerecord/test/cases/adapters/mysql2/schema_test.rb2
-rw-r--r--activerecord/test/cases/adapters/postgresql/bytea_test.rb9
-rw-r--r--activerecord/test/cases/adapters/postgresql/change_schema_test.rb26
-rw-r--r--activerecord/test/cases/adapters/postgresql/connection_test.rb4
-rw-r--r--activerecord/test/cases/adapters/postgresql/datatype_test.rb7
-rw-r--r--activerecord/test/cases/adapters/postgresql/enum_test.rb2
-rw-r--r--activerecord/test/cases/adapters/postgresql/explain_test.rb1
-rw-r--r--activerecord/test/cases/adapters/postgresql/hstore_test.rb54
-rw-r--r--activerecord/test/cases/adapters/postgresql/json_test.rb11
-rw-r--r--activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb7
-rw-r--r--activerecord/test/cases/adapters/postgresql/rename_table_test.rb34
-rw-r--r--activerecord/test/cases/adapters/postgresql/schema_test.rb2
-rw-r--r--activerecord/test/cases/adapters/postgresql/sql_types_test.rb18
-rw-r--r--activerecord/test/cases/adapters/postgresql/uuid_test.rb27
-rw-r--r--activerecord/test/cases/adapters/sqlite3/explain_test.rb1
-rw-r--r--activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb12
-rw-r--r--activerecord/test/cases/ar_schema_test.rb9
-rw-r--r--activerecord/test/cases/associations/belongs_to_associations_test.rb30
-rw-r--r--activerecord/test/cases/associations/callbacks_test.rb1
-rw-r--r--activerecord/test/cases/associations/eager_load_nested_include_test.rb4
-rw-r--r--activerecord/test/cases/associations/eager_test.rb35
-rw-r--r--activerecord/test/cases/associations/extension_test.rb1
-rw-r--r--activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb23
-rw-r--r--activerecord/test/cases/associations/has_many_associations_test.rb125
-rw-r--r--activerecord/test/cases/associations/has_many_through_associations_test.rb10
-rw-r--r--activerecord/test/cases/associations/has_one_associations_test.rb14
-rw-r--r--activerecord/test/cases/associations/inner_join_association_test.rb2
-rw-r--r--activerecord/test/cases/associations/join_model_test.rb6
-rw-r--r--activerecord/test/cases/associations_test.rb3
-rw-r--r--activerecord/test/cases/attribute_methods_test.rb1
-rw-r--r--activerecord/test/cases/attribute_set_test.rb19
-rw-r--r--activerecord/test/cases/autosave_association_test.rb23
-rw-r--r--activerecord/test/cases/base_test.rb1
-rw-r--r--activerecord/test/cases/bind_parameter_test.rb8
-rw-r--r--activerecord/test/cases/callbacks_test.rb8
-rw-r--r--activerecord/test/cases/finder_test.rb9
-rw-r--r--activerecord/test/cases/fixtures_test.rb15
-rw-r--r--activerecord/test/cases/inheritance_test.rb2
-rw-r--r--activerecord/test/cases/integration_test.rb1
-rw-r--r--activerecord/test/cases/migration/change_table_test.rb6
-rw-r--r--activerecord/test/cases/migration/column_positioning_test.rb12
-rw-r--r--activerecord/test/cases/migration/foreign_key_test.rb12
-rw-r--r--activerecord/test/cases/migration/index_test.rb14
-rw-r--r--activerecord/test/cases/migration_test.rb1
-rw-r--r--activerecord/test/cases/migrator_test.rb4
-rw-r--r--activerecord/test/cases/modules_test.rb1
-rw-r--r--activerecord/test/cases/nested_attributes_test.rb12
-rw-r--r--activerecord/test/cases/persistence_test.rb5
-rw-r--r--activerecord/test/cases/pooled_connections_test.rb2
-rw-r--r--activerecord/test/cases/readonly_test.rb13
-rw-r--r--activerecord/test/cases/reflection_test.rb8
-rw-r--r--activerecord/test/cases/relation/merging_test.rb1
-rw-r--r--activerecord/test/cases/relations_test.rb11
-rw-r--r--activerecord/test/cases/schema_dumper_test.rb17
-rw-r--r--activerecord/test/cases/scoping/default_scoping_test.rb65
-rw-r--r--activerecord/test/cases/scoping/named_scoping_test.rb1
-rw-r--r--activerecord/test/cases/scoping/relation_scoping_test.rb1
-rw-r--r--activerecord/test/cases/test_case.rb2
-rw-r--r--activerecord/test/cases/timestamp_test.rb1
-rw-r--r--activerecord/test/cases/transactions_test.rb7
-rw-r--r--activerecord/test/cases/type/integer_test.rb2
-rw-r--r--activerecord/test/cases/type/string_test.rb4
-rw-r--r--activerecord/test/cases/type/type_map_test.rb47
-rw-r--r--activerecord/test/cases/validations/uniqueness_validation_test.rb2
-rw-r--r--activerecord/test/cases/validations_repair_helper.rb8
-rw-r--r--activerecord/test/cases/validations_test.rb1
-rw-r--r--activerecord/test/config.example.yml6
-rw-r--r--activerecord/test/fixtures/bulbs.yml5
-rw-r--r--activerecord/test/fixtures/computers.yml5
-rw-r--r--activerecord/test/fixtures/developers.yml1
-rw-r--r--activerecord/test/models/customer.rb2
-rw-r--r--activerecord/test/models/developer.rb2
-rw-r--r--activerecord/test/models/pirate.rb4
-rw-r--r--activerecord/test/models/post.rb1
-rw-r--r--activerecord/test/models/ship.rb2
-rw-r--r--activerecord/test/schema/postgresql_specific_schema.rb15
-rw-r--r--activerecord/test/schema/schema.rb5
-rw-r--r--activesupport/CHANGELOG.md383
-rw-r--r--activesupport/activesupport.gemspec2
-rwxr-xr-xactivesupport/bin/generate_tables2
-rw-r--r--activesupport/lib/active_support/core_ext/array/conversions.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/big_decimal/conversions.rb13
-rw-r--r--activesupport/lib/active_support/core_ext/hash/compact.rb6
-rw-r--r--activesupport/lib/active_support/core_ext/hash/except.rb10
-rw-r--r--activesupport/lib/active_support/core_ext/hash/keys.rb8
-rw-r--r--activesupport/lib/active_support/core_ext/numeric/conversions.rb28
-rw-r--r--activesupport/lib/active_support/core_ext/object/deep_dup.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/object/instance_variables.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/object/to_query.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/string/filters.rb9
-rw-r--r--activesupport/lib/active_support/core_ext/string/output_safety.rb5
-rw-r--r--activesupport/lib/active_support/core_ext/time/zones.rb1
-rw-r--r--activesupport/lib/active_support/dependencies.rb33
-rw-r--r--activesupport/lib/active_support/duration.rb3
-rw-r--r--activesupport/lib/active_support/gem_version.rb6
-rw-r--r--activesupport/lib/active_support/message_verifier.rb12
-rw-r--r--activesupport/lib/active_support/multibyte/unicode.rb2
-rw-r--r--activesupport/lib/active_support/notifications.rb2
-rw-r--r--activesupport/lib/active_support/number_helper/number_to_human_converter.rb2
-rw-r--r--activesupport/lib/active_support/testing/assertions.rb2
-rw-r--r--activesupport/lib/active_support/values/time_zone.rb2
-rw-r--r--activesupport/lib/active_support/values/unicode_tables.datbin904640 -> 1001806 bytes
-rw-r--r--activesupport/lib/active_support/xml_mini/jdom.rb2
-rw-r--r--activesupport/test/core_ext/duration_test.rb13
-rw-r--r--activesupport/test/core_ext/enumerable_test.rb4
-rw-r--r--activesupport/test/core_ext/hash_ext_test.rb2
-rw-r--r--activesupport/test/core_ext/object/try_test.rb4
-rw-r--r--activesupport/test/core_ext/range_ext_test.rb4
-rw-r--r--activesupport/test/core_ext/string_ext_test.rb18
-rw-r--r--activesupport/test/dependencies_test.rb237
-rw-r--r--activesupport/test/multibyte_chars_test.rb2
-rw-r--r--activesupport/test/multibyte_conformance_test.rb2
-rw-r--r--activesupport/test/rescuable_test.rb4
-rwxr-xr-xci/travis.rb2
-rw-r--r--guides/CHANGELOG.md28
-rw-r--r--guides/Rakefile4
-rw-r--r--guides/bug_report_templates/action_controller_gem.rb4
-rw-r--r--guides/bug_report_templates/action_controller_master.rb4
-rw-r--r--guides/rails_guides/kindle.rb2
-rw-r--r--guides/source/3_0_release_notes.md4
-rw-r--r--guides/source/4_1_release_notes.md2
-rw-r--r--guides/source/4_2_release_notes.md475
-rw-r--r--guides/source/_welcome.html.erb2
-rw-r--r--guides/source/action_mailer_basics.md51
-rw-r--r--guides/source/action_view_overview.md1
-rw-r--r--guides/source/active_job_basics.md24
-rw-r--r--guides/source/active_record_postgresql.md9
-rw-r--r--guides/source/active_support_core_extensions.md4
-rw-r--r--guides/source/association_basics.md2
-rw-r--r--guides/source/command_line.md21
-rw-r--r--guides/source/configuring.md8
-rw-r--r--guides/source/documents.yaml1
-rw-r--r--guides/source/engines.md41
-rw-r--r--guides/source/form_helpers.md10
-rw-r--r--guides/source/getting_started.md18
-rw-r--r--guides/source/i18n.md2
-rw-r--r--guides/source/rails_on_rack.md4
-rw-r--r--guides/source/security.md2
-rw-r--r--guides/source/testing.md87
-rw-r--r--guides/source/upgrading_ruby_on_rails.md32
-rw-r--r--rails.gemspec4
-rw-r--r--railties/CHANGELOG.md179
-rw-r--r--railties/lib/rails/application.rb28
-rw-r--r--railties/lib/rails/application/bootstrap.rb13
-rw-r--r--railties/lib/rails/application/configuration.rb13
-rw-r--r--railties/lib/rails/application/routes_reloader.rb4
-rw-r--r--railties/lib/rails/code_statistics.rb1
-rw-r--r--railties/lib/rails/commands/dbconsole.rb17
-rw-r--r--railties/lib/rails/commands/destroy.rb2
-rw-r--r--railties/lib/rails/commands/generate.rb2
-rw-r--r--railties/lib/rails/commands/plugin.rb2
-rw-r--r--railties/lib/rails/configuration.rb4
-rw-r--r--railties/lib/rails/engine.rb15
-rw-r--r--railties/lib/rails/gem_version.rb6
-rw-r--r--railties/lib/rails/generators.rb4
-rw-r--r--railties/lib/rails/generators/actions.rb2
-rw-r--r--railties/lib/rails/generators/app_base.rb17
-rw-r--r--railties/lib/rails/generators/base.rb2
-rw-r--r--railties/lib/rails/generators/erb/mailer/mailer_generator.rb25
-rw-r--r--railties/lib/rails/generators/erb/mailer/templates/layout.html.erb5
-rw-r--r--railties/lib/rails/generators/erb/mailer/templates/layout.text.erb1
-rw-r--r--railties/lib/rails/generators/named_base.rb4
-rw-r--r--railties/lib/rails/generators/rails/app/app_generator.rb4
-rw-r--r--railties/lib/rails/generators/rails/app/templates/Gemfile2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/bin/rails2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config.ru2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt5
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/gitignore3
-rw-r--r--railties/lib/rails/generators/rails/plugin/templates/rails/javascripts.js2
-rw-r--r--railties/lib/rails/generators/rails/plugin/templates/rails/stylesheets.css2
-rw-r--r--railties/lib/rails/generators/resource_helpers.rb4
-rw-r--r--railties/lib/rails/info.rb7
-rw-r--r--railties/lib/rails/paths.rb14
-rw-r--r--railties/lib/rails/ruby_version_check.rb6
-rw-r--r--railties/lib/rails/source_annotation_extractor.rb5
-rw-r--r--railties/lib/rails/tasks/statistics.rake3
-rw-r--r--railties/lib/rails/templates/rails/welcome/index.html.erb2
-rw-r--r--railties/lib/rails/test_unit/testing.rake26
-rw-r--r--railties/railties.gemspec2
-rw-r--r--railties/test/application/configuration_test.rb149
-rw-r--r--railties/test/application/middleware/session_test.rb8
-rw-r--r--railties/test/application/multiple_applications_test.rb14
-rw-r--r--railties/test/application/rake/dbs_test.rb9
-rw-r--r--railties/test/application/routing_test.rb20
-rw-r--r--railties/test/application/test_test.rb94
-rw-r--r--railties/test/application/url_generation_test.rb2
-rw-r--r--railties/test/generators/mailer_generator_test.rb24
-rw-r--r--railties/test/generators/migration_generator_test.rb26
-rw-r--r--railties/test/generators/model_generator_test.rb21
-rw-r--r--railties/test/generators/namespaced_generators_test.rb4
-rw-r--r--railties/test/isolation/abstract_unit.rb12
-rw-r--r--railties/test/railties/engine_test.rb2
-rw-r--r--tasks/release.rb2
-rw-r--r--version.rb6
396 files changed, 3261 insertions, 4136 deletions
diff --git a/.travis.yml b/.travis.yml
index 2823a5456f..5352873d8f 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -9,29 +9,26 @@ env:
matrix:
- "GEM=railties"
- "GEM=ap"
- - "GEM=am,amo,as,av,aj"
+ - "GEM=aj"
+ - "GEM=am,amo,as,av"
- "GEM=ar:mysql"
- "GEM=ar:mysql2"
- "GEM=ar:sqlite3"
- "GEM=ar:postgresql"
- "GEM=aj:integration"
rvm:
- - 1.9.3
- - 2.0.0
- 2.1
- ruby-head
- rbx-2
- jruby
matrix:
allow_failures:
- - rvm: 1.9.3
- env: "GEM=ar:mysql"
- - rvm: 2.0.0
- env: "GEM=ar:mysql"
- rvm: ruby-head
env: "GEM=ar:mysql"
- rvm: rbx-2
- rvm: jruby
+ - env: "GEM=aj"
+ - env: "GEM=aj:integration"
fast_finish: true
notifications:
email: false
diff --git a/Gemfile b/Gemfile
index 931c8e85bc..a021f77417 100644
--- a/Gemfile
+++ b/Gemfile
@@ -11,7 +11,7 @@ gem 'rake', '>= 10.3'
gem 'mocha', '~> 0.14', require: false
gem 'rack-cache', '~> 1.2'
-gem 'jquery-rails', '~> 4.0.0.beta2'
+gem 'jquery-rails', github: 'rails/jquery-rails'
gem 'coffee-rails', '~> 4.1.0'
gem 'turbolinks'
gem 'arel', github: 'rails/arel'
@@ -48,7 +48,7 @@ group :job do
gem 'backburner', require: false
gem 'qu-rails', github: "bkeepers/qu", branch: "master", require: false
gem 'qu-redis', require: false
- gem 'delayed_job_active_record', require: false
+ # gem 'delayed_job_active_record', require: false
gem 'sequel', require: false
end
@@ -64,6 +64,10 @@ group :test do
gem 'ruby-prof', '~> 0.11.2'
end
+ platforms :mri_21 do
+ gem 'stackprof'
+ end
+
# platforms :mri_19, :mri_20 do
# gem 'debugger'
# end
@@ -81,7 +85,7 @@ platforms :ruby do
gem 'sqlite3', '~> 1.3.6'
group :db do
- gem 'pg', '>= 0.11.0'
+ gem 'pg', '>= 0.15.0'
gem 'mysql', '>= 2.9.0'
gem 'mysql2', '>= 0.3.13'
end
diff --git a/RAILS_VERSION b/RAILS_VERSION
index b86dc8c0c6..2b915d7d5c 100644
--- a/RAILS_VERSION
+++ b/RAILS_VERSION
@@ -1 +1 @@
-4.2.0.beta4
+5.0.0.alpha
diff --git a/RELEASING_RAILS.rdoc b/RELEASING_RAILS.rdoc
index f8c40f0b02..c80a5816a7 100644
--- a/RELEASING_RAILS.rdoc
+++ b/RELEASING_RAILS.rdoc
@@ -28,7 +28,7 @@ Do not release with Red AWDwR tests.
=== Are the supported plugins working? If not, make it work.
Some Rails plugins are important and need to be supported until Rails 5.
-As these plugins are outside the Rails repository it is easy to break then without knowing
+As these plugins are outside the Rails repository it is easy to break them without knowing
after some refactoring or bug fix, so it is important to check if the following plugins
are working with the versions that will be released:
@@ -54,7 +54,7 @@ addressed, and that can impact your release date.
Ruby implementors have high stakes in making sure Rails works. Be kind and
give them a heads up that Rails will be released soonish.
-This only needs done for major and minor releases, bugfix releases aren't a
+This only need to be done for major and minor releases, bugfix releases aren't a
big enough deal, and are supposed to be backwards compatible.
Send an email just giving a heads up about the upcoming release to these
diff --git a/actionmailer/CHANGELOG.md b/actionmailer/CHANGELOG.md
index 5685871ac9..88b0962e8c 100644
--- a/actionmailer/CHANGELOG.md
+++ b/actionmailer/CHANGELOG.md
@@ -1,50 +1 @@
-* Attachments can be added while rendering the mail template.
-
- Fixes #16974.
-
- *Christian Felder*
-
-* Added `#deliver_later`, `#deliver_now` and deprecate `#deliver` in favour of
- `#deliver_now`. `#deliver_later` will enqueue a job to render and deliver
- the mail instead of delivering it right at that moment. The job is enqueued
- using the new Active Job framework in Rails, and will use whatever queue is
- configured for Rails.
-
- *DHH*, *Abdelkader Boudih*, *Cristian Bica*
-
-* Make `ActionMailer::Previews` methods class methods. Previously they were
- instance methods and `ActionMailer` tries to render a message when they
- are called.
-
- *Cristian Bica*
-
-* Deprecate `*_path` helpers in email views. When used they generate
- non-working links and are not the intention of most developers. Instead
- we recommend to use `*_url` helper.
-
- *Richard Schneeman*
-
-* Raise an exception when attachments are added after `mail` was called.
- This is a safeguard to prevent invalid emails.
-
- Fixes #16163.
-
- *Yves Senn*
-
-* Add `config.action_mailer.show_previews` configuration option.
-
- This config option can be used to enable the mail preview in environments
- other than development (such as staging).
-
- Defaults to `true` in development and false elsewhere.
-
- *Leonard Garvey*
-
-* Allow preview interceptors to be registered through
- `config.action_mailer.preview_interceptors`.
-
- See #15739.
-
- *Yves Senn*
-
-Please check [4-1-stable](https://github.com/rails/rails/blob/4-1-stable/actionmailer/CHANGELOG.md) for previous changes.
+Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/actionmailer/CHANGELOG.md) for previous changes.
diff --git a/actionmailer/actionmailer.gemspec b/actionmailer/actionmailer.gemspec
index abc047d339..f3bddd8382 100644
--- a/actionmailer/actionmailer.gemspec
+++ b/actionmailer/actionmailer.gemspec
@@ -7,7 +7,7 @@ Gem::Specification.new do |s|
s.summary = 'Email composition, delivery, and receiving framework (part of Rails).'
s.description = 'Email on Rails. Compose, deliver, receive, and test emails using the familiar controller/view pattern. First-class support for multipart email and attachments.'
- s.required_ruby_version = '>= 1.9.3'
+ s.required_ruby_version = '>= 2.1.0'
s.license = 'MIT'
@@ -24,5 +24,5 @@ Gem::Specification.new do |s|
s.add_dependency 'activejob', version
s.add_dependency 'mail', ['~> 2.5', '>= 2.5.4']
- s.add_dependency 'rails-dom-testing', '~> 1.0', '>= 1.0.4'
+ s.add_dependency 'rails-dom-testing', '~> 1.0', '>= 1.0.5'
end
diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb
index a70bf1544a..67e316c4fe 100644
--- a/actionmailer/lib/action_mailer/base.rb
+++ b/actionmailer/lib/action_mailer/base.rb
@@ -15,11 +15,17 @@ module ActionMailer
#
# $ rails generate mailer Notifier
#
- # The generated model inherits from <tt>ActionMailer::Base</tt>. A mailer model defines methods
+ # The generated model inherits from <tt>ApplicationMailer</tt> which in turn
+ # inherits from <tt>ActionMailer::Base</tt>. A mailer model defines methods
# used to generate an email message. In these methods, you can setup variables to be used in
# the mailer views, options on the mail itself such as the <tt>:from</tt> address, and attachments.
#
- # class Notifier < ActionMailer::Base
+ # class ApplicationMailer < ActionMailer::Base
+ # default from: 'from@exmaple.com'
+ # layout 'mailer'
+ # end
+ #
+ # class Notifier < ApplicationMailer
# default from: 'no-reply@example.com',
# return_path: 'system@example.com'
#
@@ -84,7 +90,7 @@ module ActionMailer
# name as the method in your mailer model. For example, in the mailer defined above, the template at
# <tt>app/views/notifier/welcome.text.erb</tt> would be used to generate the email.
#
- # Variables defined in the methods of your mailer model are accessible as instance variables in their
+ # Variables defined in the methods of your mailer model are accessible as instance variables in their
# corresponding view.
#
# Emails by default are sent in plain text, so a sample view for our model example might look like this:
@@ -126,11 +132,6 @@ module ActionMailer
#
# config.action_mailer.default_url_options = { host: "example.com" }
#
- # When you decide to set a default <tt>:host</tt> for your mailers, then you need to make sure to use the
- # <tt>only_path: false</tt> option when using <tt>url_for</tt>. Since the <tt>url_for</tt> view helper
- # will generate relative URLs by default when a <tt>:host</tt> option isn't explicitly provided, passing
- # <tt>only_path: false</tt> will ensure that absolute URLs are generated.
- #
# = Sending mail
#
# Once a mailer action and template are defined, you can deliver your message or create it and save it
@@ -178,7 +179,7 @@ module ActionMailer
#
# Sending attachment in emails is easy:
#
- # class ApplicationMailer < ActionMailer::Base
+ # class Notifier < ApplicationMailer
# def welcome(recipient)
# attachments['free_book.pdf'] = File.read('path/to/file.pdf')
# mail(to: recipient, subject: "New account information")
@@ -194,7 +195,7 @@ module ActionMailer
# If you need to send attachments with no content, you need to create an empty view for it,
# or add an empty body parameter like this:
#
- # class ApplicationMailer < ActionMailer::Base
+ # class Notifier < ApplicationMailer
# def welcome(recipient)
# attachments['free_book.pdf'] = File.read('path/to/file.pdf')
# mail(to: recipient, subject: "New account information", body: "")
@@ -206,7 +207,7 @@ module ActionMailer
# You can also specify that a file should be displayed inline with other HTML. This is useful
# if you want to display a corporate logo or a photo.
#
- # class ApplicationMailer < ActionMailer::Base
+ # class Notifier < ApplicationMailer
# def welcome(recipient)
# attachments.inline['photo.png'] = File.read('path/to/photo.png')
# mail(to: recipient, subject: "Here is what we look like")
@@ -245,7 +246,7 @@ module ActionMailer
# Action Mailer provides some intelligent defaults for your emails, these are usually specified in a
# default method inside the class definition:
#
- # class Notifier < ActionMailer::Base
+ # class Notifier < ApplicationMailer
# default sender: 'system@example.com'
# end
#
@@ -263,7 +264,7 @@ module ActionMailer
# As you can pass in any header, you need to either quote the header as a string, or pass it in as
# an underscored symbol, so the following will work:
#
- # class Notifier < ActionMailer::Base
+ # class Notifier < ApplicationMailer
# default 'Content-Transfer-Encoding' => '7bit',
# content_description: 'This is a description'
# end
@@ -271,7 +272,7 @@ module ActionMailer
# Finally, Action Mailer also supports passing <tt>Proc</tt> objects into the default hash, so you
# can define methods that evaluate as the message is being generated:
#
- # class Notifier < ActionMailer::Base
+ # class Notifier < ApplicationMailer
# default 'X-Special-Header' => Proc.new { my_method }
#
# private
@@ -296,7 +297,7 @@ module ActionMailer
# This may be useful, for example, when you want to add default inline attachments for all
# messages sent out by a certain mailer class:
#
- # class Notifier < ActionMailer::Base
+ # class Notifier < ApplicationMailer
# before_action :add_inline_attachment!
#
# def welcome
@@ -703,7 +704,7 @@ module ActionMailer
# The main method that creates the message and renders the email templates. There are
# two ways to call this method, with a block, or without a block.
#
- # It accepts a headers hash. This hash allows you to specify
+ # It accepts a headers hash. This hash allows you to specify
# the most used headers in an email message, these are:
#
# * +:subject+ - The subject of the message, if this is omitted, Action Mailer will
@@ -853,7 +854,7 @@ module ActionMailer
when user_content_type.present?
user_content_type
when m.has_attachments?
- if m.attachments.detect { |a| a.inline? }
+ if m.attachments.detect(&:inline?)
["multipart", "related", params]
else
["multipart", "mixed", params]
@@ -908,7 +909,7 @@ module ActionMailer
if templates.empty?
raise ActionView::MissingTemplate.new(paths, name, paths, false, 'mailer')
else
- templates.uniq { |t| t.formats }.each(&block)
+ templates.uniq(&:formats).each(&block)
end
end
diff --git a/actionmailer/lib/action_mailer/gem_version.rb b/actionmailer/lib/action_mailer/gem_version.rb
index e568b8f6f2..ac79788cf0 100644
--- a/actionmailer/lib/action_mailer/gem_version.rb
+++ b/actionmailer/lib/action_mailer/gem_version.rb
@@ -5,10 +5,10 @@ module ActionMailer
end
module VERSION
- MAJOR = 4
- MINOR = 2
+ MAJOR = 5
+ MINOR = 0
TINY = 0
- PRE = "beta4"
+ PRE = "alpha"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/actionmailer/lib/rails/generators/mailer/mailer_generator.rb b/actionmailer/lib/rails/generators/mailer/mailer_generator.rb
index d5bf864595..094ec85114 100644
--- a/actionmailer/lib/rails/generators/mailer/mailer_generator.rb
+++ b/actionmailer/lib/rails/generators/mailer/mailer_generator.rb
@@ -8,6 +8,7 @@ module Rails
def create_mailer_file
template "mailer.rb", File.join('app/mailers', class_path, "#{file_name}.rb")
+ template "application_mailer.rb", 'app/mailers/application_mailer.rb'
end
hook_for :template_engine, :test_framework
diff --git a/actionmailer/lib/rails/generators/mailer/templates/application_mailer.rb b/actionmailer/lib/rails/generators/mailer/templates/application_mailer.rb
new file mode 100644
index 0000000000..d25d8892dd
--- /dev/null
+++ b/actionmailer/lib/rails/generators/mailer/templates/application_mailer.rb
@@ -0,0 +1,4 @@
+class ApplicationMailer < ActionMailer::Base
+ default from: "from@example.com"
+ layout 'mailer'
+end
diff --git a/actionmailer/lib/rails/generators/mailer/templates/mailer.rb b/actionmailer/lib/rails/generators/mailer/templates/mailer.rb
index edcfb4233d..bce64a5e6e 100644
--- a/actionmailer/lib/rails/generators/mailer/templates/mailer.rb
+++ b/actionmailer/lib/rails/generators/mailer/templates/mailer.rb
@@ -1,6 +1,5 @@
<% module_namespacing do -%>
-class <%= class_name %> < ActionMailer::Base
- default from: "from@example.com"
+class <%= class_name %> < ApplicationMailer
<% actions.each do |action| -%>
# Subject can be set in your I18n file at config/locales/en.yml
diff --git a/actionmailer/test/fixtures/url_test_mailer/exercise_url_for.erb b/actionmailer/test/fixtures/url_test_mailer/exercise_url_for.erb
new file mode 100644
index 0000000000..0322c1191e
--- /dev/null
+++ b/actionmailer/test/fixtures/url_test_mailer/exercise_url_for.erb
@@ -0,0 +1 @@
+<%= url_for(@options) %> <%= @url %>
diff --git a/actionmailer/test/url_test.rb b/actionmailer/test/url_test.rb
index be7532d42f..7928fe9542 100644
--- a/actionmailer/test/url_test.rb
+++ b/actionmailer/test/url_test.rb
@@ -23,9 +23,32 @@ class UrlTestMailer < ActionMailer::Base
mail(to: recipient, subject: "[Signed up] Welcome #{recipient}",
from: "system@loudthinking.com", date: Time.local(2004, 12, 12))
end
+
+ def exercise_url_for(options)
+ @options = options
+ @url = url_for(@options)
+ mail(from: 'from@example.com', to: 'to@example.com', subject: 'subject')
+ end
end
class ActionMailerUrlTest < ActionMailer::TestCase
+ class DummyModel
+ def self.model_name
+ OpenStruct.new(route_key: 'dummy_model')
+ end
+
+ def persisted?
+ false
+ end
+
+ def model_name
+ self.class.model_name
+ end
+
+ def to_model
+ self
+ end
+ end
def encode( text, charset="UTF-8" )
quoted_printable( text, charset )
@@ -40,10 +63,47 @@ class ActionMailerUrlTest < ActionMailer::TestCase
mail
end
+ def assert_url_for(expected, options, relative = false)
+ expected = "http://www.basecamphq.com#{expected}" if expected.start_with?('/') && !relative
+ urls = UrlTestMailer.exercise_url_for(options).body.to_s.chomp.split
+
+ assert_equal expected, urls.first
+ assert_equal expected, urls.second
+ end
+
def setup
@recipient = 'test@localhost'
end
+ def test_url_for
+ UrlTestMailer.delivery_method = :test
+
+ AppRoutes.draw do
+ get ':controller(/:action(/:id))'
+ get '/welcome' => 'foo#bar', as: 'welcome'
+ get '/dummy_model' => 'foo#baz', as: 'dummy_model'
+ end
+
+ # string
+ assert_url_for 'http://foo/', 'http://foo/'
+
+ # symbol
+ assert_url_for '/welcome', :welcome
+
+ # hash
+ assert_url_for '/a/b/c', controller: 'a', action: 'b', id: 'c'
+ assert_url_for '/a/b/c', {controller: 'a', action: 'b', id: 'c', only_path: true}, true
+
+ # model
+ assert_url_for '/dummy_model', DummyModel.new
+
+ # class
+ assert_url_for '/dummy_model', DummyModel
+
+ # array
+ assert_url_for '/dummy_model' , [DummyModel]
+ end
+
def test_signed_up_with_url
UrlTestMailer.delivery_method = :test
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md
index 158b22c0cc..556545c0d8 100644
--- a/actionpack/CHANGELOG.md
+++ b/actionpack/CHANGELOG.md
@@ -1,396 +1 @@
-* Deprecate the `only_path` option on `*_path` helpers.
-
- In cases where this option is set to `true`, the option is redundant and can
- be safely removed; otherwise, the corresponding `*_url` helper should be
- used instead.
-
- Fixes #17294.
-
- *Dan Olson*, *Godfrey Chan*
-
-* Improve Journey compliance to RFC 3986.
-
- The scanner in Journey failed to recognize routes that use literals
- from the sub-delims section of RFC 3986. It's now able to parse those
- authorized delimiters and route as expected.
-
- Fixes #17212.
-
- *Nicolas Cavigneaux*
-
-* Deprecate implicit Array conversion for Response objects. It was added
- (using `#to_ary`) so we could conveniently use implicit splatting:
-
- status, headers, body = response
-
- But it also means `response + response` works and `[response].flatten`
- cascades down to the Rack body. Nonsense behavior. Instead, rely on
- explicit conversion and splatting with `#to_a`:
-
- status, header, body = *response
-
- *Jeremy Kemper*
-
-* Don't rescue `IPAddr::InvalidAddressError`.
-
- `IPAddr::InvalidAddressError` does not exist in Ruby 1.9.3
- and fails for JRuby in 1.9 mode.
-
- *Peter Suschlik*
-
-* Fix bug where the router would ignore any constraints added to redirect
- routes.
-
- Fixes #16605.
-
- *Agis Anastasopoulos*
-
-* Allow `config.action_dispatch.trusted_proxies` to accept an IPAddr object.
-
- Example:
-
- # config/environments/production.rb
- config.action_dispatch.trusted_proxies = IPAddr.new('4.8.15.0/16')
-
- *Sam Aarons*
-
-* Avoid duplicating routes for HEAD requests.
-
- Instead of duplicating the routes, we will first match the HEAD request to
- HEAD routes. If no match is found, we will then map the HEAD request to
- GET routes.
-
- *Guo Xiang Tan*, *Andrew White*
-
-* Requests that hit `ActionDispatch::Static` can now take advantage
- of gzipped assets on disk. By default a gzip asset will be served if
- the client supports gzip and a compressed file is on disk.
-
- *Richard Schneeman*
-
-* `ActionController::Parameters` will stop inheriting from `Hash` and
- `HashWithIndifferentAccess` in the next major release. If you use any method
- that is not available on `ActionController::Parameters` you should consider
- calling `#to_h` to convert it to a `Hash` first before calling that method.
-
- *Prem Sichanugrist*
-
-* `ActionController::Parameters#to_h` now returns a `Hash` with unpermitted
- keys removed. This change is to reflect on a security concern where some
- method performed on an `ActionController::Parameters` may yield a `Hash`
- object which does not maintain `permitted?` status. If you would like to
- get a `Hash` with all the keys intact, duplicate and mark it as permitted
- before calling `#to_h`.
-
- params = ActionController::Parameters.new({
- name: 'Senjougahara Hitagi',
- oddity: 'Heavy stone crab'
- })
- params.to_h
- # => {}
-
- unsafe_params = params.dup.permit!
- unsafe_params.to_h
- # => {"name"=>"Senjougahara Hitagi", "oddity"=>"Heavy stone crab"}
-
- safe_params = params.permit(:name)
- safe_params.to_h
- # => {"name"=>"Senjougahara Hitagi"}
-
- This change is consider a stopgap as we cannot change the code to stop
- `ActionController::Parameters` to inherit from `HashWithIndifferentAccess`
- in the next minor release.
-
- *Prem Sichanugrist*
-
-* Deprecated `TagAssertions`.
-
- *Kasper Timm Hansen*
-
-* Use the Active Support JSON encoder for cookie jars using the `:json` or
- `:hybrid` serializer. This allows you to serialize custom Ruby objects into
- cookies by defining the `#as_json` hook on such objects.
-
- Fixes #16520.
-
- *Godfrey Chan*
-
-* Add `config.action_dispatch.cookies_digest` option for setting custom
- digest. The default remains the same - 'SHA1'.
-
- *Łukasz Strzałkowski*
-
-* Move `respond_with` (and the class-level `respond_to`) to
- the `responders` gem.
-
- *José Valim*
-
-* When your templates change, browser caches bust automatically.
-
- New default: the template digest is automatically included in your ETags.
- When you call `fresh_when @post`, the digest for `posts/show.html.erb`
- is mixed in so future changes to the HTML will blow HTTP caches for you.
- This makes it easy to HTTP-cache many more of your actions.
-
- If you render a different template, you can now pass the `:template`
- option to include its digest instead:
-
- fresh_when @post, template: 'widgets/show'
-
- Pass `template: false` to skip the lookup. To turn this off entirely, set:
-
- config.action_controller.etag_with_template_digest = false
-
- *Jeremy Kemper*
-
-* Remove deprecated `AbstractController::Helpers::ClassMethods::MissingHelperError`
- in favor of `AbstractController::Helpers::MissingHelperError`.
-
- *Yves Senn*
-
-* Fix `assert_template` not being able to assert that no files were rendered.
-
- *Guo Xiang Tan*
-
-* Extract source code for the entire exception stack trace for
- better debugging and diagnosis.
-
- *Ryan Dao*
-
-* Allows ActionDispatch::Request::LOCALHOST to match any IPv4 127.0.0.0/8
- loopback address.
-
- *Earl St Sauver*, *Sven Riedel*
-
-* Preserve original path in `ShowExceptions` middleware by stashing it as
- `env["action_dispatch.original_path"]`
-
- `ActionDispatch::ShowExceptions` overwrites `PATH_INFO` with the status code
- for the exception defined in `ExceptionWrapper`, so the path
- the user was visiting when an exception occurred was not previously
- available to any custom exceptions_app. The original `PATH_INFO` is now
- stashed in `env["action_dispatch.original_path"]`.
-
- *Grey Baker*
-
-* Use `String#bytesize` instead of `String#size` when checking for cookie
- overflow.
-
- *Agis Anastasopoulos*
-
-* `render nothing: true` or rendering a `nil` body no longer add a single
- space to the response body.
-
- The old behavior was added as a workaround for a bug in an early version of
- Safari, where the HTTP headers are not returned correctly if the response
- body has a 0-length. This is been fixed since and the workaround is no
- longer necessary.
-
- Use `render body: ' '` if the old behavior is desired.
-
- See #14883 for details.
-
- *Godfrey Chan*
-
-* Prepend a JS comment to JSONP callbacks. Addresses CVE-2014-4671
- ("Rosetta Flash").
-
- *Greg Campbell*
-
-* Because URI paths may contain non US-ASCII characters we need to force
- the encoding of any unescaped URIs to UTF-8 if they are US-ASCII.
- This essentially replicates the functionality of the monkey patch to
- URI.parser.unescape in active_support/core_ext/uri.rb.
-
- Fixes #16104.
-
- *Karl Entwistle*
-
-* Generate shallow paths for all children of shallow resources.
-
- Fixes #15783.
-
- *Seb Jacobs*
-
-* JSONP responses are now rendered with the `text/javascript` content type
- when rendering through a `respond_to` block.
-
- Fixes #15081.
-
- *Lucas Mazza*
-
-* Add `config.action_controller.always_permitted_parameters` to configure which
- parameters are permitted globally. The default value of this configuration is
- `['controller', 'action']`.
-
- *Gary S. Weaver*, *Rafael Chacon*
-
-* Fix env['PATH_INFO'] missing leading slash when a rack app mounted at '/'.
-
- Fixes #15511.
-
- *Larry Lv*
-
-* ActionController::Parameters#require now accepts `false` values.
-
- Fixes #15685.
-
- *Sergio Romano*
-
-* With authorization header `Authorization: Token token=`, `authenticate` now
- recognize token as nil, instead of "token".
-
- Fixes #14846.
-
- *Larry Lv*
-
-* Ensure the controller is always notified as soon as the client disconnects
- during live streaming, even when the controller is blocked on a write.
-
- *Nicholas Jakobsen*, *Matthew Draper*
-
-* Routes specifying 'to:' must be a string that contains a "#" or a rack
- application. Use of a symbol should be replaced with `action: symbol`.
- Use of a string without a "#" should be replaced with `controller: string`.
-
- *Aaron Patterson*
-
-* Fix URL generation with `:trailing_slash` such that it does not add
- a trailing slash after `.:format`
-
- *Dan Langevin*
-
-* Build full URI as string when processing path in integration tests for
- performance reasons.
-
- *Guo Xiang Tan*
-
-* Fix `'Stack level too deep'` when rendering `head :ok` in an action method
- called 'status' in a controller.
-
- Fixes #13905.
-
- *Christiaan Van den Poel*
-
-* Add MKCALENDAR HTTP method (RFC 4791).
-
- *Sergey Karpesh*
-
-* Instrument fragment cache metrics.
-
- Adds `:controller`: and `:action` keys to the instrumentation payload
- for the `*_fragment.action_controller` notifications. This allows tracking
- e.g. the fragment cache hit rates for each controller action.
-
- *Daniel Schierbeck*
-
-* Always use the provided port if the protocol is relative.
-
- Fixes #15043.
-
- *Guilherme Cavalcanti*, *Andrew White*
-
-* Moved `params[request_forgery_protection_token]` into its own method
- and improved tests.
-
- Fixes #11316.
-
- *Tom Kadwill*
-
-* Added verification of route constraints given as a Proc or an object responding
- to `:matches?`. Previously, when given an non-complying object, it would just
- silently fail to enforce the constraint. It will now raise an `ArgumentError`
- when setting up the routes.
-
- *Xavier Defrang*
-
-* Properly treat the entire IPv6 User Local Address space as private for
- purposes of remote IP detection. Also handle uppercase private IPv6
- addresses.
-
- Fixes #12638.
-
- *Caleb Spare*
-
-* Fixed an issue with migrating legacy json cookies.
-
- Previously, the `VerifyAndUpgradeLegacySignedMessage` assumes all incoming
- cookies are marshal-encoded. This is not the case when `secret_token` is
- used in conjunction with the `:json` or `:hybrid` serializer.
-
- In those case, when upgrading to use `secret_key_base`, this would cause a
- `TypeError: incompatible marshal file format` and a 500 error for the user.
-
- Fixes #14774.
-
- *Godfrey Chan*
-
-* Make URL escaping more consistent:
-
- 1. Escape '%' characters in URLs - only unescaped data should be passed to URL helpers
- 2. Add an `escape_segment` helper to `Router::Utils` that escapes '/' characters
- 3. Use `escape_segment` rather than `escape_fragment` in optimized URL generation
- 4. Use `escape_segment` rather than `escape_path` in URL generation
-
- For point 4 there are two exceptions. Firstly, when a route uses wildcard segments
- (e.g. `*foo`) then we use `escape_path` as the value may contain '/' characters. This
- means that wildcard routes can't be optimized. Secondly, if a `:controller` segment
- is used in the path then this uses `escape_path` as the controller may be namespaced.
-
- Fixes #14629, #14636 and #14070.
-
- *Andrew White*, *Edho Arief*
-
-* Add alias `ActionDispatch::Http::UploadedFile#to_io` to
- `ActionDispatch::Http::UploadedFile#tempfile`.
-
- *Tim Linquist*
-
-* Returns null type format when format is not know and controller is using `any`
- format block.
-
- Fixes #14462.
-
- *Rafael Mendonça França*
-
-* Improve routing error page with fuzzy matching search.
-
- *Winston*
-
-* Only make deeply nested routes shallow when parent is shallow.
-
- Fixes #14684.
-
- *Andrew White*, *James Coglan*
-
-* Append link to bad code to backtrace when exception is `SyntaxError`.
-
- *Boris Kuznetsov*
-
-* Swapped the parameters of assert_equal in `assert_select` so that the
- proper values were printed correctly.
-
- Fixes #14422.
-
- *Vishal Lal*
-
-* The method `shallow?` returns false if the parent resource is a singleton so
- we need to check if we're not inside a nested scope before copying the :path
- and :as options to their shallow equivalents.
-
- Fixes #14388.
-
- *Andrew White*
-
-* Make logging of CSRF failures optional (but on by default) with the
- `log_warning_on_csrf_failure` configuration setting in
- `ActionController::RequestForgeryProtection`.
-
- *John Barton*
-
-* Fix URL generation in controller tests with request-dependent
- `default_url_options` methods.
-
- *Tony Wooster*
-
-Please check [4-1-stable](https://github.com/rails/rails/blob/4-1-stable/actionpack/CHANGELOG.md) for previous changes.
+Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/actionpack/CHANGELOG.md) for previous changes.
diff --git a/actionpack/actionpack.gemspec b/actionpack/actionpack.gemspec
index 5196e67e55..0f5880c1a7 100644
--- a/actionpack/actionpack.gemspec
+++ b/actionpack/actionpack.gemspec
@@ -7,7 +7,7 @@ Gem::Specification.new do |s|
s.summary = 'Web-flow and rendering framework putting the VC in MVC (part of Rails).'
s.description = 'Web apps on Rails. Simple, battle-tested conventions for building and testing MVC web applications. Works with any Rack-compatible server.'
- s.required_ruby_version = '>= 1.9.3'
+ s.required_ruby_version = '>= 2.1.0'
s.license = 'MIT'
@@ -21,10 +21,10 @@ Gem::Specification.new do |s|
s.add_dependency 'activesupport', version
- s.add_dependency 'rack', '~> 1.6.0.beta'
+ s.add_dependency 'rack', '~> 1.6.0.beta2'
s.add_dependency 'rack-test', '~> 0.6.2'
s.add_dependency 'rails-html-sanitizer', '~> 1.0', '>= 1.0.1'
- s.add_dependency 'rails-dom-testing', '~> 1.0', '>= 1.0.4'
+ s.add_dependency 'rails-dom-testing', '~> 1.0', '>= 1.0.5'
s.add_dependency 'actionview', version
s.add_development_dependency 'activemodel', version
diff --git a/actionpack/lib/abstract_controller/base.rb b/actionpack/lib/abstract_controller/base.rb
index 4026dab2ce..51c661f735 100644
--- a/actionpack/lib/abstract_controller/base.rb
+++ b/actionpack/lib/abstract_controller/base.rb
@@ -82,7 +82,7 @@ module AbstractController
# Except for public instance methods of Base and its ancestors
internal_methods +
# Be sure to include shadowed public instance methods of this class
- public_instance_methods(false)).uniq.map { |x| x.to_s } -
+ public_instance_methods(false)).uniq.map(&:to_s) -
# And always exclude explicitly hidden actions
hidden_actions.to_a
diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb
index 7bbf938987..5cb11bc479 100644
--- a/actionpack/lib/action_controller/base.rb
+++ b/actionpack/lib/action_controller/base.rb
@@ -44,7 +44,7 @@ module ActionController
# The full request object is available via the request accessor and is primarily used to query for HTTP headers:
#
# def server_ip
- # location = request.env["SERVER_ADDR"]
+ # location = request.env["REMOTE_ADDR"]
# render plain: "This server hosted at #{location}"
# end
#
diff --git a/actionpack/lib/action_controller/log_subscriber.rb b/actionpack/lib/action_controller/log_subscriber.rb
index 89fa75f025..d3f93a5352 100644
--- a/actionpack/lib/action_controller/log_subscriber.rb
+++ b/actionpack/lib/action_controller/log_subscriber.rb
@@ -1,4 +1,3 @@
-
module ActionController
class LogSubscriber < ActiveSupport::LogSubscriber
INTERNAL_PARAMS = %w(controller action format _method only_path)
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 3ca0c6837a..f9303efe6c 100644
--- a/actionpack/lib/action_controller/metal/etag_with_template_digest.rb
+++ b/actionpack/lib/action_controller/metal/etag_with_template_digest.rb
@@ -7,8 +7,8 @@ module ActionController
#
# config.action_controller.etag_with_template_digest = false
#
- # Override the template to digest by passing `:template` to `fresh_when`
- # and `stale?` calls. For example:
+ # Override the template to digest by passing +:template+ to +fresh_when+
+ # and +stale?+ calls. For example:
#
# # We're going to render widgets/show, not posts/show
# fresh_when @post, template: 'widgets/show'
diff --git a/actionpack/lib/action_controller/metal/http_authentication.rb b/actionpack/lib/action_controller/metal/http_authentication.rb
index 25c123edf7..fd578d60ca 100644
--- a/actionpack/lib/action_controller/metal/http_authentication.rb
+++ b/actionpack/lib/action_controller/metal/http_authentication.rb
@@ -397,6 +397,7 @@ module ActionController
#
# RewriteRule ^(.*)$ dispatch.fcgi [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]
module Token
+ TOKEN_KEY = 'token='
TOKEN_REGEX = /^Token /
AUTHN_PAIR_DELIMITERS = /(?:,|;|\t+)/
extend self
@@ -462,16 +463,22 @@ module ActionController
raw_params.map { |param| param.split %r/=(.+)?/ }
end
- # This removes the `"` characters wrapping the value.
+ # This removes the <tt>"</tt> characters wrapping the value.
def rewrite_param_values(array_params)
array_params.each { |param| (param[1] || "").gsub! %r/^"|"$/, '' }
end
# This method takes an authorization body and splits up the key-value
- # pairs by the standardized `:`, `;`, or `\t` delimiters defined in
- # `AUTHN_PAIR_DELIMITERS`.
+ # pairs by the standardized <tt>:</tt>, <tt>;</tt>, or <tt>\t</tt>
+ # delimiters defined in +AUTHN_PAIR_DELIMITERS+.
def raw_params(auth)
- auth.sub(TOKEN_REGEX, '').split(/\s*#{AUTHN_PAIR_DELIMITERS}\s*/)
+ _raw_params = auth.sub(TOKEN_REGEX, '').split(/\s*#{AUTHN_PAIR_DELIMITERS}\s*/)
+
+ if !(_raw_params.first =~ %r{\A#{TOKEN_KEY}})
+ _raw_params[0] = "#{TOKEN_KEY}#{_raw_params.first}"
+ end
+
+ _raw_params
end
# Encodes the given token and options into an Authorization header value.
@@ -481,7 +488,7 @@ module ActionController
#
# Returns String.
def encode_credentials(token, options = {})
- values = ["token=#{token.to_s.inspect}"] + options.map do |key, value|
+ values = ["#{TOKEN_KEY}#{token.to_s.inspect}"] + options.map do |key, value|
"#{key}=#{value.to_s.inspect}"
end
"Token #{values * ", "}"
diff --git a/actionpack/lib/action_controller/metal/instrumentation.rb b/actionpack/lib/action_controller/metal/instrumentation.rb
index b0e164bc57..bef7545e71 100644
--- a/actionpack/lib/action_controller/metal/instrumentation.rb
+++ b/actionpack/lib/action_controller/metal/instrumentation.rb
@@ -21,7 +21,7 @@ module ActionController
:action => self.action_name,
:params => request.filtered_parameters,
:format => request.format.try(:ref),
- :method => request.method,
+ :method => request.request_method,
:path => (request.fullpath rescue "unknown")
}
diff --git a/actionpack/lib/action_controller/metal/mime_responds.rb b/actionpack/lib/action_controller/metal/mime_responds.rb
index 591f881a53..ac1f209232 100644
--- a/actionpack/lib/action_controller/metal/mime_responds.rb
+++ b/actionpack/lib/action_controller/metal/mime_responds.rb
@@ -135,18 +135,6 @@ module ActionController #:nodoc:
#
# render json: @people
#
- # Since this is a common pattern, you can use the class method respond_to
- # with the respond_with method to have the same results:
- #
- # class PeopleController < ApplicationController
- # respond_to :html, :xml, :json
- #
- # def index
- # @people = Person.all
- # respond_with(@people)
- # end
- # end
- #
# Formats can have different variants.
#
# The request variant is a specialization of the request format, like <tt>:tablet</tt>,
@@ -214,8 +202,8 @@ module ActionController #:nodoc:
# format.html.phone # this gets rendered
# end
#
- # Be sure to check the documentation of +respond_with+ and
- # <tt>ActionController::MimeResponds.respond_to</tt> for more examples.
+ # Be sure to check the documentation of <tt>ActionController::MimeResponds.respond_to</tt>
+ # for more examples.
def respond_to(*mimes)
raise ArgumentError, "respond_to takes either types or a block, never both" if mimes.any? && block_given?
@@ -234,8 +222,8 @@ module ActionController #:nodoc:
# A container for responses available from the current controller for
# requests for different mime-types sent to a particular action.
#
- # The public controller methods +respond_with+ and +respond_to+ may be called
- # with a block that is used to define responses to different mime-types, e.g.
+ # The public controller methods +respond_to+ may be called with a block
+ # that is used to define responses to different mime-types, e.g.
# for +respond_to+ :
#
# respond_to do |format|
diff --git a/actionpack/lib/action_controller/metal/renderers.rb b/actionpack/lib/action_controller/metal/renderers.rb
index bc94536c8c..45d3962494 100644
--- a/actionpack/lib/action_controller/metal/renderers.rb
+++ b/actionpack/lib/action_controller/metal/renderers.rb
@@ -86,8 +86,7 @@ module ActionController
# end
# end
# To use renderers and their mime types in more concise ways, see
- # <tt>ActionController::MimeResponds::ClassMethods.respond_to</tt> and
- # <tt>ActionController::MimeResponds#respond_with</tt>
+ # <tt>ActionController::MimeResponds::ClassMethods.respond_to</tt>
def self.add(key, &block)
define_method(_render_with_renderer_method_name(key), &block)
RENDERERS << key.to_sym
diff --git a/actionpack/lib/action_controller/metal/testing.rb b/actionpack/lib/action_controller/metal/testing.rb
index dd8da4b5dc..d01927b7cb 100644
--- a/actionpack/lib/action_controller/metal/testing.rb
+++ b/actionpack/lib/action_controller/metal/testing.rb
@@ -24,7 +24,7 @@ module ActionController
module ClassMethods
def before_filters
- _process_action_callbacks.find_all{|x| x.kind == :before}.map{|x| x.name}
+ _process_action_callbacks.find_all{|x| x.kind == :before}.map(&:name)
end
end
end
diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb
index 41d33d4396..cd92962dc3 100644
--- a/actionpack/lib/action_controller/test_case.rb
+++ b/actionpack/lib/action_controller/test_case.rb
@@ -2,6 +2,7 @@ require 'rack/session/abstract/id'
require 'active_support/core_ext/object/to_query'
require 'active_support/core_ext/module/anonymous'
require 'active_support/core_ext/hash/keys'
+require 'active_support/deprecation'
require 'rails-dom-testing'
@@ -689,7 +690,7 @@ module ActionController
private
def document_root_element
- html_document
+ html_document.root
end
def check_required_ivars
@@ -710,7 +711,28 @@ module ActionController
:relative_url_root => nil,
:_recall => @request.path_parameters)
- url, query_string = @routes.path_for(options).split("?", 2)
+ if route_name = options.delete(:use_route)
+ ActiveSupport::Deprecation.warn <<-MSG.squish
+ Passing the `use_route` option in functional tests are deprecated.
+ Support for this option in the `process` method (and the related
+ `get`, `head`, `post`, `patch`, `put` and `delete` helpers) will
+ be removed in the next version without replacement.
+
+ Functional tests are essentially unit tests for controllers and
+ they should not require knowledge to how the application's routes
+ are configured. Instead, you should explicitly pass the appropiate
+ params to the `process` method.
+
+ Previously the engines guide also contained an incorrect example
+ that recommended using this option to test an engine's controllers
+ within the dummy application. That recommendation was incorrect
+ and has since been corrected. Instead, you should override the
+ `@routes` variable in the test case with `Foo::Engine.routes`. See
+ the updated engines guide for details.
+ MSG
+ end
+
+ url, query_string = @routes.path_for(options, route_name).split("?", 2)
@request.env["SCRIPT_NAME"] = @controller.config.relative_url_root
@request.env["PATH_INFO"] = url
diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb
index b9d5009683..047a17937a 100644
--- a/actionpack/lib/action_dispatch/http/mime_type.rb
+++ b/actionpack/lib/action_dispatch/http/mime_type.rb
@@ -6,7 +6,7 @@ require 'active_support/core_ext/string/starts_ends_with'
module Mime
class Mimes < Array
def symbols
- @symbols ||= map { |m| m.to_sym }
+ @symbols ||= map(&:to_sym)
end
%w(<< concat shift unshift push pop []= clear compact! collect!
diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb
index 6b8dcaf497..22c0de2ac2 100644
--- a/actionpack/lib/action_dispatch/http/url.rb
+++ b/actionpack/lib/action_dispatch/http/url.rb
@@ -68,7 +68,9 @@ module ActionDispatch
end
def add_anchor(path, anchor)
- path << "##{Journey::Router::Utils.escape_fragment(anchor.to_param.to_s)}"
+ if anchor
+ path << "##{Journey::Router::Utils.escape_fragment(anchor.to_param)}"
+ end
end
def extract_domain_from(host, tld_length)
diff --git a/actionpack/lib/action_dispatch/journey/formatter.rb b/actionpack/lib/action_dispatch/journey/formatter.rb
index 992c1a9efe..177f586c0e 100644
--- a/actionpack/lib/action_dispatch/journey/formatter.rb
+++ b/actionpack/lib/action_dispatch/journey/formatter.rb
@@ -1,4 +1,5 @@
require 'action_controller/metal/exceptions'
+require 'active_support/deprecation'
module ActionDispatch
module Journey
@@ -80,6 +81,9 @@ module ActionDispatch
if named_routes.key?(name)
yield named_routes[name]
else
+ # Make sure we don't show the deprecation warning more than once
+ warned = false
+
routes = non_recursive(cache, options)
hash = routes.group_by { |_, r| r.score(options) }
@@ -88,6 +92,17 @@ module ActionDispatch
break if score < 0
hash[score].sort_by { |i, _| i }.each do |_, route|
+ if name && !warned
+ ActiveSupport::Deprecation.warn <<-MSG.squish
+ You are trying to generate the URL for a named route called
+ #{name.inspect} but no such route was found. In the future,
+ this will result in an `ActionController::UrlGenerationError`
+ exception.
+ MSG
+
+ warned = true
+ end
+
yield route
end
end
diff --git a/actionpack/lib/action_dispatch/journey/nfa/transition_table.rb b/actionpack/lib/action_dispatch/journey/nfa/transition_table.rb
index 66e414213a..e65f7238ab 100644
--- a/actionpack/lib/action_dispatch/journey/nfa/transition_table.rb
+++ b/actionpack/lib/action_dispatch/journey/nfa/transition_table.rb
@@ -107,7 +107,7 @@ module ActionDispatch
end
def alphabet
- inverted.values.flat_map(&:keys).compact.uniq.sort_by { |x| x.to_s }
+ inverted.values.flat_map(&:keys).compact.uniq.sort_by(&:to_s)
end
# Returns a set of NFA states reachable from some NFA state +s+ in set
diff --git a/actionpack/lib/action_dispatch/journey/path/pattern.rb b/actionpack/lib/action_dispatch/journey/path/pattern.rb
index 3af940a02f..dca83e806c 100644
--- a/actionpack/lib/action_dispatch/journey/path/pattern.rb
+++ b/actionpack/lib/action_dispatch/journey/path/pattern.rb
@@ -42,7 +42,7 @@ module ActionDispatch
end
def names
- @names ||= spec.grep(Nodes::Symbol).map { |n| n.name }
+ @names ||= spec.grep(Nodes::Symbol).map(&:name)
end
def required_names
@@ -52,7 +52,7 @@ module ActionDispatch
def optional_names
@optional_names ||= spec.grep(Nodes::Group).flat_map { |group|
group.grep(Nodes::Symbol)
- }.map { |n| n.name }.uniq
+ }.map(&:name).uniq
end
class RegexpOffsets < Journey::Visitors::Visitor # :nodoc:
diff --git a/actionpack/lib/action_dispatch/journey/route.rb b/actionpack/lib/action_dispatch/journey/route.rb
index 9f0a3af902..3b609a184d 100644
--- a/actionpack/lib/action_dispatch/journey/route.rb
+++ b/actionpack/lib/action_dispatch/journey/route.rb
@@ -60,7 +60,7 @@ module ActionDispatch
end
def parts
- @parts ||= segments.map { |n| n.to_sym }
+ @parts ||= segments.map(&:to_sym)
end
alias :segment_keys :parts
@@ -69,11 +69,11 @@ module ActionDispatch
end
def optional_parts
- path.optional_names.map { |n| n.to_sym }
+ path.optional_names.map(&:to_sym)
end
def required_parts
- @required_parts ||= path.required_names.map { |n| n.to_sym }
+ @required_parts ||= path.required_names.map(&:to_sym)
end
def required_default?(key)
diff --git a/actionpack/lib/action_dispatch/journey/router.rb b/actionpack/lib/action_dispatch/journey/router.rb
index 9131b65380..2b036796ab 100644
--- a/actionpack/lib/action_dispatch/journey/router.rb
+++ b/actionpack/lib/action_dispatch/journey/router.rb
@@ -68,8 +68,8 @@ module ActionDispatch
def visualizer
tt = GTG::Builder.new(ast).transition_table
- groups = partitioned_routes.first.map(&:ast).group_by { |a| a.to_s }
- asts = groups.values.map { |v| v.first }
+ groups = partitioned_routes.first.map(&:ast).group_by(&:to_s)
+ asts = groups.values.map(&:first)
tt.visualizer(asts)
end
diff --git a/actionpack/lib/action_dispatch/journey/visualizer/fsm.css b/actionpack/lib/action_dispatch/journey/visualizer/fsm.css
index 50caebaa18..403e16a7bb 100644
--- a/actionpack/lib/action_dispatch/journey/visualizer/fsm.css
+++ b/actionpack/lib/action_dispatch/journey/visualizer/fsm.css
@@ -16,10 +16,6 @@ h2 {
font-size: 0.5em;
}
-div#chart-2 {
- height: 350px;
-}
-
.clearfix {display: inline-block; }
.input { overflow: show;}
.instruction { color: #666; padding: 0 30px 20px; font-size: 0.9em}
diff --git a/actionpack/lib/action_dispatch/middleware/callbacks.rb b/actionpack/lib/action_dispatch/middleware/callbacks.rb
index baf9d5779e..f80df78582 100644
--- a/actionpack/lib/action_dispatch/middleware/callbacks.rb
+++ b/actionpack/lib/action_dispatch/middleware/callbacks.rb
@@ -1,6 +1,6 @@
module ActionDispatch
- # Provide callbacks to be executed before and after the request dispatch.
+ # Provides callbacks to be executed before and after dispatching the request.
class Callbacks
include ActiveSupport::Callbacks
diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb
index 83ac62a83d..c9fff081d6 100644
--- a/actionpack/lib/action_dispatch/middleware/cookies.rb
+++ b/actionpack/lib/action_dispatch/middleware/cookies.rb
@@ -71,11 +71,13 @@ module ActionDispatch
# restrict to the domain level. If you use a schema like www.example.com
# and want to share session with user.example.com set <tt>:domain</tt>
# to <tt>:all</tt>. Make sure to specify the <tt>:domain</tt> option with
- # <tt>:all</tt> again when deleting cookies.
+ # <tt>:all</tt> or <tt>Array</tt> again when deleting cookies.
#
# domain: nil # Does not sets cookie domain. (default)
# domain: :all # Allow the cookie for the top most level
# # domain and subdomains.
+ # domain: %w(.example.com .example.org) # Allow the cookie
+ # # for concrete domain names.
#
# * <tt>:expires</tt> - The time at which this cookie expires, as a \Time object.
# * <tt>:secure</tt> - Whether this cookie is only transmitted to HTTPS servers.
@@ -120,7 +122,7 @@ module ActionDispatch
# the cookie again. This is useful for creating cookies with values that the user is not supposed to change. If a signed
# cookie was tampered with by the user (or a 3rd party), nil will be returned.
#
- # If +secrets.secret_key_base+ and +config.secret_token+ (deprecated) are both set,
+ # If +secrets.secret_key_base+ and +secrets.secret_token+ (deprecated) are both set,
# legacy cookies signed with the old key generator will be transparently upgraded.
#
# This jar requires that you set a suitable secret for the verification on your app's +secrets.secret_key_base+.
@@ -143,7 +145,7 @@ module ActionDispatch
# Returns a jar that'll automatically encrypt cookie values before sending them to the client and will decrypt them for read.
# If the cookie was tampered with by the user (or a 3rd party), nil will be returned.
#
- # If +secrets.secret_key_base+ and +config.secret_token+ (deprecated) are both set,
+ # If +secrets.secret_key_base+ and +secrets.secret_token+ (deprecated) are both set,
# legacy cookies signed with the old key generator will be transparently upgraded.
#
# This jar requires that you set a suitable secret for the verification on your app's +secrets.secret_key_base+.
@@ -479,7 +481,7 @@ module ActionDispatch
end
# UpgradeLegacySignedCookieJar is used instead of SignedCookieJar if
- # config.secret_token and secrets.secret_key_base are both set. It reads
+ # secrets.secret_token and secrets.secret_key_base are both set. It reads
# legacy cookies signed with the old dummy key generator and re-saves
# them using the new key generator to provide a smooth upgrade path.
class UpgradeLegacySignedCookieJar < SignedCookieJar #:nodoc:
@@ -537,7 +539,7 @@ module ActionDispatch
end
# UpgradeLegacyEncryptedCookieJar is used by ActionDispatch::Session::CookieStore
- # instead of EncryptedCookieJar if config.secret_token and secrets.secret_key_base
+ # instead of EncryptedCookieJar if secrets.secret_token and secrets.secret_key_base
# are both set. It reads legacy cookies signed with the old dummy key generator and
# encrypts and re-saves them using the new key generator to provide a smooth upgrade path.
class UpgradeLegacyEncryptedCookieJar < EncryptedCookieJar #:nodoc:
diff --git a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
index ff72592b94..c1562fcc0d 100644
--- a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
+++ b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
@@ -35,10 +35,10 @@ module ActionDispatch
if env['action_dispatch.show_detailed_exceptions']
request = Request.new(env)
- traces = traces_from_wrapper(wrapper)
+ traces = wrapper.traces
trace_to_show = 'Application Trace'
- if traces[trace_to_show].empty?
+ if traces[trace_to_show].empty? && wrapper.rescue_template != 'routing_error'
trace_to_show = 'Full Trace'
end
@@ -53,7 +53,7 @@ module ActionDispatch
show_source_idx: source_to_show_id,
trace_to_show: trace_to_show,
routes_inspector: routes_inspector(exception),
- source_extract: wrapper.source_extract,
+ source_extracts: wrapper.source_extracts,
line_number: wrapper.line_number,
file: wrapper.file
)
@@ -106,33 +106,5 @@ module ActionDispatch
ActionDispatch::Routing::RoutesInspector.new(@routes_app.routes.routes)
end
end
-
- # Augment the exception traces by providing ids for all unique stack frame
- def traces_from_wrapper(wrapper)
- application_trace = wrapper.application_trace
- framework_trace = wrapper.framework_trace
- full_trace = wrapper.full_trace
-
- appplication_trace_with_ids = []
- framework_trace_with_ids = []
- full_trace_with_ids = []
-
- if full_trace
- full_trace.each_with_index do |trace, idx|
- id_trace = {
- id: idx,
- trace: trace
- }
- appplication_trace_with_ids << id_trace if application_trace.include? trace
- framework_trace_with_ids << id_trace if framework_trace.include? trace
- full_trace_with_ids << id_trace
- end
- end
- {
- "Application Trace" => appplication_trace_with_ids,
- "Framework Trace" => framework_trace_with_ids,
- "Full Trace" => full_trace_with_ids
- }
- end
end
end
diff --git a/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb
index a6285848b5..a4862e33aa 100644
--- a/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb
+++ b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb
@@ -57,24 +57,52 @@ module ActionDispatch
clean_backtrace(:all)
end
+ def traces
+ appplication_trace_with_ids = []
+ framework_trace_with_ids = []
+ full_trace_with_ids = []
+
+ full_trace.each_with_index do |trace, idx|
+ trace_with_id = { id: idx, trace: trace }
+
+ if application_trace.include?(trace)
+ appplication_trace_with_ids << trace_with_id
+ else
+ framework_trace_with_ids << trace_with_id
+ end
+
+ full_trace_with_ids << trace_with_id
+ end
+
+ {
+ "Application Trace" => appplication_trace_with_ids,
+ "Framework Trace" => framework_trace_with_ids,
+ "Full Trace" => full_trace_with_ids
+ }
+ end
+
def self.status_code_for_exception(class_name)
Rack::Utils.status_code(@@rescue_responses[class_name])
end
- def source_extract
- exception.backtrace.map do |trace|
+ def source_extracts
+ backtrace.map do |trace|
file, line = trace.split(":")
line_number = line.to_i
+
{
code: source_fragment(file, line_number),
- file: file,
line_number: line_number
}
- end if exception.backtrace
+ end
end
private
+ def backtrace
+ Array(@exception.backtrace)
+ end
+
def original_exception(exception)
if registered_original_exception?(exception)
exception.original_exception
@@ -89,9 +117,9 @@ module ActionDispatch
def clean_backtrace(*args)
if backtrace_cleaner
- backtrace_cleaner.clean(@exception.backtrace, *args)
+ backtrace_cleaner.clean(backtrace, *args)
else
- @exception.backtrace
+ backtrace
end
end
diff --git a/actionpack/lib/action_dispatch/middleware/flash.rb b/actionpack/lib/action_dispatch/middleware/flash.rb
index e90f8b9ce6..a7f95150a4 100644
--- a/actionpack/lib/action_dispatch/middleware/flash.rb
+++ b/actionpack/lib/action_dispatch/middleware/flash.rb
@@ -79,7 +79,7 @@ module ActionDispatch
class FlashHash
include Enumerable
- def self.from_session_value(value)
+ def self.from_session_value(value) #:nodoc:
flash = case value
when FlashHash # Rails 3.1, 3.2
new(value.instance_variable_get(:@flashes), value.instance_variable_get(:@used))
@@ -91,8 +91,11 @@ module ActionDispatch
flash.tap(&:sweep)
end
-
- def to_session_value
+
+ # Builds a hash containing the discarded values and the hashes
+ # representing the flashes.
+ # If there are no values in @flashes, returns nil.
+ def to_session_value #:nodoc:
return nil if empty?
{'discard' => @discard.to_a, 'flashes' => @flashes}
end
@@ -132,7 +135,7 @@ module ActionDispatch
end
def key?(name)
- @flashes.key? name
+ @flashes.key? name.to_s
end
def delete(key)
diff --git a/actionpack/lib/action_dispatch/middleware/params_parser.rb b/actionpack/lib/action_dispatch/middleware/params_parser.rb
index b426183488..29d43faeed 100644
--- a/actionpack/lib/action_dispatch/middleware/params_parser.rb
+++ b/actionpack/lib/action_dispatch/middleware/params_parser.rb
@@ -47,7 +47,7 @@ module ActionDispatch
else
false
end
- rescue Exception => e # JSON or Ruby code block errors
+ rescue => e # JSON or Ruby code block errors
logger(env).debug "Error occurred while parsing request parameters.\nContents:\n\n#{request.raw_post}"
raise ParseError.new(e.message, e)
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.erb
index eabac3a9d2..e7b913bbe4 100644
--- a/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.erb
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.erb
@@ -1,29 +1,27 @@
-<% if @source_extract %>
- <% @source_extract.each_with_index do |extract_source, index| %>
- <% if extract_source[:code] %>
- <div class="source <%="hidden" if @show_source_idx != index%>" id="frame-source-<%=index%>">
- <div class="info">
- Extracted source (around line <strong>#<%= extract_source[:line_number] %></strong>):
- </div>
- <div class="data">
- <table cellpadding="0" cellspacing="0" class="lines">
- <tr>
- <td>
- <pre class="line_numbers">
- <% extract_source[:code].each_key do |line_number| %>
+<% @source_extracts.each_with_index do |source_extract, index| %>
+ <% if source_extract[:code] %>
+ <div class="source <%="hidden" if @show_source_idx != index%>" id="frame-source-<%=index%>">
+ <div class="info">
+ Extracted source (around line <strong>#<%= source_extract[:line_number] %></strong>):
+ </div>
+ <div class="data">
+ <table cellpadding="0" cellspacing="0" class="lines">
+ <tr>
+ <td>
+ <pre class="line_numbers">
+ <% source_extract[:code].each_key do |line_number| %>
<span><%= line_number -%></span>
- <% end %>
- </pre>
- </td>
+ <% end %>
+ </pre>
+ </td>
<td width="100%">
<pre>
-<% extract_source[:code].each do |line, source| -%><div class="line<%= " active" if line == extract_source[:line_number] -%>"><%= source -%></div><% end -%>
+<% source_extract[:code].each do |line, source| -%><div class="line<%= " active" if line == source_extract[:line_number] -%>"><%= source -%></div><% end -%>
</pre>
</td>
- </tr>
- </table>
- </div>
+ </tr>
+ </table>
</div>
- <% end %>
+ </div>
<% end %>
<% end %>
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/missing_template.html.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/missing_template.html.erb
index 5c016e544e..2a65fd06ad 100644
--- a/actionpack/lib/action_dispatch/middleware/templates/rescues/missing_template.html.erb
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/missing_template.html.erb
@@ -4,4 +4,8 @@
<div id="container">
<h2><%= h @exception.message %></h2>
+
+ <%= render template: "rescues/_source" %>
+ <%= render template: "rescues/_trace" %>
+ <%= render template: "rescues/_request_and_response" %>
</div>
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb
index 7e9cedb95e..55dd5ddc7b 100644
--- a/actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb
@@ -27,4 +27,6 @@
<%= @routes_inspector.format(ActionDispatch::Routing::HtmlTableFormatter.new(self)) %>
<% end %>
+
+ <%= render template: "rescues/_request_and_response" %>
</div>
diff --git a/actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb b/actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb
index 6ffa242da4..5cee0b5932 100644
--- a/actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb
+++ b/actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb
@@ -1,6 +1,6 @@
<% content_for :style do %>
#route_table {
- margin: 0 auto 0;
+ margin: 0;
border-collapse: collapse;
}
diff --git a/actionpack/lib/action_dispatch/routing/inspector.rb b/actionpack/lib/action_dispatch/routing/inspector.rb
index cfe2237512..df5ebb6751 100644
--- a/actionpack/lib/action_dispatch/routing/inspector.rb
+++ b/actionpack/lib/action_dispatch/routing/inspector.rb
@@ -114,9 +114,7 @@ module ActionDispatch
def collect_routes(routes)
routes.collect do |route|
RouteWrapper.new(route)
- end.reject do |route|
- route.internal?
- end.collect do |route|
+ end.reject(&:internal?).collect do |route|
collect_engine_routes(route)
{ name: route.name,
diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb
index ac03ecb2c8..5040aa82b2 100644
--- a/actionpack/lib/action_dispatch/routing/mapper.rb
+++ b/actionpack/lib/action_dispatch/routing/mapper.rb
@@ -244,12 +244,10 @@ module ActionDispatch
def app(blocks)
if to.respond_to?(:call)
Constraints.new(to, blocks, false)
+ elsif blocks.any?
+ Constraints.new(dispatcher(defaults), blocks, true)
else
- if blocks.any?
- Constraints.new(dispatcher(defaults), blocks, true)
- else
- dispatcher(defaults)
- end
+ dispatcher(defaults)
end
end
@@ -391,7 +389,7 @@ module ActionDispatch
# Matches a url pattern to one or more routes.
#
- # You should not use the `match` method in your router
+ # You should not use the +match+ method in your router
# without specifying an HTTP method.
#
# If you want to expose your action to both GET and POST, use:
@@ -402,7 +400,7 @@ module ActionDispatch
# Note that +:controller+, +:action+ and +:id+ are interpreted as url
# query parameters and thus available through +params+ in an action.
#
- # If you want to expose your action to GET, use `get` in the router:
+ # If you want to expose your action to GET, use +get+ in the router:
#
# Instead of:
#
@@ -457,7 +455,7 @@ module ActionDispatch
# The route's action.
#
# [:param]
- # Overrides the default resource identifier `:id` (name of the
+ # Overrides the default resource identifier +:id+ (name of the
# dynamic segment used to generate the routes).
# You can access that segment from your controller using
# <tt>params[<:param>]</tt>.
@@ -582,13 +580,7 @@ module ActionDispatch
raise "A rack application must be specified" unless path
rails_app = rails_app? app
-
- if rails_app
- options[:as] ||= app.railtie_name
- else
- # non rails apps can't have an :as
- options[:as] = nil
- end
+ options[:as] ||= app.railtie_name if rails_app
target_as = name_for_action(options[:as], path)
options[:via] ||= :all
diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb
index a641ea3ea9..c2cacbd288 100644
--- a/actionpack/lib/action_dispatch/routing/route_set.rb
+++ b/actionpack/lib/action_dispatch/routing/route_set.rb
@@ -271,7 +271,7 @@ module ActionDispatch
controller_options = t.url_options
options = controller_options.merge @options
hash = handle_positional_args(controller_options,
- inner_options || {},
+ deprecate_string_options(inner_options) || {},
args,
options,
@segment_keys)
@@ -293,6 +293,22 @@ module ActionDispatch
result.merge!(inner_options)
end
+
+ DEPRECATED_STRING_OPTIONS = %w[controller action]
+
+ def deprecate_string_options(options)
+ options ||= {}
+ deprecated_string_options = options.keys & DEPRECATED_STRING_OPTIONS
+ if deprecated_string_options.any?
+ msg = "Calling URL helpers with string keys #{deprecated_string_options.join(", ")} is deprecated. Use symbols instead."
+ ActiveSupport::Deprecation.warn(msg)
+ deprecated_string_options.each do |option|
+ value = options.delete(option)
+ options[option.to_sym] = value
+ end
+ end
+ options
+ end
end
private
@@ -457,7 +473,7 @@ module ActionDispatch
RUBY
end
- def url_helpers(include_path_helpers = true)
+ def url_helpers(supports_path = true)
routes = self
Module.new do
@@ -484,7 +500,7 @@ module ActionDispatch
# named routes...
include url_helpers
- if include_path_helpers
+ if supports_path
path_helpers = routes.named_routes.path_helpers_module
else
path_helpers = routes.named_routes.path_helpers_module(true)
@@ -502,6 +518,10 @@ module ActionDispatch
# UrlFor (included in this module) add extra
# conveniences for working with @_routes.
define_method(:_routes) { @_routes || routes }
+
+ define_method(:_generate_paths_by_default) do
+ supports_path
+ end
end
end
@@ -523,7 +543,7 @@ module ActionDispatch
path = conditions.delete :path_info
ast = conditions.delete :parsed_path_info
path = build_path(path, ast, requirements, anchor)
- conditions = build_conditions(conditions, path.names.map { |x| x.to_sym })
+ conditions = build_conditions(conditions, path.names.map(&:to_sym))
route = @set.add_route(app, path, conditions, defaults, name)
named_routes[name] = route if name
@@ -585,7 +605,7 @@ module ActionDispatch
if name == :controller
value
elsif value.is_a?(Array)
- value.map { |v| v.to_param }.join('/')
+ value.map(&:to_param).join('/')
elsif param = value.to_param
param
end
@@ -729,7 +749,7 @@ module ActionDispatch
end
def find_script_name(options)
- options.delete(:script_name) { '' }
+ options.delete(:script_name) || ''
end
def path_for(options, route_name = nil) # :nodoc:
diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb
index eb554ec383..dca86858cc 100644
--- a/actionpack/lib/action_dispatch/routing/url_for.rb
+++ b/actionpack/lib/action_dispatch/routing/url_for.rb
@@ -184,6 +184,12 @@ module ActionDispatch
def _routes_context
self
end
+
+ private
+
+ def _generate_paths_by_default
+ true
+ end
end
end
end
diff --git a/actionpack/lib/action_dispatch/testing/assertions.rb b/actionpack/lib/action_dispatch/testing/assertions.rb
index 41d00b5e2b..f325c35b57 100644
--- a/actionpack/lib/action_dispatch/testing/assertions.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions.rb
@@ -15,7 +15,7 @@ module ActionDispatch
@html_document ||= if @response.content_type =~ /xml$/
Nokogiri::XML::Document.parse(@response.body)
else
- Nokogiri::HTML::DocumentFragment.parse(@response.body)
+ Nokogiri::HTML::Document.parse(@response.body)
end
end
end
diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb
index e06f7037c6..28dc88d317 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb
@@ -144,12 +144,6 @@ module ActionDispatch
old_controller, @controller = @controller, @controller.clone
_routes = @routes
- # Unfortunately, there is currently an abstraction leak between AC::Base
- # and AV::Base which requires having the URL helpers in both AC and AV.
- # To do this safely at runtime for tests, we need to bump up the helper serial
- # to that the old AV subclass isn't cached.
- #
- # TODO: Make this unnecessary
@controller.singleton_class.send(:include, _routes.url_helpers)
@controller.view_context_class = Class.new(@controller.view_context_class) do
include _routes.url_helpers
diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb
index c300a4ea0d..a9a1576fed 100644
--- a/actionpack/lib/action_dispatch/testing/integration.rb
+++ b/actionpack/lib/action_dispatch/testing/integration.rb
@@ -326,13 +326,21 @@ module ActionDispatch
@integration_session = Integration::Session.new(app)
end
+ def remove! # :nodoc:
+ @integration_session = nil
+ end
+
%w(get post patch put head delete cookies assigns
xml_http_request xhr get_via_redirect post_via_redirect).each do |method|
define_method(method) do |*args|
reset! unless integration_session
- reset_template_assertion
- # reset the html_document variable, but only for new get/post calls
- @html_document = nil unless method == 'cookies' || method == 'assigns'
+
+ # reset the html_document variable, except for cookies/assigns calls
+ unless method == 'cookies' || method == 'assigns'
+ @html_document = nil
+ reset_template_assertion
+ end
+
integration_session.__send__(method, *args).tap do
copy_session_variables!
end
@@ -497,7 +505,7 @@ module ActionDispatch
end
def document_root_element
- html_document
+ html_document.root
end
end
end
diff --git a/actionpack/lib/action_dispatch/testing/test_request.rb b/actionpack/lib/action_dispatch/testing/test_request.rb
index de3dc5f924..4b9a088265 100644
--- a/actionpack/lib/action_dispatch/testing/test_request.rb
+++ b/actionpack/lib/action_dispatch/testing/test_request.rb
@@ -60,7 +60,7 @@ module ActionDispatch
def accept=(mime_types)
@env.delete('action_dispatch.request.accepts')
- @env['HTTP_ACCEPT'] = Array(mime_types).collect { |mime_type| mime_type.to_s }.join(",")
+ @env['HTTP_ACCEPT'] = Array(mime_types).collect(&:to_s).join(",")
end
alias :rack_cookies :cookies
diff --git a/actionpack/lib/action_pack/gem_version.rb b/actionpack/lib/action_pack/gem_version.rb
index 9b3ea30f69..255ac9f4ed 100644
--- a/actionpack/lib/action_pack/gem_version.rb
+++ b/actionpack/lib/action_pack/gem_version.rb
@@ -5,10 +5,10 @@ module ActionPack
end
module VERSION
- MAJOR = 4
- MINOR = 2
+ MAJOR = 5
+ MINOR = 0
TINY = 0
- PRE = "beta4"
+ PRE = "alpha"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb
index 69312e4c22..57c076eac6 100644
--- a/actionpack/test/abstract_unit.rb
+++ b/actionpack/test/abstract_unit.rb
@@ -53,7 +53,7 @@ I18n.enforce_available_locales = false
# Register danish language for testing
I18n.backend.store_translations 'da', {}
I18n.backend.store_translations 'pt-BR', {}
-ORIGINAL_LOCALES = I18n.available_locales.map {|locale| locale.to_s }.sort
+ORIGINAL_LOCALES = I18n.available_locales.map(&:to_s).sort
FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), 'fixtures')
FIXTURES = Pathname.new(FIXTURE_LOAD_PATH)
@@ -194,6 +194,7 @@ class ActionDispatch::IntegrationTest < ActiveSupport::TestCase
yield temporary_routes
ensure
self.class.app = old_app
+ self.remove!
silence_warnings { Object.const_set(:SharedTestRoutes, old_routes) }
end
diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb
index b2b01b3fa9..38533dbf23 100644
--- a/actionpack/test/controller/filters_test.rb
+++ b/actionpack/test/controller/filters_test.rb
@@ -10,7 +10,7 @@ class ActionController::Base
def before_actions
filters = _process_action_callbacks.select { |c| c.kind == :before }
- filters.map! { |c| c.raw_filter }
+ filters.map!(&:raw_filter)
end
end
diff --git a/actionpack/test/controller/flash_hash_test.rb b/actionpack/test/controller/flash_hash_test.rb
index 50b36a0567..d979b561f2 100644
--- a/actionpack/test/controller/flash_hash_test.rb
+++ b/actionpack/test/controller/flash_hash_test.rb
@@ -29,6 +29,15 @@ module ActionDispatch
assert_equal 'world', @hash['hello']
end
+ def test_key
+ @hash['foo'] = 'bar'
+
+ assert @hash.key?('foo')
+ assert @hash.key?(:foo)
+ assert_not @hash.key?('bar')
+ assert_not @hash.key?(:bar)
+ end
+
def test_delete
@hash['foo'] = 'bar'
@hash.delete 'foo'
diff --git a/actionpack/test/controller/http_token_authentication_test.rb b/actionpack/test/controller/http_token_authentication_test.rb
index 8c6c8a0aa7..a758df2ec6 100644
--- a/actionpack/test/controller/http_token_authentication_test.rb
+++ b/actionpack/test/controller/http_token_authentication_test.rb
@@ -162,17 +162,36 @@ class HttpTokenAuthenticationTest < ActionController::TestCase
assert_equal(expected, actual)
end
+ test "token_and_options returns right token when token key is not specified in header" do
+ token = "rcHu+HzSFw89Ypyhn/896A="
+
+ actual = ActionController::HttpAuthentication::Token.token_and_options(
+ sample_request_without_token_key(token)
+ ).first
+
+ expected = token
+ assert_equal(expected, actual)
+ end
+
private
def sample_request(token, options = {nonce: "def"})
authorization = options.inject([%{Token token="#{token}"}]) do |arr, (k, v)|
arr << "#{k}=\"#{v}\""
end.join(", ")
- @sample_request ||= OpenStruct.new authorization: authorization
+ mock_authorization_request(authorization)
end
def malformed_request
- @malformed_request ||= OpenStruct.new authorization: %{Token token=}
+ mock_authorization_request(%{Token token=})
+ end
+
+ def sample_request_without_token_key(token)
+ mock_authorization_request(%{Token #{token}})
+ end
+
+ def mock_authorization_request(authorization)
+ OpenStruct.new(authorization: authorization)
end
def encode_credentials(token, options = {})
diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb
index d91a1657b3..d6219b7626 100644
--- a/actionpack/test/controller/integration_test.rb
+++ b/actionpack/test/controller/integration_test.rb
@@ -292,7 +292,7 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
assert_equal({}, cookies.to_hash)
assert_equal "OK", body
assert_equal "OK", response.body
- assert_kind_of Nokogiri::HTML::DocumentFragment, html_document
+ assert_kind_of Nokogiri::HTML::Document, html_document
assert_equal 1, request_count
end
end
@@ -308,7 +308,7 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
assert_equal({}, cookies.to_hash)
assert_equal "Created", body
assert_equal "Created", response.body
- assert_kind_of Nokogiri::HTML::DocumentFragment, html_document
+ assert_kind_of Nokogiri::HTML::Document, html_document
assert_equal 1, request_count
end
end
@@ -368,7 +368,7 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
assert_response :redirect
assert_response :found
assert_equal "<html><body>You are being <a href=\"http://www.example.com/get\">redirected</a>.</body></html>", response.body
- assert_kind_of Nokogiri::HTML::DocumentFragment, html_document
+ assert_kind_of Nokogiri::HTML::Document, html_document
assert_equal 1, request_count
follow_redirect!
@@ -814,3 +814,39 @@ class HeadWithStatusActionIntegrationTest < ActionDispatch::IntegrationTest
assert_response :ok
end
end
+
+class IntegrationWithRoutingTest < ActionDispatch::IntegrationTest
+ class FooController < ActionController::Base
+ def index
+ render plain: 'ok'
+ end
+ end
+
+ def test_with_routing_resets_session
+ klass_namespace = self.class.name.underscore
+
+ with_routing do |routes|
+ routes.draw do
+ namespace klass_namespace do
+ resources :foo, path: '/with'
+ end
+ end
+
+ get '/integration_with_routing_test/with'
+ assert_response 200
+ assert_equal 'ok', response.body
+ end
+
+ with_routing do |routes|
+ routes.draw do
+ namespace klass_namespace do
+ resources :foo, path: '/routing'
+ end
+ end
+
+ get '/integration_with_routing_test/routing'
+ assert_response 200
+ assert_equal 'ok', response.body
+ end
+ end
+end
diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb
index c18914cc8e..9caa5cbe57 100644
--- a/actionpack/test/controller/routing_test.rb
+++ b/actionpack/test/controller/routing_test.rb
@@ -884,13 +884,13 @@ class RouteSetTest < ActiveSupport::TestCase
set.draw { get ':controller/(:action(/:id))' }
path, extras = set.generate_extras(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
assert_equal "/foo/bar/15", path
- assert_equal %w(that this), extras.map { |e| e.to_s }.sort
+ assert_equal %w(that this), extras.map(&:to_s).sort
end
def test_extra_keys
set.draw { get ':controller/:action/:id' }
extras = set.extra_keys(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
- assert_equal %w(that this), extras.map { |e| e.to_s }.sort
+ assert_equal %w(that this), extras.map(&:to_s).sort
end
def test_generate_extras_not_first
@@ -900,7 +900,7 @@ class RouteSetTest < ActiveSupport::TestCase
end
path, extras = set.generate_extras(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
assert_equal "/foo/bar/15", path
- assert_equal %w(that this), extras.map { |e| e.to_s }.sort
+ assert_equal %w(that this), extras.map(&:to_s).sort
end
def test_generate_not_first
@@ -918,7 +918,7 @@ class RouteSetTest < ActiveSupport::TestCase
get ':controller/:action/:id'
end
extras = set.extra_keys(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world")
- assert_equal %w(that this), extras.map { |e| e.to_s }.sort
+ assert_equal %w(that this), extras.map(&:to_s).sort
end
def test_draw
@@ -1001,6 +1001,9 @@ class RouteSetTest < ActiveSupport::TestCase
assert_equal "http://test.host/people?baz=bar#location",
controller.send(:index_url, :baz => "bar", :anchor => 'location')
+
+ assert_equal "http://test.host/people", controller.send(:index_url, anchor: nil)
+ assert_equal "http://test.host/people", controller.send(:index_url, anchor: false)
end
def test_named_route_url_method_with_port
@@ -1383,7 +1386,7 @@ class RouteSetTest < ActiveSupport::TestCase
url = controller.url_for({ :controller => "connection", :only_path => true })
assert_equal "/connection/connection", url
- url = controller.url_for({ :use_route => :family_connection,
+ url = controller.url_for({ :use_route => "family_connection",
:controller => "connection", :only_path => true })
assert_equal "/connection", url
end
diff --git a/actionpack/test/controller/test_case_test.rb b/actionpack/test/controller/test_case_test.rb
index 9d7abd5e94..ba2ff7d12c 100644
--- a/actionpack/test/controller/test_case_test.rb
+++ b/actionpack/test/controller/test_case_test.rb
@@ -1,6 +1,7 @@
require 'abstract_unit'
require 'controller/fake_controllers'
require 'active_support/json/decoding'
+require 'rails/engine'
class TestCaseTest < ActionController::TestCase
class TestController < ActionController::Base
@@ -132,6 +133,14 @@ XML
render :nothing => true
end
+ def test_without_body
+ render html: '<div class="foo"></div>'.html_safe
+ end
+
+ def test_with_body
+ render html: '<body class="foo"></body>'.html_safe
+ end
+
private
def generate_url(opts)
@@ -179,6 +188,19 @@ XML
end
end
+ def test_assert_select_without_body
+ get :test_without_body
+
+ assert_select 'body', 0
+ assert_select 'div.foo'
+ end
+
+ def test_assert_select_with_body
+ get :test_with_body
+
+ assert_select 'body.foo'
+ end
+
def test_url_options_reset
@controller = DefaultUrlOptionsCachingController.new
get :test_url_options_reset
@@ -499,6 +521,18 @@ XML
end
end
+ def test_use_route
+ with_routing do |set|
+ set.draw do
+ get 'via_unnamed_route', to: 'test_case_test/test#test_uri'
+ get 'via_named_route', as: :a_named_route, to: 'test_case_test/test#test_uri'
+ end
+
+ assert_deprecated { get :test_uri, use_route: :a_named_route }
+ assert_equal '/via_named_route', @response.body
+ end
+ end
+
def test_assert_realistic_path_parameters
get :test_params, :id => 20, :foo => Object.new
@@ -720,6 +754,57 @@ XML
end
end
+module EngineControllerTests
+ class Engine < ::Rails::Engine
+ isolate_namespace EngineControllerTests
+
+ routes.draw do
+ get '/' => 'bar#index'
+ end
+ end
+
+ class BarController < ActionController::Base
+ def index
+ render :text => 'bar'
+ end
+ end
+
+ class BarControllerTest < ActionController::TestCase
+ tests BarController
+
+ def test_engine_controller_route
+ get :index
+ assert_equal @response.body, 'bar'
+ end
+ end
+
+ class BarControllerTestWithExplicitRouteSet < ActionController::TestCase
+ tests BarController
+
+ def setup
+ @routes = Engine.routes
+ end
+
+ def test_engine_controller_route
+ get :index
+ assert_equal @response.body, 'bar'
+ end
+ end
+
+ class BarControllerTestWithHostApplicationRouteSet < ActionController::TestCase
+ tests BarController
+
+ def test_use_route
+ with_routing do |set|
+ set.draw { mount Engine => '/foo' }
+
+ assert_deprecated { get :index, use_route: :foo }
+ assert_equal @response.body, 'bar'
+ end
+ end
+ end
+end
+
class InferringClassNameTest < ActionController::TestCase
def test_determine_controller_class
assert_equal ContentController, determine_class("ContentControllerTest")
diff --git a/actionpack/test/controller/url_for_test.rb b/actionpack/test/controller/url_for_test.rb
index 969129d9ba..0ffa2d2a03 100644
--- a/actionpack/test/controller/url_for_test.rb
+++ b/actionpack/test/controller/url_for_test.rb
@@ -25,8 +25,7 @@ module AbstractController
path = klass.new.fun_path({:controller => :articles,
:baz => "baz",
- :zot => "zot",
- :only_path => true })
+ :zot => "zot"})
# :bar key isn't provided
assert_equal '/foo/zot', path
end
@@ -55,6 +54,20 @@ module AbstractController
)
end
+ def test_nil_anchor
+ assert_equal(
+ '/c/a',
+ W.new.url_for(only_path: true, controller: 'c', action: 'a', anchor: nil)
+ )
+ end
+
+ def test_false_anchor
+ assert_equal(
+ '/c/a',
+ W.new.url_for(only_path: true, controller: 'c', action: 'a', anchor: false)
+ )
+ end
+
def test_anchor_should_call_to_param
assert_equal('/c/a#anchor',
W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :anchor => Struct.new(:to_param).new('anchor'))
@@ -277,6 +290,13 @@ module AbstractController
end
end
+ def test_using_nil_script_name_properly_concats_with_original_script_name
+ add_host!
+ assert_equal('https://www.basecamphq.com/subdir/c/a/i',
+ W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https', :script_name => nil, :original_script_name => '/subdir')
+ )
+ end
+
def test_only_path
with_routing do |set|
set.draw do
@@ -291,7 +311,7 @@ module AbstractController
assert_equal '/brave/new/world',
controller.url_for(:controller => 'brave', :action => 'new', :id => 'world', :only_path => true)
- assert_equal("/home/sweet/home/alabama", controller.home_path(:user => 'alabama', :host => 'unused', :only_path => true))
+ assert_equal("/home/sweet/home/alabama", controller.home_path(:user => 'alabama', :host => 'unused'))
assert_equal("/home/sweet/home/alabama", controller.home_path('alabama'))
end
end
diff --git a/actionpack/test/controller/webservice_test.rb b/actionpack/test/controller/webservice_test.rb
index d80b0e2da0..2b109ff19e 100644
--- a/actionpack/test/controller/webservice_test.rb
+++ b/actionpack/test/controller/webservice_test.rb
@@ -83,6 +83,16 @@ class WebServiceTest < ActionDispatch::IntegrationTest
end
end
+ def test_parsing_json_doesnot_rescue_exception
+ with_test_route_set do
+ with_params_parsers Mime::JSON => Proc.new { |data| raise Interrupt } do
+ assert_raises(Interrupt) do
+ post "/", '{"title":"JSON"}}', 'CONTENT_TYPE' => 'application/json'
+ end
+ end
+ end
+ end
+
private
def with_params_parsers(parsers = {})
old_session = @integration_session
diff --git a/actionpack/test/dispatch/debug_exceptions_test.rb b/actionpack/test/dispatch/debug_exceptions_test.rb
index f8851f0152..5e87744f6b 100644
--- a/actionpack/test/dispatch/debug_exceptions_test.rb
+++ b/actionpack/test/dispatch/debug_exceptions_test.rb
@@ -43,6 +43,8 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
raise ActionController::InvalidAuthenticityToken
when "/not_found_original_exception"
raise ActionView::Template::Error.new('template', AbstractController::ActionNotFound.new)
+ when "/missing_template"
+ raise ActionView::MissingTemplate.new(%w(foo), 'foo/index', %w(foo), false, 'mailer')
when "/bad_request"
raise ActionController::BadRequest
when "/missing_keys"
@@ -120,6 +122,15 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
assert_no_match '&lt;|&gt;', routing_table, "there should not be escaped html in the output"
end
+ test 'displays request and response info when a RoutingError occurs' do
+ @app = DevelopmentApp
+
+ get "/pass", {}, {'action_dispatch.show_exceptions' => true}
+
+ assert_select 'h2', /Request/
+ assert_select 'h2', /Response/
+ end
+
test "rescue with diagnostics message" do
@app = DevelopmentApp
@@ -275,6 +286,22 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
end
end
+ test 'display backtrace on template missing errors' do
+ @app = DevelopmentApp
+
+ get "/missing_template", nil, {}
+
+ assert_select "header h1", /Template is missing/
+
+ assert_select "#container h2", /^Missing template/
+
+ assert_select '#Application-Trace'
+ assert_select '#Framework-Trace'
+ assert_select '#Full-Trace'
+
+ assert_select 'h2', /Request/
+ end
+
test 'display backtrace when error type is SyntaxError wrapped by ActionView::Template::Error' do
@app = DevelopmentApp
diff --git a/actionpack/test/dispatch/exception_wrapper_test.rb b/actionpack/test/dispatch/exception_wrapper_test.rb
new file mode 100644
index 0000000000..d7408164ba
--- /dev/null
+++ b/actionpack/test/dispatch/exception_wrapper_test.rb
@@ -0,0 +1,97 @@
+require 'abstract_unit'
+
+module ActionDispatch
+ class ExceptionWrapperTest < ActionDispatch::IntegrationTest
+ class TestError < StandardError
+ attr_reader :backtrace
+
+ def initialize(*backtrace)
+ @backtrace = backtrace.flatten
+ end
+ end
+
+ class BadlyDefinedError < StandardError
+ def backtrace
+ nil
+ end
+ end
+
+ setup do
+ Rails.stubs(:root).returns(Pathname.new('.'))
+
+ cleaner = ActiveSupport::BacktraceCleaner.new
+ cleaner.add_silencer { |line| line !~ /^lib/ }
+
+ @environment = { 'action_dispatch.backtrace_cleaner' => cleaner }
+ end
+
+ test '#source_extracts fetches source fragments for every backtrace entry' do
+ exception = TestError.new("lib/file.rb:42:in `index'")
+ wrapper = ExceptionWrapper.new({}, exception)
+
+ wrapper.expects(:source_fragment).with('lib/file.rb', 42).returns('foo')
+
+ assert_equal [ code: 'foo', line_number: 42 ], wrapper.source_extracts
+ end
+
+
+ test '#application_trace returns traces only from the application' do
+ exception = TestError.new(caller.prepend("lib/file.rb:42:in `index'"))
+ wrapper = ExceptionWrapper.new(@environment, exception)
+
+ assert_equal [ "lib/file.rb:42:in `index'" ], wrapper.application_trace
+ end
+
+ test '#application_trace cannot be nil' do
+ nil_backtrace_wrapper = ExceptionWrapper.new(@environment, BadlyDefinedError.new)
+ nil_cleaner_wrapper = ExceptionWrapper.new({}, BadlyDefinedError.new)
+
+ assert_equal [], nil_backtrace_wrapper.application_trace
+ assert_equal [], nil_cleaner_wrapper.application_trace
+ end
+
+ test '#framework_trace returns traces outside the application' do
+ exception = TestError.new(caller.prepend("lib/file.rb:42:in `index'"))
+ wrapper = ExceptionWrapper.new(@environment, exception)
+
+ assert_equal caller, wrapper.framework_trace
+ end
+
+ test '#framework_trace cannot be nil' do
+ nil_backtrace_wrapper = ExceptionWrapper.new(@environment, BadlyDefinedError.new)
+ nil_cleaner_wrapper = ExceptionWrapper.new({}, BadlyDefinedError.new)
+
+ assert_equal [], nil_backtrace_wrapper.framework_trace
+ assert_equal [], nil_cleaner_wrapper.framework_trace
+ end
+
+ test '#full_trace returns application and framework traces' do
+ exception = TestError.new(caller.prepend("lib/file.rb:42:in `index'"))
+ wrapper = ExceptionWrapper.new(@environment, exception)
+
+ assert_equal exception.backtrace, wrapper.full_trace
+ end
+
+ test '#full_trace cannot be nil' do
+ nil_backtrace_wrapper = ExceptionWrapper.new(@environment, BadlyDefinedError.new)
+ nil_cleaner_wrapper = ExceptionWrapper.new({}, BadlyDefinedError.new)
+
+ assert_equal [], nil_backtrace_wrapper.full_trace
+ assert_equal [], nil_cleaner_wrapper.full_trace
+ end
+
+ test '#traces returns every trace by category enumerated with an index' do
+ exception = TestError.new("lib/file.rb:42:in `index'", "/gems/rack.rb:43:in `index'")
+ wrapper = ExceptionWrapper.new(@environment, exception)
+
+ assert_equal({
+ 'Application Trace' => [ id: 0, trace: "lib/file.rb:42:in `index'" ],
+ 'Framework Trace' => [ id: 1, trace: "/gems/rack.rb:43:in `index'" ],
+ 'Full Trace' => [
+ { id: 0, trace: "lib/file.rb:42:in `index'" },
+ { id: 1, trace: "/gems/rack.rb:43:in `index'" }
+ ]
+ }, wrapper.traces)
+ end
+ end
+end
diff --git a/actionpack/test/dispatch/mime_type_test.rb b/actionpack/test/dispatch/mime_type_test.rb
index ad6335f132..3017a9c2d6 100644
--- a/actionpack/test/dispatch/mime_type_test.rb
+++ b/actionpack/test/dispatch/mime_type_test.rb
@@ -83,7 +83,7 @@ class MimeTypeTest < ActiveSupport::TestCase
test "parse broken acceptlines" do
accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/*,,*/*;q=0.5"
expect = [Mime::HTML, Mime::XML, "image/*", Mime::TEXT, Mime::ALL]
- assert_equal expect, Mime::Type.parse(accept).collect { |c| c.to_s }
+ assert_equal expect, Mime::Type.parse(accept).collect(&:to_s)
end
# Accept header send with user HTTP_USER_AGENT: Mozilla/4.0
@@ -91,7 +91,7 @@ class MimeTypeTest < ActiveSupport::TestCase
test "parse other broken acceptlines" do
accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, , pronto/1.00.00, sslvpn/1.00.00.00, */*"
expect = ['image/gif', 'image/x-xbitmap', 'image/jpeg','image/pjpeg', 'application/x-shockwave-flash', 'application/vnd.ms-excel', 'application/vnd.ms-powerpoint', 'application/msword', 'pronto/1.00.00', 'sslvpn/1.00.00.00', Mime::ALL]
- assert_equal expect, Mime::Type.parse(accept).collect { |c| c.to_s }
+ assert_equal expect, Mime::Type.parse(accept).collect(&:to_s)
end
test "custom type" do
diff --git a/actionpack/test/dispatch/routing/inspector_test.rb b/actionpack/test/dispatch/routing/inspector_test.rb
index ff33dd5652..5910f364cc 100644
--- a/actionpack/test/dispatch/routing/inspector_test.rb
+++ b/actionpack/test/dispatch/routing/inspector_test.rb
@@ -235,7 +235,7 @@ module ActionDispatch
assert_equal [
"Prefix Verb URI Pattern Controller#Action",
- " /foo #{RackApp.name} {:constraint=>( my custom constraint )}"
+ " foo /foo #{RackApp.name} {:constraint=>( my custom constraint )}"
], output
end
diff --git a/actionpack/test/dispatch/routing/route_set_test.rb b/actionpack/test/dispatch/routing/route_set_test.rb
index a7acc0de41..5a39119446 100644
--- a/actionpack/test/dispatch/routing/route_set_test.rb
+++ b/actionpack/test/dispatch/routing/route_set_test.rb
@@ -160,6 +160,26 @@ module ActionDispatch
assert_equal '/foo/1/bar/2', url_helpers.foo_bar_path(2, foo_id: 1)
end
+ test "stringified controller and action keys are properly symbolized" do
+ draw do
+ root 'foo#bar'
+ end
+
+ assert_deprecated do
+ assert_equal '/', url_helpers.root_path('controller' => 'foo', 'action' => 'bar')
+ end
+ end
+
+ test "mix of string and symbol keys are properly symbolized" do
+ draw do
+ root 'foo#bar'
+ end
+
+ assert_deprecated do
+ assert_equal '/', url_helpers.root_path('controller' => 'foo', :action => 'bar')
+ end
+ end
+
private
def draw(&block)
@set.draw(&block)
diff --git a/actionpack/test/dispatch/template_assertions_test.rb b/actionpack/test/dispatch/template_assertions_test.rb
index 3c393f937b..7278754b49 100644
--- a/actionpack/test/dispatch/template_assertions_test.rb
+++ b/actionpack/test/dispatch/template_assertions_test.rb
@@ -10,7 +10,7 @@ class AssertTemplateController < ActionController::Base
end
def render_with_layout
- @variable_for_layout = nil
+ @variable_for_layout = 'hello'
render 'test/hello_world', layout: "layouts/standard"
end
@@ -95,4 +95,16 @@ class AssertTemplateControllerTest < ActionDispatch::IntegrationTest
session.assert_template file: nil
end
end
+
+ def test_assigns_do_not_reset_template_assertion
+ get '/assert_template/render_with_layout'
+ assert_equal 'hello', assigns(:variable_for_layout)
+ assert_template layout: 'layouts/standard'
+ end
+
+ def test_cookies_do_not_reset_template_assertion
+ get '/assert_template/render_with_layout'
+ cookies
+ assert_template layout: 'layouts/standard'
+ end
end
diff --git a/actionpack/test/journey/router_test.rb b/actionpack/test/journey/router_test.rb
index fbac86e8ca..19c61b5914 100644
--- a/actionpack/test/journey/router_test.rb
+++ b/actionpack/test/journey/router_test.rb
@@ -415,7 +415,7 @@ module ActionDispatch
def test_generate_with_name
path = Path::Pattern.from_string '/:controller(/:action)'
- @router.routes.add_route @app, path, {}, {}, {}
+ @router.routes.add_route @app, path, {}, {}, "tasks"
path, params = @formatter.generate(
"tasks",
diff --git a/actionview/CHANGELOG.md b/actionview/CHANGELOG.md
index e388e6ecd3..729717608f 100644
--- a/actionview/CHANGELOG.md
+++ b/actionview/CHANGELOG.md
@@ -1,199 +1 @@
-* Update `select_tag` to work correctly with `:include_blank` option passing a string.
-
- Fixes #16483.
-
- *Frank Groeneveld*
-
-* Changed the meaning of `render "foo/bar"`.
-
- Previously, calling `render "foo/bar"` in a controller action is equivalent
- to `render file: "foo/bar"`. In Rails 4.2, this has been changed to mean
- `render template: "foo/bar"` instead. If you need to render a file, please
- change your code to use the explicit form (`render file: "foo/bar"`) instead.
-
- *Jeremy Jackson*
-
-* Add support for ARIA attributes in tags.
-
- Example:
-
- <%= f.text_field :name, aria: { required: "true", hidden: "false" } %>
-
- now generates:
-
- <input aria-hidden="false" aria-required="true" id="user_name" name="user[name]" type="text">
-
- *Paola Garcia Casadiego*
-
-* Provide a `builder` object when using the `label` form helper in block form.
-
- The new `builder` object responds to `translation`, allowing I18n fallback support
- when you want to customize how a particular label is presented.
-
- *Alex Robbin*
-
-* Add I18n support for input/textarea placeholder text.
-
- Placeholder I18n follows the same convention as `label` I18n.
-
- *Alex Robbin*
-
-* Fix that render layout: 'messages/layout' should also be added to the dependency tracker tree.
-
- *DHH*
-
-* Add `PartialIteration` object used when rendering collections.
-
- The iteration object is available as the local variable
- `#{template_name}_iteration` when rendering partials with collections.
-
- It gives access to the `size` of the collection being iterated over,
- the current `index` and two convenience methods `first?` and `last?`.
-
- *Joel Junström*, *Lucas Uyezu*
-
-* Return an absolute instead of relative path from an asset url in the case
- of the `asset_host` proc returning nil.
-
- *Jolyon Pawlyn*
-
-* Fix `html_escape_once` to properly handle hex escape sequences (e.g. &#x1a2b;).
-
- *John F. Douthat*
-
-* Added String support for min and max properties for date field helpers.
-
- *Todd Bealmear*
-
-* The `highlight` helper now accepts a block to be used instead of the `highlighter`
- option.
-
- *Lucas Mazza*
-
-* The `except` and `highlight` helpers now accept regular expressions.
-
- *Jan Szumiec*
-
-* Flatten the array parameter in `safe_join`, so it behaves consistently with
- `Array#join`.
-
- *Paul Grayson*
-
-* Honor `html_safe` on array elements in tag values, as we do for plain string
- values.
-
- *Paul Grayson*
-
-* Add `ActionView::Template::Handler.unregister_template_handler`.
-
- It performs the opposite of `ActionView::Template::Handler.register_template_handler`.
-
- *Zuhao Wan*
-
-* Bring `cache_digest` rake tasks up-to-date with the latest API changes.
-
- *Jiri Pospisil*
-
-* Allow custom `:host` option to be passed to `asset_url` helper that
- overwrites `config.action_controller.asset_host` for particular asset.
-
- *Hubert Łępicki*
-
-* Deprecate `AbstractController::Base.parent_prefixes`.
- Override `AbstractController::Base.local_prefixes` when you want to change
- where to find views.
-
- *Nick Sutterer*
-
-* Take label values into account when doing I18n lookups for model attributes.
-
- The following:
-
- # form.html.erb
- <%= form_for @post do |f| %>
- <%= f.label :type, value: "long" %>
- <% end %>
-
- # en.yml
- en:
- activerecord:
- attributes:
- post/long: "Long-form Post"
-
- Used to simply return "long", but now it will return "Long-form
- Post".
-
- *Joshua Cody*
-
-* Change `asset_path` to use File.join to create proper paths:
-
- Before:
-
- https://some.host.com//assets/some.js
-
- After:
-
- https://some.host.com/assets/some.js
-
- *Peter Schröder*
-
-* Change `favicon_link_tag` default mimetype from `image/vnd.microsoft.icon` to
- `image/x-icon`.
-
- Before:
-
- # => favicon_link_tag 'myicon.ico'
- <link href="/assets/myicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon" />
-
- After:
-
- # => favicon_link_tag 'myicon.ico'
- <link href="/assets/myicon.ico" rel="shortcut icon" type="image/x-icon" />
-
- *Geoffroy Lorieux*
-
-* Remove wrapping div with inline styles for hidden form fields.
-
- We are dropping HTML 4.01 and XHTML strict compliance since input tags directly
- inside a form are valid HTML5, and the absence of inline styles help in validating
- for Content Security Policy.
-
- *Joost Baaij*
-
-* `collection_check_boxes` respects `:index` option for the hidden field name.
-
- Fixes #14147.
-
- *Vasiliy Ermolovich*
-
-* `date_select` helper with option `with_css_classes: true` does not overwrite other classes.
-
- *Izumi Wong-Horiuchi*
-
-* `number_to_percentage` does not crash with `Float::NAN` or `Float::INFINITY`
- as input.
-
- Fixes #14405.
-
- *Yves Senn*
-
-* Add `include_hidden` option to `collection_check_boxes` helper.
-
- *Vasiliy Ermolovich*
-
-* Fixed a problem where the default options for the `button_tag` helper are not
- applied correctly.
-
- Fixes #14254.
-
- *Sergey Prikhodko*
-
-* Take variants into account when calculating template digests in ActionView::Digestor.
-
- The arguments to ActionView::Digestor#digest are now being passed as a hash
- to support variants and allow more flexibility in the future. The support for
- regular (required) arguments is deprecated and will be removed in Rails 5.0 or later.
-
- *Piotr Chmolowski, Łukasz Strzałkowski*
-
-Please check [4-1-stable](https://github.com/rails/rails/blob/4-1-stable/actionview/CHANGELOG.md) for previous changes.
+Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/actionview/CHANGELOG.md) for previous changes.
diff --git a/actionview/actionview.gemspec b/actionview/actionview.gemspec
index 70efe7e8c2..fd4ffea33d 100644
--- a/actionview/actionview.gemspec
+++ b/actionview/actionview.gemspec
@@ -7,7 +7,7 @@ Gem::Specification.new do |s|
s.summary = 'Rendering framework putting the V in MVC (part of Rails).'
s.description = 'Simple, battle-tested conventions and helpers for building web pages.'
- s.required_ruby_version = '>= 1.9.3'
+ s.required_ruby_version = '>= 2.1.0'
s.license = 'MIT'
@@ -24,7 +24,7 @@ Gem::Specification.new do |s|
s.add_dependency 'builder', '~> 3.1'
s.add_dependency 'erubis', '~> 2.7.0'
s.add_dependency 'rails-html-sanitizer', '~> 1.0', '>= 1.0.1'
- s.add_dependency 'rails-dom-testing', '~> 1.0', '>= 1.0.4'
+ s.add_dependency 'rails-dom-testing', '~> 1.0', '>= 1.0.5'
s.add_development_dependency 'actionpack', version
s.add_development_dependency 'activemodel', version
diff --git a/actionview/lib/action_view/base.rb b/actionview/lib/action_view/base.rb
index 3071a13655..1feafc1094 100644
--- a/actionview/lib/action_view/base.rb
+++ b/actionview/lib/action_view/base.rb
@@ -126,8 +126,8 @@ module ActionView #:nodoc:
# end
# end
#
- # For more information on Builder please consult the [source
- # code](https://github.com/jimweirich/builder).
+ # For more information on Builder please consult the {source
+ # code}[https://github.com/jimweirich/builder].
class Base
include Helpers, ::ERB::Util, Context
diff --git a/actionview/lib/action_view/gem_version.rb b/actionview/lib/action_view/gem_version.rb
index 752eafee3c..4f45f5b8c8 100644
--- a/actionview/lib/action_view/gem_version.rb
+++ b/actionview/lib/action_view/gem_version.rb
@@ -5,10 +5,10 @@ module ActionView
end
module VERSION
- MAJOR = 4
- MINOR = 2
+ MAJOR = 5
+ MINOR = 0
TINY = 0
- PRE = "beta4"
+ PRE = "alpha"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/actionview/lib/action_view/helpers/date_helper.rb b/actionview/lib/action_view/helpers/date_helper.rb
index 01a9747035..4b4f0ae577 100644
--- a/actionview/lib/action_view/helpers/date_helper.rb
+++ b/actionview/lib/action_view/helpers/date_helper.rb
@@ -177,7 +177,7 @@ module ActionView
# and +:name+ (string). A format string would be something like "%{name} (%<number>02d)" for example.
# See <tt>Kernel.sprintf</tt> for documentation on format sequences.
# * <tt>:date_separator</tt> - Specifies a string to separate the date fields. Default is "" (i.e. nothing).
- # * <tt>:start_year</tt> - Set the start year for the year select. Default is <tt>Date.today.year - 5</tt>if
+ # * <tt>:start_year</tt> - Set the start year for the year select. Default is <tt>Date.today.year - 5</tt> if
# you are creating new record. While editing existing record, <tt>:start_year</tt> defaults to
# the current selected year minus 5.
# * <tt>:end_year</tt> - Set the end year for the year select. Default is <tt>Date.today.year + 5</tt> if
@@ -898,7 +898,7 @@ module ActionView
def translated_date_order
date_order = I18n.translate(:'date.order', :locale => @options[:locale], :default => [])
- date_order = date_order.map { |element| element.to_sym }
+ date_order = date_order.map(&:to_sym)
forbidden_elements = date_order - [:year, :month, :day]
if forbidden_elements.any?
diff --git a/actionview/lib/action_view/helpers/form_helper.rb b/actionview/lib/action_view/helpers/form_helper.rb
index 03f80ff360..6d10b41bd5 100644
--- a/actionview/lib/action_view/helpers/form_helper.rb
+++ b/actionview/lib/action_view/helpers/form_helper.rb
@@ -164,6 +164,23 @@ module ActionView
# * <tt>:namespace</tt> - A namespace for your form to ensure uniqueness of
# id attributes on form elements. The namespace attribute will be prefixed
# with underscore on the generated HTML id.
+ # * <tt>:method</tt> - The method to use when submitting the form, usually
+ # either "get" or "post". If "patch", "put", "delete", or another verb
+ # is used, a hidden input with name <tt>_method</tt> is added to
+ # simulate the verb over post.
+ # * <tt>:authenticity_token</tt> - Authenticity token to use in the form.
+ # Use only if you need to pass custom authenticity token string, or to
+ # not add authenticity_token field at all (by passing <tt>false</tt>).
+ # Remote forms may omit the embedded authenticity token by setting
+ # <tt>config.action_view.embed_authenticity_token_in_remote_forms = false</tt>.
+ # This is helpful when you're fragment-caching the form. Remote forms
+ # get the authenticity token from the <tt>meta</tt> tag, so embedding is
+ # unnecessary unless you support browsers without JavaScript.
+ # * <tt>:remote</tt> - If set to true, will allow the Unobtrusive
+ # JavaScript drivers to control the submit behavior. By default this
+ # behavior is an ajax submit.
+ # * <tt>:enforce_utf8</tt> - If set to false, a hidden input with name
+ # utf8 is not output.
# * <tt>:html</tt> - Optional HTML attributes for the form tag.
#
# Also note that +form_for+ doesn't create an exclusive scope. It's still
@@ -420,6 +437,7 @@ module ActionView
html_options[:data] = options.delete(:data) if options.has_key?(:data)
html_options[:remote] = options.delete(:remote) if options.has_key?(:remote)
html_options[:method] = options.delete(:method) if options.has_key?(:method)
+ html_options[:enforce_utf8] = options.delete(:enforce_utf8) if options.has_key?(:enforce_utf8)
html_options[:authenticity_token] = options.delete(:authenticity_token)
builder = instantiate_builder(object_name, object, options)
diff --git a/actionview/lib/action_view/helpers/form_options_helper.rb b/actionview/lib/action_view/helpers/form_options_helper.rb
index 83b07a00d4..bbfbf482a4 100644
--- a/actionview/lib/action_view/helpers/form_options_helper.rb
+++ b/actionview/lib/action_view/helpers/form_options_helper.rb
@@ -351,12 +351,12 @@ module ActionView
return container if String === container
selected, disabled = extract_selected_and_disabled(selected).map do |r|
- Array(r).map { |item| item.to_s }
+ Array(r).map(&:to_s)
end
container.map do |element|
html_attributes = option_html_attributes(element)
- text, value = option_text_and_value(element).map { |item| item.to_s }
+ text, value = option_text_and_value(element).map(&:to_s)
html_attributes[:selected] ||= option_value_selected?(value, selected)
html_attributes[:disabled] ||= disabled && option_value_selected?(value, disabled)
diff --git a/actionview/lib/action_view/helpers/form_tag_helper.rb b/actionview/lib/action_view/helpers/form_tag_helper.rb
index c0218fd55d..93c04fbec6 100644
--- a/actionview/lib/action_view/helpers/form_tag_helper.rb
+++ b/actionview/lib/action_view/helpers/form_tag_helper.rb
@@ -140,7 +140,9 @@ module ActionView
include_blank = ''
end
- option_tags = content_tag(:option, include_blank, value: '').safe_concat(option_tags)
+ if include_blank
+ option_tags = content_tag(:option, include_blank, value: '').safe_concat(option_tags)
+ end
end
if prompt = options.delete(:prompt)
diff --git a/actionview/lib/action_view/helpers/tag_helper.rb b/actionview/lib/action_view/helpers/tag_helper.rb
index b2038576a2..a87c223a71 100644
--- a/actionview/lib/action_view/helpers/tag_helper.rb
+++ b/actionview/lib/action_view/helpers/tag_helper.rb
@@ -18,7 +18,7 @@ module ActionView
itemscope allowfullscreen default inert sortable
truespeed typemustmatch).to_set
- BOOLEAN_ATTRIBUTES.merge(BOOLEAN_ATTRIBUTES.map {|attribute| attribute.to_sym })
+ BOOLEAN_ATTRIBUTES.merge(BOOLEAN_ATTRIBUTES.map(&:to_sym))
TAG_PREFIXES = ['aria', 'data', :aria, :data].to_set
diff --git a/actionview/lib/action_view/layouts.rb b/actionview/lib/action_view/layouts.rb
index 9ee05bd816..0b5c0b9991 100644
--- a/actionview/lib/action_view/layouts.rb
+++ b/actionview/lib/action_view/layouts.rb
@@ -262,7 +262,7 @@ module ActionView
def layout(layout, conditions = {})
include LayoutConditions unless conditions.empty?
- conditions.each {|k, v| conditions[k] = Array(v).map {|a| a.to_s} }
+ conditions.each {|k, v| conditions[k] = Array(v).map(&:to_s) }
self._layout_conditions = conditions
self._layout = layout
diff --git a/actionview/lib/action_view/renderer/partial_renderer.rb b/actionview/lib/action_view/renderer/partial_renderer.rb
index 0407632435..f627d5d40c 100644
--- a/actionview/lib/action_view/renderer/partial_renderer.rb
+++ b/actionview/lib/action_view/renderer/partial_renderer.rb
@@ -366,10 +366,12 @@ module ActionView
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
@@ -506,7 +508,7 @@ module ActionView
def retrieve_template_keys
keys = @locals.keys
- keys << @variable if @object || @collection
+ keys << @variable if @has_object || @collection
if @collection
keys << @variable_counter
keys << @variable_iteration
diff --git a/actionview/lib/action_view/rendering.rb b/actionview/lib/action_view/rendering.rb
index 5cbdfdf6c0..abd3b77c67 100644
--- a/actionview/lib/action_view/rendering.rb
+++ b/actionview/lib/action_view/rendering.rb
@@ -35,13 +35,13 @@ module ActionView
module ClassMethods
def view_context_class
@view_context_class ||= begin
- include_path_helpers = supports_path?
+ supports_path = supports_path?
routes = respond_to?(:_routes) && _routes
helpers = respond_to?(:_helpers) && _helpers
Class.new(ActionView::Base) do
if routes
- include routes.url_helpers(include_path_helpers)
+ include routes.url_helpers(supports_path)
include routes.mounted_helpers
end
diff --git a/actionview/lib/action_view/routing_url_for.rb b/actionview/lib/action_view/routing_url_for.rb
index 75febb8652..f281333a41 100644
--- a/actionview/lib/action_view/routing_url_for.rb
+++ b/actionview/lib/action_view/routing_url_for.rb
@@ -80,21 +80,38 @@ module ActionView
when String
options
when nil
- super({:only_path => true})
+ super(only_path: _generate_paths_by_default)
when Hash
options = options.symbolize_keys
- options[:only_path] = options[:host].nil? unless options.key?(:only_path)
+ unless options.key?(:only_path)
+ if options[:host].nil?
+ options[:only_path] = _generate_paths_by_default
+ else
+ options[:only_path] = false
+ end
+ end
+
super(options)
when :back
_back_url
- when Symbol
- ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.path.handle_string_call self, options
when Array
- polymorphic_path(options, options.extract_options!)
- when Class
- ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.path.handle_class_call self, options
+ if _generate_paths_by_default
+ polymorphic_path(options, options.extract_options!)
+ else
+ polymorphic_url(options, options.extract_options!)
+ end
else
- ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.path.handle_model_call self, options
+ method = _generate_paths_by_default ? :path : :url
+ builder = ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.send(method)
+
+ case options
+ when Symbol
+ builder.handle_string_call(self, options)
+ when Class
+ builder.handle_class_call(self, options)
+ else
+ builder.handle_model_call(self, options)
+ end
end
end
diff --git a/actionview/lib/action_view/template/error.rb b/actionview/lib/action_view/template/error.rb
index 743ef6de0a..390bce98a2 100644
--- a/actionview/lib/action_view/template/error.rb
+++ b/actionview/lib/action_view/template/error.rb
@@ -75,7 +75,7 @@ module ActionView
def sub_template_message
if @sub_templates
"Trace of template inclusion: " +
- @sub_templates.collect { |template| template.inspect }.join(", ")
+ @sub_templates.collect(&:inspect).join(", ")
else
""
end
diff --git a/actionview/lib/action_view/template/handlers.rb b/actionview/lib/action_view/template/handlers.rb
index 33bfcb458c..9e61ea4225 100644
--- a/actionview/lib/action_view/template/handlers.rb
+++ b/actionview/lib/action_view/template/handlers.rb
@@ -22,7 +22,7 @@ module ActionView #:nodoc:
# Register an object that knows how to handle template files with the given
# extensions. This can be used to implement new template types.
- # The handler must respond to `:call`, which will be passed the template
+ # The handler must respond to +:call+, which will be passed the template
# and should return the rendered template as a String.
def register_template_handler(*extensions, handler)
raise(ArgumentError, "Extension is required") if extensions.empty?
@@ -42,7 +42,7 @@ module ActionView #:nodoc:
end
def template_handler_extensions
- @@template_handlers.keys.map {|key| key.to_s }.sort
+ @@template_handlers.keys.map(&:to_s).sort
end
def registered_template_handler(extension)
diff --git a/actionview/lib/action_view/template/handlers/erb.rb b/actionview/lib/action_view/template/handlers/erb.rb
index 3c2224fbf5..85a100ed4c 100644
--- a/actionview/lib/action_view/template/handlers/erb.rb
+++ b/actionview/lib/action_view/template/handlers/erb.rb
@@ -35,7 +35,7 @@ module ActionView
end
end
- BLOCK_EXPR = /\s+(do|\{)(\s*\|[^|]*\|)?\s*\Z/
+ BLOCK_EXPR = /\s*((\s+|\))do|\{)(\s*\|[^|]*\|)?\s*\Z/
def add_expr_literal(src, code)
flush_newline_if_pending(src)
diff --git a/actionview/lib/action_view/template/resolver.rb b/actionview/lib/action_view/template/resolver.rb
index b65507f4a2..29d2e9ca90 100644
--- a/actionview/lib/action_view/template/resolver.rb
+++ b/actionview/lib/action_view/template/resolver.rb
@@ -139,7 +139,7 @@ module ActionView
# resolver is fresher before returning it.
def cached(key, path_info, details, locals) #:nodoc:
name, prefix, partial = path_info
- locals = locals.map { |x| x.to_s }.sort!
+ locals = locals.map(&:to_s).sort!
if key
@cache.cache(key, name, prefix, partial, locals) do
diff --git a/actionview/lib/action_view/template/types.rb b/actionview/lib/action_view/template/types.rb
index b84e0281ae..be45fcf742 100644
--- a/actionview/lib/action_view/template/types.rb
+++ b/actionview/lib/action_view/template/types.rb
@@ -9,7 +9,7 @@ module ActionView
self.types = Set.new
def self.register(*t)
- types.merge(t.map { |type| type.to_s })
+ types.merge(t.map(&:to_s))
end
register :html, :text, :js, :css, :xml, :json
diff --git a/actionview/lib/action_view/test_case.rb b/actionview/lib/action_view/test_case.rb
index fec980462d..812b011bd7 100644
--- a/actionview/lib/action_view/test_case.rb
+++ b/actionview/lib/action_view/test_case.rb
@@ -125,6 +125,7 @@ module ActionView
@_rendered_views ||= RenderedViewsCollection.new
end
+ # Need to experiment if this priority is the best one: rendered => output_buffer
class RenderedViewsCollection
def initialize
@rendered_views ||= Hash.new { |hash, key| hash[key] = [] }
@@ -158,7 +159,7 @@ module ActionView
# Need to experiment if this priority is the best one: rendered => output_buffer
def document_root_element
- Nokogiri::HTML::DocumentFragment.parse(@rendered.blank? ? @output_buffer : @rendered)
+ Nokogiri::HTML::Document.parse(@rendered.blank? ? @output_buffer : @rendered).root
end
def say_no_to_protect_against_forgery!
diff --git a/actionview/test/abstract_unit.rb b/actionview/test/abstract_unit.rb
index 7096d588b6..4aa56f60f7 100644
--- a/actionview/test/abstract_unit.rb
+++ b/actionview/test/abstract_unit.rb
@@ -46,7 +46,7 @@ I18n.enforce_available_locales = false
# Register danish language for testing
I18n.backend.store_translations 'da', {}
I18n.backend.store_translations 'pt-BR', {}
-ORIGINAL_LOCALES = I18n.available_locales.map {|locale| locale.to_s }.sort
+ORIGINAL_LOCALES = I18n.available_locales.map(&:to_s).sort
FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), 'fixtures')
FIXTURES = Pathname.new(FIXTURE_LOAD_PATH)
diff --git a/actionview/test/actionpack/controller/view_paths_test.rb b/actionview/test/actionpack/controller/view_paths_test.rb
index c6e7a523b9..7fba9ff8ff 100644
--- a/actionview/test/actionpack/controller/view_paths_test.rb
+++ b/actionview/test/actionpack/controller/view_paths_test.rb
@@ -39,7 +39,7 @@ class ViewLoadPathsTest < ActionController::TestCase
def assert_paths(*paths)
controller = paths.first.is_a?(Class) ? paths.shift : @controller
- assert_equal expand(paths), controller.view_paths.map { |p| p.to_s }
+ assert_equal expand(paths), controller.view_paths.map(&:to_s)
end
def test_template_load_path_was_set_correctly
diff --git a/actionview/test/template/debug_helper_test.rb b/actionview/test/activerecord/debug_helper_test.rb
index 5609694cd5..5609694cd5 100644
--- a/actionview/test/template/debug_helper_test.rb
+++ b/actionview/test/activerecord/debug_helper_test.rb
diff --git a/actionview/test/fixtures/test/_label_with_block.erb b/actionview/test/fixtures/test/_label_with_block.erb
index 40117e594e..94089ea93d 100644
--- a/actionview/test/fixtures/test/_label_with_block.erb
+++ b/actionview/test/fixtures/test/_label_with_block.erb
@@ -1,4 +1,4 @@
-<%= label 'post', 'message' do %>
+<%= label('post', 'message')do %>
Message
<%= text_field 'post', 'message' %>
<% end %>
diff --git a/actionview/test/template/date_helper_test.rb b/actionview/test/template/date_helper_test.rb
index 0cdb130710..a6962b5200 100644
--- a/actionview/test/template/date_helper_test.rb
+++ b/actionview/test/template/date_helper_test.rb
@@ -1504,7 +1504,7 @@ class DateHelperTest < ActionView::TestCase
expected << %(<option value="">Choose seconds</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18" selected="selected">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n<option value="32">32</option>\n<option value="33">33</option>\n<option value="34">34</option>\n<option value="35">35</option>\n<option value="36">36</option>\n<option value="37">37</option>\n<option value="38">38</option>\n<option value="39">39</option>\n<option value="40">40</option>\n<option value="41">41</option>\n<option value="42">42</option>\n<option value="43">43</option>\n<option value="44">44</option>\n<option value="45">45</option>\n<option value="46">46</option>\n<option value="47">47</option>\n<option value="48">48</option>\n<option value="49">49</option>\n<option value="50">50</option>\n<option value="51">51</option>\n<option value="52">52</option>\n<option value="53">53</option>\n<option value="54">54</option>\n<option value="55">55</option>\n<option value="56">56</option>\n<option value="57">57</option>\n<option value="58">58</option>\n<option value="59">59</option>\n)
expected << "</select>\n"
- assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), :prompt => true, :include_seconds => true,
+ assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), :include_seconds => true,
:prompt => {:hour => 'Choose hour', :minute => 'Choose minute', :second => 'Choose seconds'})
end
diff --git a/actionview/test/template/erb_util_test.rb b/actionview/test/template/erb_util_test.rb
index 3bb84cbc50..3e72be31de 100644
--- a/actionview/test/template/erb_util_test.rb
+++ b/actionview/test/template/erb_util_test.rb
@@ -84,7 +84,7 @@ class ErbUtilTest < ActiveSupport::TestCase
end
def test_rest_in_ascii
- (0..127).to_a.map {|int| int.chr }.each do |chr|
+ (0..127).to_a.map(&:chr).each do |chr|
next if %('"&<>).include?(chr)
assert_equal chr, html_escape(chr)
end
diff --git a/actionview/test/template/form_helper_test.rb b/actionview/test/template/form_helper_test.rb
index 4bbbdf4fb1..a131752b2a 100644
--- a/actionview/test/template/form_helper_test.rb
+++ b/actionview/test/template/form_helper_test.rb
@@ -1864,6 +1864,30 @@ class FormHelperTest < ActionView::TestCase
assert_dom_equal expected, output_buffer
end
+ def test_form_for_enforce_utf8_true
+ form_for(:post, enforce_utf8: true) do |f|
+ concat f.text_field(:title)
+ end
+
+ expected = whole_form("/", nil, nil, enforce_utf8: true) do
+ "<input name='post[title]' type='text' id='post_title' value='Hello World' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_form_for_enforce_utf8_false
+ form_for(:post, enforce_utf8: false) do |f|
+ concat f.text_field(:title)
+ end
+
+ expected = whole_form("/", nil, nil, enforce_utf8: false) do
+ "<input name='post[title]' type='text' id='post_title' value='Hello World' />"
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
def test_form_for_with_remote_in_html
form_for(@post, url: '/', html: { remote: true, id: 'create-post', method: :patch }) do |f|
concat f.text_field(:title)
@@ -3313,8 +3337,14 @@ class FormHelperTest < ActionView::TestCase
protected
- def hidden_fields(method = nil)
- txt = %{<input name="utf8" type="hidden" value="&#x2713;" />}
+ def hidden_fields(options = {})
+ method = options[:method]
+
+ if options.fetch(:enforce_utf8, true)
+ txt = %{<input name="utf8" type="hidden" value="&#x2713;" />}
+ else
+ txt = ''
+ end
if method && !%w(get post).include?(method.to_s)
txt << %{<input name="_method" type="hidden" value="#{method}" />}
@@ -3338,7 +3368,7 @@ class FormHelperTest < ActionView::TestCase
method, remote, multipart = options.values_at(:method, :remote, :multipart)
- form_text(action, id, html_class, remote, multipart, method) + hidden_fields(method) + contents + "</form>"
+ form_text(action, id, html_class, remote, multipart, method) + hidden_fields(options.slice :method, :enforce_utf8) + contents + "</form>"
end
def protect_against_forgery?
diff --git a/actionview/test/template/form_tag_helper_test.rb b/actionview/test/template/form_tag_helper_test.rb
index f8fd642809..84a581b107 100644
--- a/actionview/test/template/form_tag_helper_test.rb
+++ b/actionview/test/template/form_tag_helper_test.rb
@@ -232,6 +232,12 @@ class FormTagHelperTest < ActionView::TestCase
assert_dom_equal expected, actual
end
+ def test_select_tag_with_include_blank_false
+ actual = select_tag "places", "<option>Home</option><option>Work</option><option>Pub</option>".html_safe, include_blank: false
+ expected = %(<select id="places" name="places"><option>Home</option><option>Work</option><option>Pub</option></select>)
+ assert_dom_equal expected, actual
+ end
+
def test_select_tag_with_include_blank_string
actual = select_tag "places", "<option>Home</option><option>Work</option><option>Pub</option>".html_safe, include_blank: 'Choose'
expected = %(<select id="places" name="places"><option value="">Choose</option><option>Home</option><option>Work</option><option>Pub</option></select>)
diff --git a/actionview/test/template/render_test.rb b/actionview/test/template/render_test.rb
index 85817119ba..4e502bede9 100644
--- a/actionview/test/template/render_test.rb
+++ b/actionview/test/template/render_test.rb
@@ -16,7 +16,7 @@ module RenderTestCases
I18n.backend.store_translations 'pt-BR', {}
# Ensure original are still the same since we are reindexing view paths
- assert_equal ORIGINAL_LOCALES, I18n.available_locales.map {|l| l.to_s }.sort
+ assert_equal ORIGINAL_LOCALES, I18n.available_locales.map(&:to_s).sort
end
def test_render_without_options
diff --git a/activejob/CHANGELOG.md b/activejob/CHANGELOG.md
index b04883413e..f9c481998e 100644
--- a/activejob/CHANGELOG.md
+++ b/activejob/CHANGELOG.md
@@ -1 +1 @@
-* Started project. \ No newline at end of file
+Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/activejob/CHANGELOG.md) for previous changes.
diff --git a/activejob/README.md b/activejob/README.md
index b5d27272b1..8c83d3669a 100644
--- a/activejob/README.md
+++ b/activejob/README.md
@@ -5,7 +5,7 @@ of queueing backends. These jobs can be everything from regularly scheduled
clean-ups, to billing charges, to mailings. Anything that can be chopped up into
small units of work and run in parallel, really.
-It also serves as the backend for ActionMailer's #deliver_later functionality
+It also serves as the backend for Action Mailer's #deliver_later functionality
that makes it easy to turn any mailing into a job for running later. That's
one of the most common jobs in a modern web application: Sending emails outside
of the request-response cycle, so the user doesn't have to wait on it.
@@ -26,7 +26,8 @@ Set the queue adapter for Active Job:
ActiveJob::Base.queue_adapter = :inline # default queue adapter
```
Note: To learn how to use your preferred queueing backend see its adapter
-documentation at ActiveJob::QueueAdapters.
+documentation at
+[ActiveJob::QueueAdapters](http://api.rubyonrails.org/classes/ActiveJob/QueueAdapters.html).
Declare a job like so:
@@ -110,7 +111,7 @@ Source code can be downloaded as part of the Rails project on GitHub
## License
-ActiveJob is released under the MIT license:
+Active Job is released under the MIT license:
* http://www.opensource.org/licenses/MIT
@@ -128,5 +129,3 @@ Bug reports can be filed for the Ruby on Rails project here:
Feature requests should be discussed on the rails-core mailing list here:
* https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core
-
-
diff --git a/activejob/activejob.gemspec b/activejob/activejob.gemspec
index a9be2a8f00..f6c8bc1682 100644
--- a/activejob/activejob.gemspec
+++ b/activejob/activejob.gemspec
@@ -7,7 +7,7 @@ Gem::Specification.new do |s|
s.summary = 'Job framework with pluggable queues.'
s.description = 'Declare job classes that can be run by a variety of queueing backends.'
- s.required_ruby_version = '>= 1.9.3'
+ s.required_ruby_version = '>= 2.1.0'
s.license = 'MIT'
diff --git a/activejob/lib/active_job/base.rb b/activejob/lib/active_job/base.rb
index 0c4a29090e..fd49b3fda5 100644
--- a/activejob/lib/active_job/base.rb
+++ b/activejob/lib/active_job/base.rb
@@ -32,7 +32,7 @@ module ActiveJob #:nodoc:
# end
#
# Records that are passed in are serialized/deserialized using Global
- # Id. More information can be found in Arguments.
+ # ID. More information can be found in Arguments.
#
# To enqueue a job to be performed as soon the queueing system is free:
#
diff --git a/activejob/lib/active_job/gem_version.rb b/activejob/lib/active_job/gem_version.rb
index ac364f77d1..27a5de93f4 100644
--- a/activejob/lib/active_job/gem_version.rb
+++ b/activejob/lib/active_job/gem_version.rb
@@ -5,10 +5,10 @@ module ActiveJob
end
module VERSION
- MAJOR = 4
- MINOR = 2
+ MAJOR = 5
+ MINOR = 0
TINY = 0
- PRE = "beta4"
+ PRE = "alpha"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/activejob/lib/active_job/queue_adapters.rb b/activejob/lib/active_job/queue_adapters.rb
index f22b0502dc..4b91c93dbe 100644
--- a/activejob/lib/active_job/queue_adapters.rb
+++ b/activejob/lib/active_job/queue_adapters.rb
@@ -19,6 +19,7 @@ module ActiveJob
# |-------------------|-------|--------|-----------|------------|---------|---------|
# | Backburner | Yes | Yes | Yes | Yes | Job | Global |
# | Delayed Job | Yes | Yes | Yes | Job | Global | Global |
+ # | Qu | Yes | Yes | No | No | No | Global |
# | Que | Yes | Yes | Yes | Job | No | Job |
# | queue_classic | Yes | Yes | No* | No | No | No |
# | Resque | Yes | Yes | Yes (Gem) | Queue | Global | Yes |
diff --git a/activejob/lib/active_job/test_helper.rb b/activejob/lib/active_job/test_helper.rb
index bb20d93947..1720b140e5 100644
--- a/activejob/lib/active_job/test_helper.rb
+++ b/activejob/lib/active_job/test_helper.rb
@@ -77,13 +77,21 @@ module ActiveJob
end
# Asserts that the number of performed jobs matches the given number.
+ # If no block is passed, <tt>perform_enqueued_jobs</tt>
+ # must be called around the job call.
#
# def test_jobs
# assert_performed_jobs 0
- # HelloJob.perform_later('xavier')
+ #
+ # perform_enqueued_jobs do
+ # HelloJob.perform_later('xavier')
+ # end
# assert_performed_jobs 1
- # HelloJob.perform_later('yves')
- # assert_performed_jobs 2
+ #
+ # perform_enqueued_jobs do
+ # HelloJob.perform_later('yves')
+ # assert_performed_jobs 2
+ # end
# end
#
# If a block is passed, that block should cause the specified number of
@@ -102,7 +110,7 @@ module ActiveJob
def assert_performed_jobs(number)
if block_given?
original_count = performed_jobs.size
- yield
+ perform_enqueued_jobs { yield }
new_count = performed_jobs.size
assert_equal original_count + number, new_count,
"#{number} jobs expected, but #{new_count - original_count} were performed"
@@ -116,8 +124,11 @@ module ActiveJob
#
# def test_jobs
# assert_no_performed_jobs
- # HelloJob.perform_later('matthew')
- # assert_performed_jobs 1
+ #
+ # perform_enqueued_jobs do
+ # HelloJob.perform_later('matthew')
+ # assert_performed_jobs 1
+ # end
# end
#
# If a block is passed, that block should not cause any job to be performed.
@@ -166,7 +177,7 @@ module ActiveJob
original_performed_jobs = performed_jobs.dup
clear_performed_jobs
args.assert_valid_keys(:job, :args, :at, :queue)
- yield
+ perform_enqueued_jobs { yield }
matching_job = performed_jobs.any? do |job|
args.all? { |key, value| value == job[key] }
end
@@ -175,6 +186,17 @@ module ActiveJob
queue_adapter.performed_jobs = original_performed_jobs + performed_jobs
end
+ def perform_enqueued_jobs
+ @old_perform_enqueued_jobs = queue_adapter.perform_enqueued_jobs
+ @old_perform_enqueued_at_jobs = queue_adapter.perform_enqueued_at_jobs
+ queue_adapter.perform_enqueued_jobs = true
+ queue_adapter.perform_enqueued_at_jobs = true
+ yield
+ ensure
+ queue_adapter.perform_enqueued_jobs = @old_perform_enqueued_jobs
+ queue_adapter.perform_enqueued_at_jobs = @old_perform_enqueued_at_jobs
+ end
+
def queue_adapter
ActiveJob::Base.queue_adapter
end
diff --git a/activejob/test/cases/test_helper_test.rb b/activejob/test/cases/test_helper_test.rb
index 71c505a65f..784ede3674 100644
--- a/activejob/test/cases/test_helper_test.rb
+++ b/activejob/test/cases/test_helper_test.rb
@@ -6,8 +6,6 @@ require 'jobs/logging_job'
require 'jobs/nested_job'
class EnqueuedJobsTest < ActiveJob::TestCase
- setup { queue_adapter.perform_enqueued_at_jobs = true }
-
def test_assert_enqueued_jobs
assert_nothing_raised do
assert_enqueued_jobs 1 do
@@ -44,11 +42,16 @@ class EnqueuedJobsTest < ActiveJob::TestCase
end
end
+ def test_assert_no_enqueued_jobs_with_no_block
+ assert_nothing_raised do
+ assert_no_enqueued_jobs
+ end
+ end
+
def test_assert_no_enqueued_jobs
assert_nothing_raised do
assert_no_enqueued_jobs do
- # Scheduled jobs are being performed in this context
- HelloJob.set(wait_until: Date.tomorrow.noon).perform_later('godfrey')
+ HelloJob.perform_now
end
end
end
@@ -86,7 +89,7 @@ class EnqueuedJobsTest < ActiveJob::TestCase
def test_assert_enqueued_job
assert_enqueued_with(job: LoggingJob, queue: 'default') do
- NestedJob.set(wait_until: Date.tomorrow.noon).perform_later
+ LoggingJob.set(wait_until: Date.tomorrow.noon).perform_later
end
end
@@ -116,8 +119,6 @@ class EnqueuedJobsTest < ActiveJob::TestCase
end
class PerformedJobsTest < ActiveJob::TestCase
- setup { queue_adapter.perform_enqueued_jobs = true }
-
def test_assert_performed_jobs
assert_nothing_raised do
assert_performed_jobs 1 do
@@ -143,22 +144,31 @@ class PerformedJobsTest < ActiveJob::TestCase
def test_assert_performed_jobs_with_no_block
assert_nothing_raised do
- HelloJob.perform_later('rafael')
+ perform_enqueued_jobs do
+ HelloJob.perform_later('rafael')
+ end
assert_performed_jobs 1
end
assert_nothing_raised do
- HelloJob.perform_later('aaron')
- HelloJob.perform_later('matthew')
- assert_performed_jobs 3
+ perform_enqueued_jobs do
+ HelloJob.perform_later('aaron')
+ HelloJob.perform_later('matthew')
+ assert_performed_jobs 3
+ end
+ end
+ end
+
+ def test_assert_no_performed_jobs_with_no_block
+ assert_nothing_raised do
+ assert_no_performed_jobs
end
end
def test_assert_no_performed_jobs
assert_nothing_raised do
assert_no_performed_jobs do
- # Scheduled jobs are being enqueued in this context
- HelloJob.set(wait_until: Date.tomorrow.noon).perform_later('godfrey')
+ # empty block won't perform jobs
end
end
end
diff --git a/activejob/test/support/delayed_job/delayed/backend/test.rb b/activejob/test/support/delayed_job/delayed/backend/test.rb
index b50ed36fc2..f80ec3a5a6 100644
--- a/activejob/test/support/delayed_job/delayed/backend/test.rb
+++ b/activejob/test/support/delayed_job/delayed/backend/test.rb
@@ -43,9 +43,7 @@ module Delayed
end
def self.create(attrs = {})
- new(attrs).tap do |o|
- o.save
- end
+ new(attrs).tap(&:save)
end
def self.create!(*args); create(*args); end
diff --git a/activejob/test/support/integration/adapters/sidekiq.rb b/activejob/test/support/integration/adapters/sidekiq.rb
index 3cc9a34993..bdc61a1462 100644
--- a/activejob/test/support/integration/adapters/sidekiq.rb
+++ b/activejob/test/support/integration/adapters/sidekiq.rb
@@ -48,7 +48,7 @@ module SidekiqJobsManager
def can_run?
begin
- Sidekiq.redis { |conn| conn.connect }
+ Sidekiq.redis(&:connect)
rescue
return false
end
diff --git a/activemodel/CHANGELOG.md b/activemodel/CHANGELOG.md
index 5588699d9b..b86e988841 100644
--- a/activemodel/CHANGELOG.md
+++ b/activemodel/CHANGELOG.md
@@ -1,61 +1 @@
-* Passwords with spaces only allowed in `ActiveModel::SecurePassword`.
-
- Presence validation can be used to restore old behavior.
-
- *Yevhene Shemet*
-
-* Validate options passed to `ActiveModel::Validations.validate`.
-
- Preventing, in many cases, the simple mistake of using `validate` instead of `validates`.
-
- *Sonny Michaud*
-
-* Deprecate `reset_#{attribute}` in favor of `restore_#{attribute}`.
-
- These methods may cause confusion with the `reset_changes`, which has
- different behaviour.
-
- *Rafael Mendonça França*
-
-* Deprecate `ActiveModel::Dirty#reset_changes` in favor of `#clear_changes_information`.
-
- Method's name is causing confusion with the `reset_#{attribute}` methods.
- While `reset_name` sets the value of the name attribute to previous value
- `reset_changes` only discards the changes.
-
- *Rafael Mendonça França*
-
-* Added `restore_attributes` method to `ActiveModel::Dirty` API which restores
- the value of changed attributes to previous value.
-
- *Igor G.*
-
-* Allow proc and symbol as values for `only_integer` of `NumericalityValidator`
-
- *Robin Mehner*
-
-* `has_secure_password` now verifies that the given password is less than 72
- characters if validations are enabled.
-
- Fixes #14591.
-
- *Akshay Vishnoi*
-
-* Remove deprecated `Validator#setup` without replacement.
-
- See #10716.
-
- *Kuldeep Aggarwal*
-
-* Add plural and singular form for length validator's default messages.
-
- *Abd ar-Rahman Hamid*
-
-* Introduce `validate` as an alias for `valid?`.
-
- This is more intuitive when you want to run validations but don't care about
- the return value.
-
- *Henrik Nyh*
-
-Please check [4-1-stable](https://github.com/rails/rails/blob/4-1-stable/activemodel/CHANGELOG.md) for previous changes.
+Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/activemodel/CHANGELOG.md) for previous changes.
diff --git a/activemodel/activemodel.gemspec b/activemodel/activemodel.gemspec
index 36e565f692..73600b83fb 100644
--- a/activemodel/activemodel.gemspec
+++ b/activemodel/activemodel.gemspec
@@ -7,7 +7,7 @@ Gem::Specification.new do |s|
s.summary = 'A toolkit for building modeling frameworks (part of Rails).'
s.description = 'A toolkit for building modeling frameworks like Active Record. Rich support for attributes, callbacks, validations, serialization, internationalization, and testing.'
- s.required_ruby_version = '>= 1.9.3'
+ s.required_ruby_version = '>= 2.1.0'
s.license = 'MIT'
diff --git a/activemodel/lib/active_model/dirty.rb b/activemodel/lib/active_model/dirty.rb
index ae185694ca..4e389c8692 100644
--- a/activemodel/lib/active_model/dirty.rb
+++ b/activemodel/lib/active_model/dirty.rb
@@ -255,7 +255,7 @@ module ActiveModel
end
# Remove changes information for the provided attributes.
- def clear_attribute_changes(attributes)
+ def clear_attribute_changes(attributes) # :doc:
attributes_changed_by_setter.except!(*attributes)
end
end
diff --git a/activemodel/lib/active_model/gem_version.rb b/activemodel/lib/active_model/gem_version.rb
index 932fe3e5a9..2403242ce6 100644
--- a/activemodel/lib/active_model/gem_version.rb
+++ b/activemodel/lib/active_model/gem_version.rb
@@ -5,10 +5,10 @@ module ActiveModel
end
module VERSION
- MAJOR = 4
- MINOR = 2
+ MAJOR = 5
+ MINOR = 0
TINY = 0
- PRE = "beta4"
+ PRE = "alpha"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/activemodel/lib/active_model/serializers/json.rb b/activemodel/lib/active_model/serializers/json.rb
index 77f2a64b11..b66dbf1afe 100644
--- a/activemodel/lib/active_model/serializers/json.rb
+++ b/activemodel/lib/active_model/serializers/json.rb
@@ -130,10 +130,10 @@ module ActiveModel
#
# json = { person: { name: 'bob', age: 22, awesome:true } }.to_json
# person = Person.new
- # person.from_json(json) # => #<Person:0x007fec5e7a0088 @age=22, @awesome=true, @name="bob">
- # person.name # => "bob"
- # person.age # => 22
- # person.awesome # => true
+ # person.from_json(json, true) # => #<Person:0x007fec5e7a0088 @age=22, @awesome=true, @name="bob">
+ # person.name # => "bob"
+ # person.age # => 22
+ # person.awesome # => true
def from_json(json, include_root=include_root_in_json)
hash = ActiveSupport::JSON.decode(json)
hash = hash.values.first if include_root
diff --git a/activemodel/test/cases/validations/numericality_validation_test.rb b/activemodel/test/cases/validations/numericality_validation_test.rb
index 3834d327ea..12a22f9c40 100644
--- a/activemodel/test/cases/validations/numericality_validation_test.rb
+++ b/activemodel/test/cases/validations/numericality_validation_test.rb
@@ -59,7 +59,7 @@ class NumericalityValidationTest < ActiveModel::TestCase
def test_validates_numericality_of_with_integer_only_and_proc_as_value
Topic.send(:define_method, :allow_only_integers?, lambda { false })
- Topic.validates_numericality_of :approved, only_integer: Proc.new {|topic| topic.allow_only_integers? }
+ Topic.validates_numericality_of :approved, only_integer: Proc.new(&:allow_only_integers?)
invalid!(NIL + BLANK + JUNK)
valid!(FLOATS + INTEGERS + BIGDECIMAL + INFINITY)
@@ -130,7 +130,7 @@ class NumericalityValidationTest < ActiveModel::TestCase
def test_validates_numericality_with_proc
Topic.send(:define_method, :min_approved, lambda { 5 })
- Topic.validates_numericality_of :approved, greater_than_or_equal_to: Proc.new {|topic| topic.min_approved }
+ Topic.validates_numericality_of :approved, greater_than_or_equal_to: Proc.new(&:min_approved)
invalid!([3, 4])
valid!([5, 6])
diff --git a/activemodel/test/cases/validations_test.rb b/activemodel/test/cases/validations_test.rb
index de71bb6f42..98e0266d7e 100644
--- a/activemodel/test/cases/validations_test.rb
+++ b/activemodel/test/cases/validations_test.rb
@@ -282,7 +282,7 @@ class ValidationsTest < ActiveModel::TestCase
ActiveModel::Validations::FormatValidator,
ActiveModel::Validations::LengthValidator,
ActiveModel::Validations::PresenceValidator
- ], validators.map { |v| v.class }.sort_by { |c| c.to_s }
+ ], validators.map(&:class).sort_by(&:to_s)
end
def test_list_of_validators_will_be_empty_when_empty
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md
index f7ca41908d..38c5583708 100644
--- a/activerecord/CHANGELOG.md
+++ b/activerecord/CHANGELOG.md
@@ -1,1273 +1 @@
-* Deprecate `sanitize_sql_hash_for_conditions` without replacement. Using a
- `Relation` for performing queries and updates is the prefered API.
-
- *Sean Griffin*
-
-* Queries now properly type cast values that are part of a join statement,
- even when using type decorators such as `serialize`.
-
- *Melanie Gilman & Sean Griffin*
-
-* MySQL enum type lookups, with values matching another type, no longer result
- in an endless loop.
-
- Fixes #17402.
-
- *Yves Senn*
-
-* Raise `ArgumentError` when the body of a scope is not callable.
-
- *Mauro George*
-
-* Use type column first in multi-column indexes created with `add-reference`.
-
- *Derek Prior*
-
-* Fix `Relation.rewhere` to work with Range values.
-
- *Dan Olson*
-
-* `AR::UnknownAttributeError` now includes the class name of a record.
-
- User.new(name: "Yuki Nishijima", project_attributes: {name: "kaminari"})
- # => ActiveRecord::UnknownAttributeError: unknown attribute 'name' for User.
-
- *Yuki Nishijima*
-
-* Fix regression causing `after_create` callbacks to run before associated
- records are autosaved.
-
- Fixes #17209.
-
- *Agis Anastasopoulos*
-
-* Honor overridden `rack.test` in Rack environment for the connection
- management middleware.
-
- *Simon Eskildsen*
-
-* Add a truncate method to the connection.
-
- *Aaron Patterson*
-
-* Don't autosave unchanged has_one through records.
-
- *Alan Kennedy*, *Steve Parrington*
-
-* Do not dump foreign keys for ignored tables.
-
- *Yves Senn*
-
-* PostgreSQL adapter correctly dumps foreign keys targeting tables
- outside the schema search path.
-
- Fixes #16907.
-
- *Matthew Draper*, *Yves Senn*
-
-* When a thread is killed, rollback the active transaction, instead of
- committing it during the stack unwind. Previously, we could commit half-
- completed work. This fix only works for Ruby 2.0+; on 1.9, we can't
- distinguish a thread kill from an ordinary non-local (block) return, so must
- default to committing.
-
- *Chris Hanks*
-
-* A `NullRelation` should represent nothing. This fixes a bug where
- `Comment.where(post_id: Post.none)` returned a non-empty result.
-
- Fixes #15176.
-
- *Matthew Draper*, *Yves Senn*
-
-* Include default column limits in schema.rb. Allows defaults to be changed
- in the future without affecting old migrations that assumed old defaults.
-
- *Jeremy Kemper*
-
-* MySQL: schema.rb now includes TEXT and BLOB column limits.
-
- *Jeremy Kemper*
-
-* MySQL: correct LONGTEXT and LONGBLOB limits from 2GB to their true 4GB.
-
- *Jeremy Kemper*
-
-* SQLite3Adapter now checks for views in `table_exists?`. Fixes #14041.
-
- *Girish Sonawane*
-
-* Introduce `connection.supports_views?` to check whether the current adapter
- has support for SQL views. Connection adapters should define this method.
-
- *Yves Senn*
-
-* Allow included modules to override association methods.
-
- Fixes #16684.
-
- *Yves Senn*
-
-* Schema loading rake tasks (like `db:schema:load` and `db:setup`) maintain
- the database connection to the current environment.
-
- Fixes #16757.
-
- *Joshua Cody*, *Yves Senn*
-
-* MySQL: set the connection collation along with the charset.
-
- Sets the connection collation to the database collation configured in
- database.yml. Otherwise, `SET NAMES utf8mb4` will use the default
- collation for that charset (utf8mb4_general_ci) when you may have chosen
- a different collation, like utf8mb4_unicode_ci.
-
- This only applies to literal string comparisons, not column values, so it
- is unlikely to affect you.
-
- *Jeremy Kemper*
-
-* `default_sequence_name` from the PostgreSQL adapter returns a `String`.
-
- *Yves Senn*
-
-* Fixed a regression where whitespaces were stripped from DISTINCT queries in
- PostgreSQL.
-
- *Agis Anastasopoulos*
-
- Fixes #16623.
-
-* Fix has_many :through relation merging failing when dynamic conditions are
- passed as a lambda with an arity of one.
-
- Fixes #16128.
-
- *Agis Anastasopoulos*
-
-* Fixed `Relation#exists?` to work with polymorphic associations.
-
- Fixes #15821.
-
- *Kassio Borges*
-
-* Currently, Active Record rescues any errors raised within
- `after_rollback`/`after_create` callbacks and prints them to the logs.
- Future versions of Rails will not rescue these errors anymore and
- just bubble them up like the other callbacks.
-
- This commit adds an opt-in flag to enable not rescuing the errors.
-
- Example:
-
- # Do not swallow errors in after_commit/after_rollback callbacks.
- config.active_record.raise_in_transactional_callbacks = true
-
- Fixes #13460.
-
- *arthurnn*
-
-* Fixed an issue where custom accessor methods (such as those generated by
- `enum`) with the same name as a global method are incorrectly overridden
- when subclassing.
-
- Fixes #16288.
-
- *Godfrey Chan*
-
-* `*_was` and `changes` now work correctly for in-place attribute changes as
- well.
-
- *Sean Griffin*
-
-* Fix regression on `after_commit` that did not fire with nested transactions.
-
- Fixes #16425.
-
- *arthurnn*
-
-* Do not try to write timestamps when a table has no timestamps columns.
-
- Fixes #8813.
-
- *Sergey Potapov*
-
-* `index_exists?` with `:name` option does verify specified columns.
-
- Example:
-
- add_index :articles, :title, name: "idx_title"
-
- # Before:
- index_exists? :articles, :title, name: "idx_title" # => `true`
- index_exists? :articles, :body, name: "idx_title" # => `true`
-
- # After:
- index_exists? :articles, :title, name: "idx_title" # => `true`
- index_exists? :articles, :body, name: "idx_title" # => `false`
-
- *Yves Senn*, *Matthew Draper*
-
-* When calling `update_columns` on a record that is not persisted, the error
- message now reflects whether that object is a new record or has been
- destroyed.
-
- *Lachlan Sylvester*
-
-* Define `id_was` to get the previous value of the primary key.
-
- Currently when we call `id_was` and we have a custom primary key name,
- Active Record will return the current value of the primary key. This
- makes it impossible to correctly do an update operation if you change the
- id.
-
- Fixes #16413.
-
- *Rafael Mendonça França*
-
-* Deprecate `DatabaseTasks.load_schema` to act on the current connection.
- Use `.load_schema_current` instead. In the future `load_schema` will
- require the `configuration` to act on as an argument.
-
- *Yves Senn*
-
-* Fixed automatic maintaining test schema to properly handle sql structure
- schema format.
-
- Fixes #15394.
-
- *Wojciech Wnętrzak*
-
-* Fix type casting to Decimal from Float with large precision.
-
- *Tomohiro Hashidate*
-
-* Deprecate `Reflection#source_macro`
-
- `Reflection#source_macro` is no longer needed in Active Record
- source so it has been deprecated. Code that used `source_macro`
- was removed in #16353.
-
- *Eileen M. Uchtitelle*, *Aaron Patterson*
-
-* No verbose backtrace by `db:drop` when database does not exist.
-
- Fixes #16295.
-
- *Kenn Ejima*
-
-* Add support for PostgreSQL JSONB.
-
- Example:
-
- create_table :posts do |t|
- t.jsonb :meta_data
- end
-
- *Philippe Creux*, *Chris Teague*
-
-* `db:purge` with MySQL respects `Rails.env`.
-
- *Yves Senn*
-
-* `change_column_default :table, :column, nil` with PostgreSQL will issue a
- `DROP DEFAULT` instead of a `DEFAULT NULL` query.
-
- Fixes #16261.
-
- *Matthew Draper*, *Yves Senn*
-
-* Allow to specify a type for the foreign key column in `references`
- and `add_reference`.
-
- Example:
-
- change_table :vehicle do |t|
- t.references :station, type: :uuid
- end
-
- *Andrey Novikov*, *Łukasz Sarnacki*
-
-* `create_join_table` removes a common prefix when generating the join table.
- This matches the existing behavior of HABTM associations.
-
- Fixes #13683.
-
- *Stefan Kanev*
-
-* Do not swallow errors on `compute_type` when having a bad `alias_method` on
- a class.
-
- *arthurnn*
-
-* PostgreSQL invalid `uuid` are convert to nil.
-
- *Abdelkader Boudih*
-
-* Restore 4.0 behavior for using serialize attributes with `JSON` as coder.
-
- With 4.1.x, `serialize` started returning a string when `JSON` was passed as
- the second attribute. It will now return a hash as per previous versions.
-
- Example:
-
- class Post < ActiveRecord::Base
- serialize :comment, JSON
- end
-
- class Comment
- include ActiveModel::Model
- attr_accessor :category, :text
- end
-
- post = Post.create!
- post.comment = Comment.new(category: "Animals", text: "This is a comment about squirrels.")
- post.save!
-
- # 4.0
- post.comment # => {"category"=>"Animals", "text"=>"This is a comment about squirrels."}
-
- # 4.1 before
- post.comment # => "#<Comment:0x007f80ab48ff98>"
-
- # 4.1 after
- post.comment # => {"category"=>"Animals", "text"=>"This is a comment about squirrels."}
-
- When using `JSON` as the coder in `serialize`, Active Record will use the
- new `ActiveRecord::Coders::JSON` coder which delegates its `dump/load` to
- `ActiveSupport::JSON.encode/decode`. This ensures special objects are dumped
- correctly using the `#as_json` hook.
-
- To keep the previous behaviour, supply a custom coder instead
- ([example](https://gist.github.com/jenncoop/8c4142bbe59da77daa63)).
-
- Fixes #15594.
-
- *Jenn Cooper*
-
-* Do not use `RENAME INDEX` syntax for MariaDB 10.0.
-
- Fixes #15931.
-
- *Jeff Browning*
-
-* Calling `#empty?` on a `has_many` association would use the value from the
- counter cache if one exists.
-
- *David Verhasselt*
-
-* Fix the schema dump generated for tables without constraints and with
- primary key with default value of custom PostgreSQL function result.
-
- Fixes #16111.
-
- *Andrey Novikov*
-
-* Fix the SQL generated when a `delete_all` is run on an association to not
- produce an `IN` statements.
-
- Before:
-
- UPDATE "categorizations" SET "category_id" = NULL WHERE
- "categorizations"."category_id" = 1 AND "categorizations"."id" IN (1, 2)
-
- After:
-
- UPDATE "categorizations" SET "category_id" = NULL WHERE
- "categorizations"."category_id" = 1
-
- *Eileen M. Uchitelle, Aaron Patterson*
-
-* Avoid type casting boolean and `ActiveSupport::Duration` values to numeric
- values for string columns. Otherwise, in some database, the string column
- values will be coerced to a numeric allowing false or 0.seconds match any
- string starting with a non-digit.
-
- Example:
-
- App.where(apikey: false) # => SELECT * FROM users WHERE apikey = '0'
-
- *Dylan Thacker-Smith*
-
-* Add a `:required` option to singular associations, providing a nicer
- API for presence validations on associations.
-
- *Sean Griffin*
-
-* Fixed error in `reset_counters` when associations have `select` scope.
- (Call to `count` generates invalid SQL.)
-
- *Cade Truitt*
-
-* After a successful `reload`, `new_record?` is always false.
-
- Fixes #12101.
-
- *Matthew Draper*
-
-* PostgreSQL renaming table doesn't attempt to rename non existent sequences.
-
- *Abdelkader Boudih*
-
-* Move 'dependent: :destroy' handling for `belongs_to`
- from `before_destroy` to `after_destroy` callback chain
-
- Fixes #12380.
-
- *Ivan Antropov*
-
-* Detect in-place modifications on String attributes.
-
- Before this change, an attribute modified in-place had to be marked as
- changed in order for it to be persisted in the database. Now it is no longer
- required.
-
- Before:
-
- user = User.first
- user.name << ' Griffin'
- user.name_will_change!
- user.save
- user.reload.name # => "Sean Griffin"
-
- After:
-
- user = User.first
- user.name << ' Griffin'
- user.save
- user.reload.name # => "Sean Griffin"
-
- *Sean Griffin*
-
-* Add `ActiveRecord::Base#validate!` that raises `RecordInvalid` if the record
- is invalid.
-
- *Bogdan Gusiev*, *Marc Schütz*
-
-* Support for adding and removing foreign keys. Foreign keys are now
- a part of `schema.rb`. This is supported by Mysql2Adapter, MysqlAdapter
- and PostgreSQLAdapter.
-
- Many thanks to *Matthew Higgins* for laying the foundation with his work on
- [foreigner](https://github.com/matthuhiggins/foreigner).
-
- Example:
-
- # within your migrations:
- add_foreign_key :articles, :authors
- remove_foreign_key :articles, :authors
-
- *Yves Senn*
-
-* Fix subtle bugs regarding attribute assignment on models with no primary
- key. `'id'` will no longer be part of the attributes hash.
-
- *Sean Griffin*
-
-* Deprecate automatic counter caches on `has_many :through`. The behavior was
- broken and inconsistent.
-
- *Sean Griffin*
-
-* `preload` preserves readonly flag for associations.
-
- See #15853.
-
- *Yves Senn*
-
-* Assume numeric types have changed if they were assigned to a value that
- would fail numericality validation, regardless of the old value. Previously
- this would only occur if the old value was 0.
-
- Example:
-
- model = Model.create!(number: 5)
- model.number = '5wibble'
- model.number_changed? # => true
-
- Fixes #14731.
-
- *Sean Griffin*
-
-* `reload` no longer merges with the existing attributes.
- The attribute hash is fully replaced. The record is put into the same state
- as it would be with `Model.find(model.id)`.
-
- *Sean Griffin*
-
-* The object returned from `select_all` must respond to `column_types`.
- If this is not the case a `NoMethodError` is raised.
-
- *Sean Griffin*
-
-* Detect in-place modifications of PG array types
-
- *Sean Griffin*
-
-* Add `bin/rake db:purge` task to empty the current database.
-
- *Yves Senn*
-
-* Deprecate `serialized_attributes` without replacement.
-
- *Sean Griffin*
-
-* Correctly extract IPv6 addresses from `DATABASE_URI`: the square brackets
- are part of the URI structure, not the actual host.
-
- Fixes #15705.
-
- *Andy Bakun*, *Aaron Stone*
-
-* Ensure both parent IDs are set on join records when both sides of a
- through association are new.
-
- *Sean Griffin*
-
-* `ActiveRecord::Dirty` now detects in-place changes to mutable values.
- Serialized attributes on ActiveRecord models will no longer save when
- unchanged.
-
- Fixes #8328.
-
- *Sean Griffin*
-
-* `Pluck` now works when selecting columns from different tables with the same
- name.
-
- Fixes #15649.
-
- *Sean Griffin*
-
-* Remove `cache_attributes` and friends. All attributes are cached.
-
- *Sean Griffin*
-
-* Remove deprecated method `ActiveRecord::Base.quoted_locking_column`.
-
- *Akshay Vishnoi*
-
-* `ActiveRecord::FinderMethods.find` with block can handle proc parameter as
- `Enumerable#find` does.
-
- Fixes #15382.
-
- *James Yang*
-
-* Make timezone aware attributes work with PostgreSQL array columns.
-
- Fixes #13402.
-
- *Kuldeep Aggarwal*, *Sean Griffin*
-
-* `ActiveRecord::SchemaMigration` has no primary key regardless of the
- `primary_key_prefix_type` configuration.
-
- Fixes #15051.
-
- *JoseLuis Torres*, *Yves Senn*
-
-* `rake db:migrate:status` works with legacy migration numbers like `00018_xyz.rb`.
-
- Fixes #15538.
-
- *Yves Senn*
-
-* Baseclass becomes! subclass.
-
- Before this change, a record which changed its STI type, could not be
- updated.
-
- Fixes #14785.
-
- *Matthew Draper*, *Earl St Sauver*, *Edo Balvers*
-
-* Remove deprecated `ActiveRecord::Migrator.proper_table_name`. Use the
- `proper_table_name` instance method on `ActiveRecord::Migration` instead.
-
- *Akshay Vishnoi*
-
-* Fix regression on eager loading association based on SQL query rather than
- existing column.
-
- Fixes #15480.
-
- *Lauro Caetano*, *Carlos Antonio da Silva*
-
-* Deprecate returning `nil` from `column_for_attribute` when no column exists.
- It will return a null object in Rails 5.0
-
- *Sean Griffin*
-
-* Implemented `ActiveRecord::Base#pretty_print` to work with PP.
-
- *Ethan*
-
-* Preserve type when dumping PostgreSQL point, bit, bit varying and money
- columns.
-
- *Yves Senn*
-
-* New records remain new after YAML serialization.
-
- *Sean Griffin*
-
-* PostgreSQL support default values for enum types. Fixes #7814.
-
- *Yves Senn*
-
-* PostgreSQL `default_sequence_name` respects schema. Fixes #7516.
-
- *Yves Senn*
-
-* Fixed `columns_for_distinct` of postgresql adapter to work correctly
- with orders without sort direction modifiers.
-
- *Nikolay Kondratyev*
-
-* PostgreSQL `reset_pk_sequence!` respects schemas. Fixes #14719.
-
- *Yves Senn*
-
-* Keep PostgreSQL `hstore` and `json` attributes as `Hash` in `@attributes`.
- Fixes duplication in combination with `store_accessor`.
-
- Fixes #15369.
-
- *Yves Senn*
-
-* `rake railties:install:migrations` respects the order of railties.
-
- *Arun Agrawal*
-
-* Fix redefine a `has_and_belongs_to_many` inside inherited class
- Fixing regression case, where redefining the same `has_and_belongs_to_many`
- definition into a subclass would raise.
-
- Fixes #14983.
-
- *arthurnn*
-
-* Fix `has_and_belongs_to_many` public reflection.
- When defining a `has_and_belongs_to_many`, internally we convert that to two has_many.
- But as `reflections` is a public API, people expect to see the right macro.
-
- Fixes #14682.
-
- *arthurnn*
-
-* Fixed serialization for records with an attribute named `format`.
-
- Fixes #15188.
-
- *Godfrey Chan*
-
-* When a `group` is set, `sum`, `size`, `average`, `minimum` and `maximum`
- on a NullRelation should return a Hash.
-
- *Kuldeep Aggarwal*
-
-* Fixed serialized fields returning serialized data after being updated with
- `update_column`.
-
- *Simon Hørup Eskildsen*
-
-* Fixed polymorphic eager loading when using a String as foreign key.
-
- Fixes #14734.
-
- *Lauro Caetano*
-
-* Change belongs_to touch to be consistent with timestamp updates
-
- If a model is set up with a belongs_to: touch relationship the parent
- record will only be touched if the record was modified. This makes it
- consistent with timestamp updating on the record itself.
-
- *Brock Trappitt*
-
-* Fixed the inferred table name of a `has_and_belongs_to_many` auxiliar
- table inside a schema.
-
- Fixes #14824.
-
- *Eric Chahin*
-
-* Remove unused `:timestamp` type. Transparently alias it to `:datetime`
- in all cases. Fixes inconsistencies when column types are sent outside of
- `ActiveRecord`, such as for XML Serialization.
-
- *Sean Griffin*
-
-* Fix bug that added `table_name_prefix` and `table_name_suffix` to
- extension names in PostgreSQL when migrating.
-
- *Joao Carlos*
-
-* The `:index` option in migrations, which previously was only available for
- `references`, now works with any column types.
-
- *Marc Schütz*
-
-* Add support for counter name to be passed as parameter on `CounterCache::ClassMethods#reset_counters`.
-
- *jnormore*
-
-* Restrict deletion of record when using `delete_all` with `uniq`, `group`, `having`
- or `offset`.
-
- In these cases the generated query ignored them and that caused unintended
- records to be deleted.
-
- Fixes #11985.
-
- *Leandro Facchinetti*
-
-* Floats with limit >= 25 that get turned into doubles in MySQL no longer have
- their limit dropped from the schema.
-
- Fixes #14135.
-
- *Aaron Nelson*
-
-* Fix how to calculate associated class name when using namespaced `has_and_belongs_to_many`
- association.
-
- Fixes #14709.
-
- *Kassio Borges*
-
-* `ActiveRecord::Relation::Merger#filter_binds` now compares equivalent symbols and
- strings in column names as equal.
-
- This fixes a rare case in which more bind values are passed than there are
- placeholders for them in the generated SQL statement, which can make PostgreSQL
- throw a `StatementInvalid` exception.
-
- *Nat Budin*
-
-* Fix `stored_attributes` to correctly merge the details of stored
- attributes defined in parent classes.
-
- Fixes #14672.
-
- *Brad Bennett*, *Jessica Yao*, *Lakshmi Parthasarathy*
-
-* `change_column_default` allows `[]` as argument to `change_column_default`.
-
- Fixes #11586.
-
- *Yves Senn*
-
-* Handle `name` and `"char"` column types in the PostgreSQL adapter.
-
- `name` and `"char"` are special character types used internally by
- PostgreSQL and are used by internal system catalogs. These field types
- can sometimes show up in structure-sniffing queries that feature internal system
- structures or with certain PostgreSQL extensions.
-
- *J Smith*, *Yves Senn*
-
-* Fix `PostgreSQLAdapter::OID::Float#type_cast` to convert Infinity and
- NaN PostgreSQL values into a native Ruby `Float::INFINITY` and `Float::NAN`
-
- Before:
-
- Point.create(value: 1.0/0)
- Point.last.value # => 0.0
-
- After:
-
- Point.create(value: 1.0/0)
- Point.last.value # => Infinity
-
- *Innokenty Mikhailov*
-
-* Allow the PostgreSQL adapter to handle bigserial primary key types again.
-
- Fixes #10410.
-
- *Patrick Robertson*
-
-* Deprecate joining, eager loading and preloading of instance dependent
- associations without replacement. These operations happen before instances
- are created. The current behavior is unexpected and can result in broken
- behavior.
-
- Fixes #15024.
-
- *Yves Senn*
-
-* Fixed has_and_belongs_to_many's CollectionAssociation size calculation.
-
- `has_and_belongs_to_many` should fall back to using the normal CollectionAssociation's
- size calculation if the collection is not cached or loaded.
-
- Fixes #14913, #14914.
-
- *Fred Wu*
-
-* Return a non zero status when running `rake db:migrate:status` and migration table does
- not exist.
-
- *Paul B.*
-
-* Add support for module-level `table_name_suffix` in models.
-
- This makes `table_name_suffix` work the same way as `table_name_prefix` when
- using namespaced models.
-
- *Jenner LaFave*
-
-* Revert the behaviour of `ActiveRecord::Relation#join` changed through 4.0 => 4.1 to 4.0.
-
- In 4.1.0 `Relation#join` is delegated to `Arel#SelectManager`.
- In 4.0 series it is delegated to `Array#join`.
-
- *Bogdan Gusiev*
-
-* Log nil binary column values correctly.
-
- When an object with a binary column is updated with a nil value
- in that column, the SQL logger would throw an exception when trying
- to log that nil value. This only occurs when updating a record
- that already has a non-nil value in that column since an initial nil
- value isn't included in the SQL anyway (at least, when dirty checking
- is enabled.) The column's new value will now be logged as `<NULL binary data>`
- to parallel the existing `<N bytes of binary data>` for non-nil values.
-
- *James Coleman*
-
-* Rails will now pass a custom validation context through to autosave associations
- in order to validate child associations with the same context.
-
- Fixes #13854.
-
- *Eric Chahin*, *Aaron Nelson*, *Kevin Casey*
-
-* Stringify all variables keys of MySQL connection configuration.
-
- When `sql_mode` variable for MySQL adapters set in configuration as `String`
- was ignored and overwritten by strict mode option.
-
- Fixes #14895.
-
- *Paul Nikitochkin*
-
-* Ensure SQLite3 statements are closed on errors.
-
- Fixes #13631.
-
- *Timur Alperovich*
-
-* Give `ActiveRecord::PredicateBuilder` private methods the privacy they deserve.
-
- *Hector Satre*
-
-* When using a custom `join_table` name on a `habtm`, rails was not saving it
- on Reflections. This causes a problem when rails loads fixtures, because it
- uses the reflections to set database with fixtures.
-
- Fixes #14845.
-
- *Kassio Borges*
-
-* Reset the cache when modifying a Relation with cached Arel.
- Additionally display a warning message to make the user aware.
-
- *Yves Senn*
-
-* PostgreSQL should internally use `:datetime` consistently for TimeStamp. Assures
- different spellings of timestamps are treated the same.
-
- Example:
-
- mytimestamp.simplified_type('timestamp without time zone')
- # => :datetime
- mytimestamp.simplified_type('timestamp(6) without time zone')
- # => also :datetime (previously would be :timestamp)
-
- See #14513.
-
- *Jefferson Lai*
-
-* `ActiveRecord::Base.no_touching` no longer triggers callbacks or start empty transactions.
-
- Fixes #14841.
-
- *Lucas Mazza*
-
-* Fix name collision with `Array#select!` with `Relation#select!`.
-
- Fixes #14752.
-
- *Earl St Sauver*
-
-* Fixed unexpected behavior for `has_many :through` associations going through a scoped `has_many`.
-
- If a `has_many` association is adjusted using a scope, and another `has_many :through`
- uses this association, then the scope adjustment is unexpectedly neglected.
-
- Fixes #14537.
-
- *Jan Habermann*
-
-* `@destroyed` should always be set to `false` when an object is duped.
-
- *Kuldeep Aggarwal*
-
-* Fixed `has_many` association to make it support irregular inflections.
-
- Fixes #8928.
-
- *arthurnn*, *Javier Goizueta*
-
-* Fixed a problem where count used with a grouping was not returning a Hash.
-
- Fixes #14721.
-
- *Eric Chahin*
-
-* `sanitize_sql_like` helper method to escape a string for safe use in an SQL
- LIKE statement.
-
- Example:
-
- class Article
- def self.search(term)
- where("title LIKE ?", sanitize_sql_like(term))
- end
- end
-
- Article.search("20% _reduction_")
- # => Query looks like "... title LIKE '20\% \_reduction\_' ..."
-
- *Rob Gilson*, *Yves Senn*
-
-* Do not quote uuid default value on `change_column`.
-
- Fixes #14604.
-
- *Eric Chahin*
-
-* The comparison between `Relation` and `CollectionProxy` should be consistent.
-
- Example:
-
- author.posts == Post.where(author_id: author.id)
- # => true
- Post.where(author_id: author.id) == author.posts
- # => true
-
- Fixes #13506.
-
- *Lauro Caetano*
-
-* Calling `delete_all` on an unloaded `CollectionProxy` no longer
- generates an SQL statement containing each id of the collection:
-
- Before:
-
- DELETE FROM `model` WHERE `model`.`parent_id` = 1
- AND `model`.`id` IN (1, 2, 3...)
-
- After:
-
- DELETE FROM `model` WHERE `model`.`parent_id` = 1
-
- *Eileen M. Uchitelle*, *Aaron Patterson*
-
-* Fixed error for aggregate methods (`empty?`, `any?`, `count`) with `select`
- which created invalid SQL.
-
- Fixes #13648.
-
- *Simon Woker*
-
-* PostgreSQL adapter only warns once for every missing OID per connection.
-
- Fixes #14275.
-
- *Matthew Draper*, *Yves Senn*
-
-* PostgreSQL adapter automatically reloads it's type map when encountering
- unknown OIDs.
-
- Fixes #14678.
-
- *Matthew Draper*, *Yves Senn*
-
-* Fix insertion of records via `has_many :through` association with scope.
-
- Fixes #3548.
-
- *Ivan Antropov*
-
-* Auto-generate stable fixture UUIDs on PostgreSQL.
-
- Fixes #11524.
-
- *Roderick van Domburg*
-
-* Fixed a problem where an enum would overwrite values of another enum
- with the same name in an unrelated class.
-
- Fixes #14607.
-
- *Evan Whalen*
-
-* PostgreSQL and SQLite string columns no longer have a default limit of 255.
-
- Fixes #13435, #9153.
-
- *Vladimir Sazhin*, *Toms Mikoss*, *Yves Senn*
-
-* Make possible to have an association called `records`.
-
- Fixes #11645.
-
- *prathamesh-sonpatki*
-
-* `to_sql` on an association now matches the query that is actually executed, where it
- could previously have incorrectly accrued additional conditions (e.g. as a result of
- a previous query). `CollectionProxy` now always defers to the association scope's
- `arel` method so the (incorrect) inherited one should be entirely concealed.
-
- Fixes #14003.
-
- *Jefferson Lai*
-
-* Block a few default Class methods as scope name.
-
- For instance, this will raise:
-
- scope :public, -> { where(status: 1) }
-
- *arthurnn*
-
-* Fixed error when using `with_options` with lambda.
-
- Fixes #9805.
-
- *Lauro Caetano*
-
-* Switch `sqlite3:///` URLs (which were temporarily
- deprecated in 4.1) from relative to absolute.
-
- If you still want the previous interpretation, you should replace
- `sqlite3:///my/path` with `sqlite3:my/path`.
-
- *Matthew Draper*
-
-* Treat blank UUID values as `nil`.
-
- Example:
-
- Sample.new(uuid_field: '') #=> <Sample id: nil, uuid_field: nil>
-
- *Dmitry Lavrov*
-
-* Enable support for materialized views on PostgreSQL >= 9.3.
-
- *Dave Lee*
-
-* The PostgreSQL adapter supports custom domains. Fixes #14305.
-
- *Yves Senn*
-
-* PostgreSQL `Column#type` is now determined through the corresponding OID.
- The column types stay the same except for enum columns. They no longer have
- `nil` as type but `enum`.
-
- See #7814.
-
- *Yves Senn*
-
-* Fixed error when specifying a non-empty default value on a PostgreSQL array column.
-
- Fixes #10613.
-
- *Luke Steensen*
-
-* Fixed error where .persisted? throws SystemStackError for an unsaved model with a
- custom primary key that didn't save due to validation error.
-
- Fixes #14393.
-
- *Chris Finne*
-
-* Introduce `validate` as an alias for `valid?`.
-
- This is more intuitive when you want to run validations but don't care about the return value.
-
- *Henrik Nyh*
-
-* Create indexes inline in CREATE TABLE for MySQL.
-
- This is important, because adding an index on a temporary table after it has been created
- would commit the transaction.
-
- It also allows creating and dropping indexed tables with fewer queries and fewer permissions
- required.
-
- Example:
-
- create_table :temp, temporary: true, as: "SELECT id, name, zip FROM a_really_complicated_query" do |t|
- t.index :zip
- end
- # => CREATE TEMPORARY TABLE temp (INDEX (zip)) AS SELECT id, name, zip FROM a_really_complicated_query
-
- *Cody Cutrer*, *Steve Rice*, *Rafael Mendonça Franca*
-
-* Use singular table name in generated migrations when
- `ActiveRecord::Base.pluralize_table_names` is `false`.
-
- Fixes #13426.
-
- *Kuldeep Aggarwal*
-
-* `touch` accepts many attributes to be touched at once.
-
- Example:
-
- # touches :signed_at, :sealed_at, and :updated_at/on attributes.
- Photo.last.touch(:signed_at, :sealed_at)
-
- *James Pinto*
-
-* `rake db:structure:dump` only dumps schema information if the schema
- migration table exists.
-
- Fixes #14217.
-
- *Yves Senn*
-
-* Reap connections that were checked out by now-dead threads, instead
- of waiting until they disconnect by themselves. Before this change,
- a suitably constructed series of short-lived threads could starve
- the connection pool, without ever having more than a couple alive at
- the same time.
-
- *Matthew Draper*
-
-* `pk_and_sequence_for` now ensures that only the pg_depend entries
- pointing to pg_class, and thus only sequence objects, are considered.
-
- *Josh Williams*
-
-* `where.not` adds `references` for `includes` like normal `where` calls do.
-
- Fixes #14406.
-
- *Yves Senn*
-
-* Extend fixture `$LABEL` replacement to allow string interpolation.
-
- Example:
-
- martin:
- email: $LABEL@email.com
-
- users(:martin).email # => martin@email.com
-
- *Eric Steele*
-
-* Add support for `Relation` be passed as parameter on `QueryCache#select_all`.
-
- Fixes #14361.
-
- *arthurnn*
-
-* Passing an Active Record object to `find` or `exists?` is now deprecated.
- Call `.id` on the object first.
-
- *Aaron Patterson*
-
-* Only use BINARY for MySQL case sensitive uniqueness check when column has a case insensitive collation.
-
- *Ryuta Kamizono*
-
-* Support for MySQL 5.6 fractional seconds.
-
- *arthurnn*, *Tatsuhiko Miyagawa*
-
-* Support for Postgres `citext` data type enabling case-insensitive where
- values without needing to wrap in UPPER/LOWER sql functions.
-
- *Troy Kruthoff*, *Lachlan Sylvester*
-
-* Only save has_one associations if record has changes.
- Previously after save related callbacks, such as `#after_commit`, were triggered when the has_one
- object did not get saved to the db.
-
- *Alan Kennedy*
-
-* Allow strings to specify the `#order` value.
-
- Example:
-
- Model.order(id: 'asc').to_sql == Model.order(id: :asc).to_sql
-
- *Marcelo Casiraghi*, *Robin Dupret*
-
-* Dynamically register PostgreSQL enum OIDs. This prevents "unknown OID"
- warnings on enum columns.
-
- *Dieter Komendera*
-
-* `includes` is able to detect the right preloading strategy when string
- joins are involved.
-
- Fixes #14109.
-
- *Aaron Patterson*, *Yves Senn*
-
-* Fixed error with validation with enum fields for records where the
- value for any enum attribute is always evaluated as 0 during
- uniqueness validation.
-
- Fixes #14172.
-
- *Vilius Luneckas* *Ahmed AbouElhamayed*
-
-* `before_add` callbacks are fired before the record is saved on
- `has_and_belongs_to_many` associations *and* on `has_many :through`
- associations. Before this change, `before_add` callbacks would be fired
- before the record was saved on `has_and_belongs_to_many` associations, but
- *not* on `has_many :through` associations.
-
- Fixes #14144.
-
-* Fixed STI classes not defining an attribute method if there is a
- conflicting private method defined on its ancestors.
-
- Fixes #11569.
-
- *Godfrey Chan*
-
-* Coerce strings when reading attributes. Fixes #10485.
-
- Example:
-
- book = Book.new(title: 12345)
- book.save!
- book.title # => "12345"
-
- *Yves Senn*
-
-* Deprecate half-baked support for PostgreSQL range values with excluding beginnings.
- We currently map PostgreSQL ranges to Ruby ranges. This conversion is not fully
- possible because the Ruby range does not support excluded beginnings.
-
- The current solution of incrementing the beginning is not correct and is now
- deprecated. For subtypes where we don't know how to increment (e.g. `#succ`
- is not defined) it will raise an `ArgumentException` for ranges with excluding
- beginnings.
-
- *Yves Senn*
-
-* Support for user created range types in PostgreSQL.
-
- *Yves Senn*
-
-Please check [4-1-stable](https://github.com/rails/rails/blob/4-1-stable/activerecord/CHANGELOG.md) for previous changes.
+Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/activerecord/CHANGELOG.md) for previous changes.
diff --git a/activerecord/activerecord.gemspec b/activerecord/activerecord.gemspec
index bc10e96244..471769a962 100644
--- a/activerecord/activerecord.gemspec
+++ b/activerecord/activerecord.gemspec
@@ -7,7 +7,7 @@ Gem::Specification.new do |s|
s.summary = 'Object-relational mapper framework (part of Rails).'
s.description = 'Databases on Rails. Build a persistent domain model by mapping database tables to Ruby classes. Strong conventions for associations, validations, aggregations, migrations, and testing come baked-in.'
- s.required_ruby_version = '>= 1.9.3'
+ s.required_ruby_version = '>= 2.1.0'
s.license = 'MIT'
@@ -24,5 +24,5 @@ Gem::Specification.new do |s|
s.add_dependency 'activesupport', version
s.add_dependency 'activemodel', version
- s.add_dependency 'arel', '>= 6.0.0.beta2', '< 6.1'
+ s.add_dependency 'arel', '~> 6.0'
end
diff --git a/activerecord/examples/performance.rb b/activerecord/examples/performance.rb
index d3546ce948..a5a1f284a0 100644
--- a/activerecord/examples/performance.rb
+++ b/activerecord/examples/performance.rb
@@ -39,8 +39,8 @@ class Exhibit < ActiveRecord::Base
where("notes IS NOT NULL")
end
- def self.look(exhibits) exhibits.each { |e| e.look } end
- def self.feel(exhibits) exhibits.each { |e| e.feel } end
+ def self.look(exhibits) exhibits.each(&:look) end
+ def self.feel(exhibits) exhibits.each(&:feel) end
end
def progress_bar(int); print "." if (int%100).zero? ; end
diff --git a/activerecord/lib/active_record/aggregations.rb b/activerecord/lib/active_record/aggregations.rb
index e576ec4d40..1040e6e3bb 100644
--- a/activerecord/lib/active_record/aggregations.rb
+++ b/activerecord/lib/active_record/aggregations.rb
@@ -230,8 +230,8 @@ module ActiveRecord
private
def reader_method(name, class_name, mapping, allow_nil, constructor)
define_method(name) do
- if @aggregation_cache[name].nil? && (!allow_nil || mapping.any? {|key, _| !read_attribute(key).nil? })
- attrs = mapping.collect {|key, _| read_attribute(key)}
+ if @aggregation_cache[name].nil? && (!allow_nil || mapping.any? {|key, _| !_read_attribute(key).nil? })
+ attrs = mapping.collect {|key, _| _read_attribute(key)}
object = constructor.respond_to?(:call) ?
constructor.call(*attrs) :
class_name.constantize.send(constructor, *attrs)
diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb
index 8911506694..eb21712f96 100644
--- a/activerecord/lib/active_record/associations.rb
+++ b/activerecord/lib/active_record/associations.rb
@@ -57,7 +57,7 @@ module ActiveRecord
through_reflection = reflection.through_reflection
source_reflection_names = reflection.source_reflection_names
source_associations = reflection.through_reflection.klass._reflections.keys
- super("Could not find the source association(s) #{source_reflection_names.collect{ |a| a.inspect }.to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)} in model #{through_reflection.klass}. Try 'has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}, :source => <name>'. Is it one of #{source_associations.to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)}?")
+ super("Could not find the source association(s) #{source_reflection_names.collect(&:inspect).to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)} in model #{through_reflection.klass}. Try 'has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}, :source => <name>'. Is it one of #{source_associations.to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)}?")
end
end
@@ -1700,7 +1700,7 @@ module ActiveRecord
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].each do |k|
+ [:before_add, :after_add, :before_remove, :after_remove, :autosave, :validate, :join_table, :class_name].each do |k|
hm_options[k] = options[k] if options.key? k
end
diff --git a/activerecord/lib/active_record/associations/alias_tracker.rb b/activerecord/lib/active_record/associations/alias_tracker.rb
index a6a1947148..0c3234ed24 100644
--- a/activerecord/lib/active_record/associations/alias_tracker.rb
+++ b/activerecord/lib/active_record/associations/alias_tracker.rb
@@ -57,20 +57,10 @@ module ActiveRecord
end
def aliased_table_for(table_name, aliased_name)
- table_alias = aliased_name_for(table_name, aliased_name)
-
- if table_alias == table_name
- Arel::Table.new(table_name)
- else
- Arel::Table.new(table_name).alias(table_alias)
- end
- end
-
- def aliased_name_for(table_name, aliased_name)
if aliases[table_name].zero?
# If it's zero, we can have our table_name
aliases[table_name] = 1
- table_name
+ Arel::Table.new(table_name)
else
# Otherwise, we need to use an alias
aliased_name = connection.table_alias_for(aliased_name)
@@ -78,11 +68,12 @@ module ActiveRecord
# Update the count
aliases[aliased_name] += 1
- if aliases[aliased_name] > 1
+ table_alias = if aliases[aliased_name] > 1
"#{truncate(aliased_name)}_#{aliases[aliased_name]}"
else
aliased_name
end
+ Arel::Table.new(table_name).alias(table_alias)
end
end
diff --git a/activerecord/lib/active_record/associations/association_scope.rb b/activerecord/lib/active_record/associations/association_scope.rb
index b965230e60..dcbd57e61d 100644
--- a/activerecord/lib/active_record/associations/association_scope.rb
+++ b/activerecord/lib/active_record/associations/association_scope.rb
@@ -11,8 +11,7 @@ module ActiveRecord
end
def bind_value(scope, column, value, alias_tracker)
- substitute = alias_tracker.connection.substitute_at(
- column, scope.bind_values.length)
+ substitute = alias_tracker.connection.substitute_at(column)
scope.bind_values += [[column, @block.call(value)]]
substitute
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 815e8eb97f..092b4ebd2f 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
@@ -98,7 +98,7 @@ module ActiveRecord::Associations::Builder
def middle_options(join_model)
middle_options = {}
- middle_options[:class] = join_model
+ 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]
@@ -110,7 +110,7 @@ module ActiveRecord::Associations::Builder
rhs_options = {}
if options.key? :class_name
- rhs_options[:foreign_key] = options[:class_name].foreign_key
+ rhs_options[:foreign_key] = options[:class_name].to_s.foreign_key
rhs_options[:class_name] = options[:class_name]
end
diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb
index bdfd569be2..7b6aefe345 100644
--- a/activerecord/lib/active_record/associations/collection_association.rb
+++ b/activerecord/lib/active_record/associations/collection_association.rb
@@ -33,7 +33,13 @@ module ActiveRecord
reload
end
- @proxy ||= CollectionProxy.create(klass, self)
+ if owner.new_record?
+ # Cache the proxy separately before the owner has an id
+ # or else a post-save proxy will still lack the id
+ @new_record_proxy ||= CollectionProxy.create(klass, self)
+ else
+ @proxy ||= CollectionProxy.create(klass, self)
+ end
end
# Implements the writer method, e.g. foo.items= for Foo.has_many :items
@@ -56,9 +62,9 @@ module ActiveRecord
# Implements the ids writer method, e.g. foo.item_ids= for Foo.has_many :items
def ids_writer(ids)
pk_type = reflection.primary_key_type
- ids = Array(ids).reject { |id| id.blank? }
+ ids = Array(ids).reject(&:blank?)
ids.map! { |i| pk_type.type_cast_from_user(i) }
- replace(klass.find(ids).index_by { |r| r.id }.values_at(*ids))
+ replace(klass.find(ids).index_by(&:id).values_at(*ids))
end
def reset
@@ -169,8 +175,8 @@ module ActiveRecord
end
# Removes all records from the association without calling callbacks
- # on the associated records. It honors the `:dependent` option. However
- # if the `:dependent` value is `:destroy` then in that case the `:delete_all`
+ # on the associated records. It honors the +:dependent+ option. However
+ # if the +:dependent+ value is +:destroy+ then in that case the +:delete_all+
# deletion strategy for the association is applied.
#
# You can force a particular deletion strategy by passing a parameter.
@@ -283,7 +289,7 @@ module ActiveRecord
elsif !loaded? && !association_scope.group_values.empty?
load_target.size
elsif !loaded? && !association_scope.distinct_value && target.is_a?(Array)
- unsaved_records = target.select { |r| r.new_record? }
+ unsaved_records = target.select(&:new_record?)
unsaved_records.size + count_records
else
count_records
@@ -352,6 +358,7 @@ module ActiveRecord
if owner.new_record?
replace_records(other_array, original_target)
else
+ replace_common_records_in_memory(other_array, original_target)
if other_array != original_target
transaction { replace_records(other_array, original_target) }
end
@@ -379,11 +386,18 @@ module ActiveRecord
target
end
- def add_to_target(record, skip_callbacks = false)
+ def add_to_target(record, skip_callbacks = false, &block)
+ if association_scope.distinct_value
+ index = @target.index(record)
+ end
+ replace_on_target(record, index, skip_callbacks, &block)
+ end
+
+ def replace_on_target(record, index, skip_callbacks)
callback(:before_add, record) unless skip_callbacks
yield(record) if block_given?
- if association_scope.distinct_value && index = @target.index(record)
+ if index
@target[index] = record
else
@target << record
@@ -409,7 +423,8 @@ module ActiveRecord
def get_records
if reflection.scope_chain.any?(&:any?) ||
scope.eager_loading? ||
- klass.current_scope
+ klass.current_scope ||
+ klass.default_scopes.any?
return scope.to_a
end
@@ -491,7 +506,7 @@ module ActiveRecord
def delete_or_destroy(records, method)
records = records.flatten
records.each { |record| raise_on_type_mismatch!(record) }
- existing_records = records.reject { |r| r.new_record? }
+ existing_records = records.reject(&:new_record?)
if existing_records.empty?
remove_records(existing_records, records, method)
@@ -527,6 +542,14 @@ module ActiveRecord
target
end
+ def replace_common_records_in_memory(new_target, original_target)
+ common_records = new_target & original_target
+ common_records.each do |record|
+ skip_callbacks = true
+ replace_on_target(record, @target.index(record), skip_callbacks)
+ end
+ end
+
def concat_records(records, should_raise = false)
result = true
@@ -586,7 +609,7 @@ module ActiveRecord
# specified, then #find scans the entire collection.
def find_by_scan(*args)
expects_array = args.first.kind_of?(Array)
- ids = args.flatten.compact.map{ |arg| arg.to_s }.uniq
+ ids = args.flatten.compact.map(&:to_s).uniq
if ids.size == 1
id = ids.first
diff --git a/activerecord/lib/active_record/associations/has_many_association.rb b/activerecord/lib/active_record/associations/has_many_association.rb
index 1413efaf7f..93084e0dcf 100644
--- a/activerecord/lib/active_record/associations/has_many_association.rb
+++ b/activerecord/lib/active_record/associations/has_many_association.rb
@@ -66,7 +66,7 @@ module ActiveRecord
# the loaded flag is set to true as well.
def count_records
count = if has_cached_counter?
- owner.read_attribute cached_counter_attribute_name
+ owner._read_attribute cached_counter_attribute_name
else
scope.count
end
diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb
index bde23fc116..3f4d3bfc08 100644
--- a/activerecord/lib/active_record/associations/has_many_through_association.rb
+++ b/activerecord/lib/active_record/associations/has_many_through_association.rb
@@ -20,7 +20,7 @@ module ActiveRecord
# SELECT query will be generated by using #length instead.
def size
if has_cached_counter?
- owner.read_attribute cached_counter_attribute_name(reflection)
+ owner._read_attribute cached_counter_attribute_name(reflection)
elsif loaded?
target.size
else
@@ -161,13 +161,11 @@ module ActiveRecord
if scope.klass.primary_key
count = scope.destroy_all.length
else
- scope.each do |record|
- record._run_destroy_callbacks
- end
+ scope.each(&:_run_destroy_callbacks)
arel = scope.arel
- stmt = Arel::DeleteManager.new arel.engine
+ stmt = Arel::DeleteManager.new
stmt.from scope.klass.arel_table
stmt.wheres = arel.constraints
diff --git a/activerecord/lib/active_record/associations/join_dependency.rb b/activerecord/lib/active_record/associations/join_dependency.rb
index c5c4edd090..cf63430a97 100644
--- a/activerecord/lib/active_record/associations/join_dependency.rb
+++ b/activerecord/lib/active_record/associations/join_dependency.rb
@@ -20,7 +20,7 @@ module ActiveRecord
end
def columns
- @tables.flat_map { |t| t.column_aliases }
+ @tables.flat_map(&:column_aliases)
end
# An array of [column_name, alias] pairs for the table
@@ -94,7 +94,7 @@ module ActiveRecord
#
def initialize(base, associations, joins)
@alias_tracker = AliasTracker.create(base.connection, joins)
- @alias_tracker.aliased_name_for(base.table_name, base.table_name) # Updates the count for base.table_name to 1
+ @alias_tracker.aliased_table_for(base.table_name, base.table_name) # Updates the count for base.table_name to 1
tree = self.class.make_tree associations
@join_root = JoinBase.new base, build(tree, base)
@join_root.children.each { |child| construct_tables! @join_root, child }
diff --git a/activerecord/lib/active_record/associations/join_dependency/join_association.rb b/activerecord/lib/active_record/associations/join_dependency/join_association.rb
index e7d3c9ba40..5dede5527d 100644
--- a/activerecord/lib/active_record/associations/join_dependency/join_association.rb
+++ b/activerecord/lib/active_record/associations/join_dependency/join_association.rb
@@ -67,7 +67,7 @@ module ActiveRecord
value = foreign_klass.base_class.name
column = klass.columns_hash[reflection.type.to_s]
- substitute = klass.connection.substitute_at(column, bind_values.length)
+ substitute = klass.connection.substitute_at(column)
bind_values.push [column, value]
constraint = constraint.and table[reflection.type].eq substitute
end
diff --git a/activerecord/lib/active_record/associations/preloader.rb b/activerecord/lib/active_record/associations/preloader.rb
index 46bccbf15a..4358f3b581 100644
--- a/activerecord/lib/active_record/associations/preloader.rb
+++ b/activerecord/lib/active_record/associations/preloader.rb
@@ -178,6 +178,7 @@ module ActiveRecord
class NullPreloader
def self.new(klass, owners, reflection, preload_scope); self; end
def self.run(preloader); end
+ def self.preloaded_records; []; end
end
def preloader_for(reflection, owners, rhs_klass)
diff --git a/activerecord/lib/active_record/associations/preloader/association.rb b/activerecord/lib/active_record/associations/preloader/association.rb
index c0639742be..7d6523dbc4 100644
--- a/activerecord/lib/active_record/associations/preloader/association.rb
+++ b/activerecord/lib/active_record/associations/preloader/association.rb
@@ -142,14 +142,8 @@ module ActiveRecord
scope._select! preload_values[:select] || values[:select] || table[Arel.star]
scope.includes! preload_values[:includes] || values[:includes]
-
- if preload_values.key? :order
- scope.order! preload_values[:order]
- else
- if values.key? :order
- scope.order! values[:order]
- end
- end
+ scope.joins! preload_values[:joins] || values[:joins]
+ scope.order! preload_values[:order] || values[:order]
if preload_values[:readonly] || values[:readonly]
scope.readonly!
@@ -159,6 +153,7 @@ module ActiveRecord
scope.where!(klass.table_name => { reflection.type => model.base_class.sti_name })
end
+ scope.unscope_values = Array(values[:unscope])
klass.default_scoped.merge(scope)
end
end
diff --git a/activerecord/lib/active_record/associations/preloader/has_many_through.rb b/activerecord/lib/active_record/associations/preloader/has_many_through.rb
index 7b37b5942d..2029871f39 100644
--- a/activerecord/lib/active_record/associations/preloader/has_many_through.rb
+++ b/activerecord/lib/active_record/associations/preloader/has_many_through.rb
@@ -8,7 +8,7 @@ module ActiveRecord
records_by_owner = super
if reflection_scope.distinct_value
- records_by_owner.each_value { |records| records.uniq! }
+ records_by_owner.each_value(&:uniq!)
end
records_by_owner
diff --git a/activerecord/lib/active_record/associations/singular_association.rb b/activerecord/lib/active_record/associations/singular_association.rb
index c360ef1b2c..c44242a0f0 100644
--- a/activerecord/lib/active_record/associations/singular_association.rb
+++ b/activerecord/lib/active_record/associations/singular_association.rb
@@ -41,7 +41,8 @@ module ActiveRecord
def get_records
if reflection.scope_chain.any?(&:any?) ||
scope.eager_loading? ||
- klass.current_scope
+ klass.current_scope ||
+ klass.default_scopes.any?
return scope.limit(1).to_a
end
diff --git a/activerecord/lib/active_record/attribute_assignment.rb b/activerecord/lib/active_record/attribute_assignment.rb
index 2887db3bf7..bf64830417 100644
--- a/activerecord/lib/active_record/attribute_assignment.rb
+++ b/activerecord/lib/active_record/attribute_assignment.rb
@@ -87,7 +87,7 @@ module ActiveRecord
end
end
unless errors.empty?
- error_descriptions = errors.map { |ex| ex.message }.join(",")
+ error_descriptions = errors.map(&:message).join(",")
raise MultiparameterAssignmentErrors.new(errors), "#{errors.size} error(s) on assignment of multiparameter attributes [#{error_descriptions}]"
end
end
diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb
index 21ddbbcb66..83fcefa64d 100644
--- a/activerecord/lib/active_record/attribute_methods.rb
+++ b/activerecord/lib/active_record/attribute_methods.rb
@@ -332,7 +332,7 @@ module ActiveRecord
# task.attribute_present?(:title) # => true
# task.attribute_present?(:is_done) # => true
def attribute_present?(attribute)
- value = read_attribute(attribute)
+ value = _read_attribute(attribute)
!value.nil? && !(value.respond_to?(:empty?) && value.empty?)
end
@@ -433,7 +433,7 @@ module ActiveRecord
end
def typecasted_attribute_value(name)
- read_attribute(name)
+ _read_attribute(name)
end
end
end
diff --git a/activerecord/lib/active_record/attribute_methods/dirty.rb b/activerecord/lib/active_record/attribute_methods/dirty.rb
index 2f02738f6d..9ba46ec4c7 100644
--- a/activerecord/lib/active_record/attribute_methods/dirty.rb
+++ b/activerecord/lib/active_record/attribute_methods/dirty.rb
@@ -110,7 +110,7 @@ module ActiveRecord
if attribute_changed?(attr)
changed_attributes[attr]
else
- clone_attribute_value(:read_attribute, attr)
+ clone_attribute_value(:_read_attribute, attr)
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 9bd333bbac..c28374e4ab 100644
--- a/activerecord/lib/active_record/attribute_methods/primary_key.rb
+++ b/activerecord/lib/active_record/attribute_methods/primary_key.rb
@@ -17,7 +17,7 @@ module ActiveRecord
def id
if pk = self.class.primary_key
sync_with_transaction_state
- read_attribute(pk)
+ _read_attribute(pk)
end
end
@@ -120,6 +120,7 @@ module ActiveRecord
def primary_key=(value)
@primary_key = value && value.to_s
@quoted_primary_key = nil
+ @attributes_builder = nil
end
end
end
diff --git a/activerecord/lib/active_record/attribute_methods/read.rb b/activerecord/lib/active_record/attribute_methods/read.rb
index bf2a084a00..20f0936e52 100644
--- a/activerecord/lib/active_record/attribute_methods/read.rb
+++ b/activerecord/lib/active_record/attribute_methods/read.rb
@@ -27,7 +27,7 @@ module ActiveRecord
<<-EOMETHOD
def #{method_name}
name = ::ActiveRecord::AttributeMethods::AttrNames::ATTR_#{const_name}
- read_attribute(name) { |n| missing_attribute(n, caller) }
+ _read_attribute(name) { |n| missing_attribute(n, caller) }
end
EOMETHOD
end
@@ -64,7 +64,7 @@ module ActiveRecord
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) }
+ _read_attribute(name) { |n| missing_attribute(n, caller) }
end
STR
@@ -76,19 +76,27 @@ module ActiveRecord
end
end
+ ID = 'id'.freeze
+
# Returns the value of the attribute identified by <tt>attr_name</tt> after
# it has been typecast (for example, "2004-12-12" in a date column is cast
# to a date object, like Date.new(2004, 12, 12)).
def read_attribute(attr_name, &block)
name = attr_name.to_s
- name = self.class.primary_key if name == 'id'
- @attributes.fetch_value(name, &block)
+ name = self.class.primary_key if name == ID
+ _read_attribute(name, &block)
+ end
+
+ # This method exists to avoid the expensive primary_key check internally, without
+ # breaking compatibility with the read_attribute API
+ def _read_attribute(attr_name) # :nodoc:
+ @attributes.fetch_value(attr_name.to_s) { |n| yield n if block_given? }
end
private
def attribute(attribute_name)
- read_attribute(attribute_name)
+ _read_attribute(attribute_name)
end
end
end
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 b7fe079ef5..33d9d2002c 100644
--- a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
+++ b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
@@ -1,7 +1,7 @@
module ActiveRecord
module AttributeMethods
module TimeZoneConversion
- class TimeZoneConverter < SimpleDelegator # :nodoc:
+ class TimeZoneConverter < DelegateClass(Type::Value) # :nodoc:
include Type::Decorator
def type_cast_from_database(value)
diff --git a/activerecord/lib/active_record/attribute_set.rb b/activerecord/lib/active_record/attribute_set.rb
index 98ac63c7e1..6b1d7ea79e 100644
--- a/activerecord/lib/active_record/attribute_set.rb
+++ b/activerecord/lib/active_record/attribute_set.rb
@@ -2,8 +2,6 @@ require 'active_record/attribute_set/builder'
module ActiveRecord
class AttributeSet # :nodoc:
- delegate :keys, to: :initialized_attributes
-
def initialize(attributes)
@attributes = attributes
end
@@ -25,8 +23,12 @@ module ActiveRecord
attributes.key?(name) && self[name].initialized?
end
- def fetch_value(name, &block)
- self[name].value(&block)
+ def keys
+ attributes.initialized_keys
+ end
+
+ def fetch_value(name)
+ self[name].value { |n| yield n if block_given? }
end
def write_from_database(name, value)
@@ -43,7 +45,7 @@ module ActiveRecord
end
def initialize_dup(_)
- @attributes = attributes.transform_values(&:dup)
+ @attributes = attributes.dup
super
end
@@ -58,12 +60,6 @@ module ActiveRecord
end
end
- def ensure_initialized(key)
- unless self[key].initialized?
- write_from_database(key, nil)
- end
- end
-
protected
attr_reader :attributes
diff --git a/activerecord/lib/active_record/attribute_set/builder.rb b/activerecord/lib/active_record/attribute_set/builder.rb
index d4a787f2fe..05138ae36d 100644
--- a/activerecord/lib/active_record/attribute_set/builder.rb
+++ b/activerecord/lib/active_record/attribute_set/builder.rb
@@ -1,35 +1,84 @@
module ActiveRecord
class AttributeSet # :nodoc:
class Builder # :nodoc:
- attr_reader :types
+ attr_reader :types, :always_initialized
- def initialize(types)
+ def initialize(types, always_initialized = nil)
@types = types
+ @always_initialized = always_initialized
end
def build_from_database(values = {}, additional_types = {})
- attributes = build_attributes_from_values(values, additional_types)
- add_uninitialized_attributes(attributes)
+ if always_initialized && !values.key?(always_initialized)
+ values[always_initialized] = nil
+ end
+
+ attributes = LazyAttributeHash.new(types, values, additional_types)
AttributeSet.new(attributes)
end
+ end
+ end
- private
+ class LazyAttributeHash # :nodoc:
+ delegate :select, :transform_values, to: :materialize
- def build_attributes_from_values(values, additional_types)
- values.each_with_object({}) do |(name, value), hash|
- type = additional_types.fetch(name, types[name])
- hash[name] = Attribute.from_database(name, value, type)
- end
+ def initialize(types, values, additional_types)
+ @types = types
+ @values = values
+ @additional_types = additional_types
+ @materialized = false
+ @delegate_hash = {}
+ end
+
+ def key?(key)
+ delegate_hash.key?(key) || values.key?(key) || types.key?(key)
+ end
+
+ def [](key)
+ delegate_hash[key] || assign_default_value(key)
+ end
+
+ def []=(key, value)
+ if frozen?
+ raise RuntimeError, "Can't modify frozen hash"
+ end
+ delegate_hash[key] = value
+ end
+
+ def initialized_keys
+ delegate_hash.keys | values.keys
+ end
+
+ def initialize_dup(_)
+ @delegate_hash = delegate_hash.transform_values(&:dup)
+ super
+ end
+
+ protected
+
+ attr_reader :types, :values, :additional_types, :delegate_hash
+
+ private
+
+ 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] = Attribute.uninitialized(name, type)
end
+ end
- def add_uninitialized_attributes(attributes)
- types.each_key do |name|
- next if attributes.key? name
- type = types[name]
- attributes[name] =
- Attribute.uninitialized(name, type)
- end
+ def materialize
+ unless @materialized
+ values.each_key { |key| self[key] }
+ types.each_key { |key| self[key] }
+ @materialized = true
end
+ delegate_hash
end
end
end
diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb
index a0d70435fa..c39b045a5e 100644
--- a/activerecord/lib/active_record/autosave_association.rb
+++ b/activerecord/lib/active_record/autosave_association.rb
@@ -263,9 +263,9 @@ module ActiveRecord
if new_record
association && association.target
elsif autosave
- association.target.find_all { |record| record.changed_for_autosave? }
+ association.target.find_all(&:changed_for_autosave?)
else
- association.target.find_all { |record| record.new_record? }
+ association.target.find_all(&:new_record?)
end
end
@@ -275,7 +275,7 @@ module ActiveRecord
self.class._reflections.values.any? do |reflection|
if reflection.options[:autosave]
association = association_instance_get(reflection.name)
- association && Array.wrap(association.target).any? { |a| a.changed_for_autosave? }
+ association && Array.wrap(association.target).any?(&:changed_for_autosave?)
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 46812b75bb..3a9db4a109 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
@@ -320,9 +320,7 @@ module ActiveRecord
checkin conn
conn.disconnect! if conn.requires_reloading?
end
- @connections.delete_if do |conn|
- conn.requires_reloading?
- end
+ @connections.delete_if(&:requires_reloading?)
@available.clear
@connections.each do |conn|
@available.add conn
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
index 1a3ed28d66..12b16b2473 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
@@ -287,10 +287,6 @@ module ActiveRecord
"DEFAULT VALUES"
end
- def limited_update_conditions(where_sql, quoted_table_name, quoted_primary_key)
- "WHERE #{quoted_primary_key} IN (SELECT #{quoted_primary_key} FROM #{quoted_table_name} #{where_sql})"
- end
-
# Sanitizes the given LIMIT parameter in order to prevent SQL injection.
#
# The +limit+ may be anything that can evaluate to a string via #to_s. It
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb
index 6bab260f5a..5c95b95184 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb
@@ -15,9 +15,7 @@ module ActiveRecord
end
def visit_AddColumn(o)
- sql_type = type_to_sql(o.type, o.limit, o.precision, o.scale)
- sql = "ADD #{quote_column_name(o.name)} #{sql_type}"
- add_column_options!(sql, column_options(o))
+ "ADD #{accept(o)}"
end
private
@@ -83,7 +81,7 @@ module ActiveRecord
end
def add_column_options!(sql, options)
- sql << " DEFAULT #{quote_value(options[:default], options[:column])}" if options_include_default?(options)
+ sql << " DEFAULT #{quote_default_expression(options[:default], options[:column])}" if options_include_default?(options)
# must explicitly check for :null to allow change_column to work on migrations
if options[:null] == false
sql << " NOT NULL"
@@ -94,7 +92,7 @@ module ActiveRecord
sql
end
- def quote_value(value, column)
+ def quote_default_expression(value, column)
column.sql_type ||= type_to_sql(column.type, column.limit, column.precision, column.scale)
column.cast_type ||= type_for_column(column)
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 f8b6daea5a..d2236d046b 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
@@ -124,8 +124,8 @@ module ActiveRecord
# which is one of the following:
# <tt>:primary_key</tt>, <tt>:string</tt>, <tt>:text</tt>,
# <tt>:integer</tt>, <tt>:float</tt>, <tt>:decimal</tt>,
- # <tt>:datetime</tt>, <tt>:timestamp</tt>, <tt>:time</tt>,
- # <tt>:date</tt>, <tt>:binary</tt>, <tt>:boolean</tt>.
+ # <tt>:datetime</tt>, <tt>:time</tt>, <tt>:date</tt>,
+ # <tt>:binary</tt>, <tt>:boolean</tt>.
#
# You may use a type not in this list as long as it is supported by your
# database (for example, "polygon" in MySQL), but this will not be database
@@ -226,7 +226,7 @@ module ActiveRecord
# t.integer :shop_id, :creator_id
# t.string :item_number, index: true
# t.string :name, :value, default: "Untitled"
- # t.timestamps
+ # t.timestamps null: false
# end
#
# There's a short-hand method for each of the type values declared at the top. And then there's
@@ -287,7 +287,9 @@ module ActiveRecord
end
# Appends <tt>:datetime</tt> columns <tt>:created_at</tt> and
- # <tt>:updated_at</tt> to the table.
+ # <tt>:updated_at</tt> to the table. See SchemaStatements#add_timestamps
+ #
+ # t.timestamps null: false
def timestamps(*args)
options = args.extract_options!
emit_warning_if_null_unspecified(options)
@@ -412,10 +414,10 @@ module ActiveRecord
# end
#
class Table
- include TimestampDefaultDeprecation
+ attr_reader :name
def initialize(table_name, base)
- @table_name = table_name
+ @name = table_name
@base = base
end
@@ -425,12 +427,12 @@ module ActiveRecord
# ====== Creating a simple column
# t.column(:name, :string)
def column(column_name, type, options = {})
- @base.add_column(@table_name, column_name, type, options)
+ @base.add_column(name, column_name, type, options)
end
# Checks to see if a column exists. See SchemaStatements#column_exists?
def column_exists?(column_name, type = nil, options = {})
- @base.column_exists?(@table_name, column_name, type, options)
+ @base.column_exists?(name, column_name, type, options)
end
# Adds a new index to the table. +column_name+ can be a single Symbol, or
@@ -443,27 +445,26 @@ module ActiveRecord
# ====== Creating a named index
# t.index([:branch_id, :party_id], unique: true, name: 'by_branch_party')
def index(column_name, options = {})
- @base.add_index(@table_name, column_name, options)
+ @base.add_index(name, column_name, options)
end
# Checks to see if an index exists. See SchemaStatements#index_exists?
def index_exists?(column_name, options = {})
- @base.index_exists?(@table_name, column_name, options)
+ @base.index_exists?(name, column_name, options)
end
# Renames the given index on the table.
#
# t.rename_index(:user_id, :account_id)
def rename_index(index_name, new_index_name)
- @base.rename_index(@table_name, index_name, new_index_name)
+ @base.rename_index(name, index_name, new_index_name)
end
# Adds timestamps (+created_at+ and +updated_at+) columns to the table. See SchemaStatements#add_timestamps
#
- # t.timestamps
+ # t.timestamps null: false
def timestamps(options = {})
- emit_warning_if_null_unspecified(options)
- @base.add_timestamps(@table_name, options)
+ @base.add_timestamps(name, options)
end
# Changes the column's definition according to the new options.
@@ -472,7 +473,7 @@ module ActiveRecord
# t.change(:name, :string, limit: 80)
# t.change(:description, :text)
def change(column_name, type, options = {})
- @base.change_column(@table_name, column_name, type, options)
+ @base.change_column(name, column_name, type, options)
end
# Sets a new default value for a column. See SchemaStatements#change_column_default
@@ -480,7 +481,7 @@ module ActiveRecord
# t.change_default(:qualification, 'new')
# t.change_default(:authorized, 1)
def change_default(column_name, default)
- @base.change_column_default(@table_name, column_name, default)
+ @base.change_column_default(name, column_name, default)
end
# Removes the column(s) from the table definition.
@@ -488,7 +489,7 @@ module ActiveRecord
# t.remove(:qualification)
# t.remove(:qualification, :experience)
def remove(*column_names)
- @base.remove_columns(@table_name, *column_names)
+ @base.remove_columns(name, *column_names)
end
# Removes the given index from the table.
@@ -502,21 +503,21 @@ module ActiveRecord
# ====== Remove the index named by_branch_party in the table_name table
# t.remove_index name: :by_branch_party
def remove_index(options = {})
- @base.remove_index(@table_name, options)
+ @base.remove_index(name, options)
end
# Removes the timestamp columns (+created_at+ and +updated_at+) from the table.
#
# t.remove_timestamps
def remove_timestamps
- @base.remove_timestamps(@table_name)
+ @base.remove_timestamps(name)
end
# Renames a column.
#
# t.rename(:description, :name)
def rename(column_name, new_column_name)
- @base.rename_column(@table_name, column_name, new_column_name)
+ @base.rename_column(name, column_name, new_column_name)
end
# Adds a reference. Optionally adds a +type+ column, if <tt>:polymorphic</tt> option is provided.
@@ -531,7 +532,7 @@ module ActiveRecord
def references(*args)
options = args.extract_options!
args.each do |ref_name|
- @base.add_reference(@table_name, ref_name, options)
+ @base.add_reference(name, ref_name, options)
end
end
alias :belongs_to :references
@@ -546,7 +547,7 @@ module ActiveRecord
def remove_references(*args)
options = args.extract_options!
args.each do |ref_name|
- @base.remove_reference(@table_name, ref_name, options)
+ @base.remove_reference(name, ref_name, options)
end
end
alias :remove_belongs_to :remove_references
@@ -558,8 +559,8 @@ module ActiveRecord
[:string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean].each do |column_type|
define_method column_type do |*args|
options = args.extract_options!
- args.each do |name|
- @base.add_column(@table_name, name, column_type, options)
+ args.each do |column_name|
+ @base.add_column(name, column_name, column_type, options)
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 cbf87df356..aa7c406050 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
@@ -571,6 +571,9 @@ module ActiveRecord
# rename_index :people, 'index_people_on_last_name', 'index_users_on_last_name'
#
def rename_index(table_name, old_name, new_name)
+ if new_name.length > allowed_index_name_length
+ raise ArgumentError, "Index name '#{new_name}' on table '#{table_name}' is too long; the limit is #{allowed_index_name_length} characters"
+ end
# this is a naive implementation; some DBs may support this more efficiently (Postgres, for instance)
old_index_def = indexes(table_name).detect { |i| i.name == old_name }
return unless old_index_def
@@ -740,7 +743,7 @@ module ActiveRecord
end
fk_name_to_delete = options.fetch(:name) do
- fk_to_delete = foreign_keys(from_table).detect {|fk| fk.column == options[:column] }
+ fk_to_delete = foreign_keys(from_table).detect {|fk| fk.column == options[:column].to_s }
if fk_to_delete
fk_to_delete.name
@@ -778,7 +781,7 @@ module ActiveRecord
version = version.to_i
sm_table = quote_table_name(ActiveRecord::Migrator.schema_migrations_table_name)
- migrated = select_values("SELECT version FROM #{sm_table}").map { |v| v.to_i }
+ migrated = select_values("SELECT version FROM #{sm_table}").map(&:to_i)
paths = migrations_paths.map {|p| "#{p}/[0-9]*_*.rb" }
versions = Dir[*paths].map do |filename|
filename.split('/').last.split('_').first.to_i
@@ -835,11 +838,14 @@ module ActiveRecord
columns
end
- # Adds timestamps (+created_at+ and +updated_at+) columns to the named table.
+ include TimestampDefaultDeprecation
+ # Adds timestamps (+created_at+ and +updated_at+) columns to +table_name+.
+ # Additional options (like <tt>null: false</tt>) are forwarded to #add_column.
#
- # add_timestamps(:suppliers)
+ # add_timestamps(:suppliers, null: false)
#
def add_timestamps(table_name, options = {})
+ emit_warning_if_null_unspecified(options)
add_column table_name, :created_at, :datetime, options
add_column table_name, :updated_at, :datetime, options
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
index 582dd360f0..e0a4af5359 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
@@ -24,6 +24,7 @@ module ActiveRecord
autoload :TableDefinition
autoload :Table
autoload :AlterTable
+ autoload :TimestampDefaultDeprecation
end
autoload_at 'active_record/connection_adapters/abstract/connection_pool' do
@@ -262,10 +263,10 @@ module ActiveRecord
# QUOTING ==================================================
- # Returns a bind substitution value given a bind +index+ and +column+
+ # Returns a bind substitution value given a bind +column+
# NOTE: The column param is currently being used by the sqlserver-adapter
- def substitute_at(column, index = 0)
- Arel::Nodes::BindParam.new '?'
+ def substitute_at(column, _unused = 0)
+ Arel::Nodes::BindParam.new
end
# REFERENTIAL INTEGRITY ====================================
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 7f04e35042..bf16804aa0 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
@@ -285,7 +285,9 @@ module ActiveRecord
end
end
+ #--
# DATABASE STATEMENTS ======================================
+ #++
def clear_cache!
super
@@ -396,7 +398,7 @@ module ActiveRecord
sql << "LIKE #{quote(like)}" if like
execute_and_free(sql, 'SCHEMA') do |result|
- result.collect { |field| field.first }
+ result.collect(&:first)
end
end
@@ -585,14 +587,6 @@ module ActiveRecord
end
end
- def add_column_position!(sql, options)
- if options[:first]
- sql << " FIRST"
- elsif options[:after]
- sql << " AFTER #{quote_column_name(options[:after])}"
- end
- end
-
# SHOW VARIABLES LIKE 'name'
def show_variable(name)
variables = select_all("SHOW VARIABLES LIKE '#{name}'", 'SCHEMA')
@@ -639,10 +633,6 @@ module ActiveRecord
end
end
- def limited_update_conditions(where_sql, quoted_table_name, quoted_primary_key)
- where_sql
- end
-
def strict_mode?
self.class.type_cast_config_to_boolean(@config.fetch(:strict, true))
end
@@ -656,6 +646,8 @@ module ActiveRecord
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)
@@ -680,7 +672,7 @@ module ActiveRecord
m.register_type(%r(enum)i) do |sql_type|
limit = sql_type[/^enum\((.+)\)/i, 1]
.split(',').map{|enum| enum.strip.length - 2}.max
- Type::String.new(limit: limit)
+ MysqlString.new(limit: limit)
end
end
@@ -794,7 +786,7 @@ module ActiveRecord
private
def version
- @version ||= full_version.scan(/^(\d+)\.(\d+)\.(\d+)/).flatten.map { |v| v.to_i }
+ @version ||= full_version.scan(/^(\d+)\.(\d+)\.(\d+)/).flatten.map(&:to_i)
end
def mariadb?
@@ -855,6 +847,26 @@ module ActiveRecord
end
end
end
+
+ class MysqlString < Type::String # :nodoc:
+ def type_cast_for_database(value)
+ case value
+ when true then "1"
+ when false then "0"
+ else super
+ end
+ end
+
+ private
+
+ def cast_value(value)
+ case value
+ when true then "1"
+ when false then "0"
+ else super
+ end
+ end
+ end
end
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/connection_specification.rb b/activerecord/lib/active_record/connection_adapters/connection_specification.rb
index 609ec7dabd..e54e3199ff 100644
--- a/activerecord/lib/active_record/connection_adapters/connection_specification.rb
+++ b/activerecord/lib/active_record/connection_adapters/connection_specification.rb
@@ -234,7 +234,7 @@ module ActiveRecord
end
end
- # Takes the environment such as `:production` or `:development`.
+ # Takes the environment such as +:production+ or +:development+.
# This requires that the @configurations was initialized with a key that
# matches.
#
diff --git a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
index 5b83131f0e..d19bd80576 100644
--- a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
@@ -66,7 +66,9 @@ module ActiveRecord
exception.error_number if exception.respond_to?(:error_number)
end
+ #--
# QUOTING ==================================================
+ #++
def quote_string(string)
@connection.escape(string)
@@ -80,7 +82,9 @@ module ActiveRecord
end
end
+ #--
# CONNECTION MANAGEMENT ====================================
+ #++
def active?
return false unless @connection
@@ -104,7 +108,9 @@ module ActiveRecord
end
end
+ #--
# DATABASE STATEMENTS ======================================
+ #++
def explain(arel, binds = [])
sql = "EXPLAIN #{to_sql(arel, binds.dup)}"
diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
index 3357ed52e5..23d8389abb 100644
--- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
@@ -58,7 +58,7 @@ module ActiveRecord
# * <tt>:encoding</tt> - (Optional) Sets the client encoding by executing "SET NAMES <encoding>" after connection.
# * <tt>:reconnect</tt> - Defaults to false (See MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html).
# * <tt>:strict</tt> - Defaults to true. Enable STRICT_ALL_TABLES. (See MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html)
- # * <tt>:variables</tt> - (Optional) A hash session variables to send as `SET @@SESSION.key = value` on each database connection. Use the value `:default` to set a variable to its DEFAULT value. (See MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/set-statement.html).
+ # * <tt>:variables</tt> - (Optional) A hash session variables to send as <tt>SET @@SESSION.key = value</tt> on each database connection. Use the value +:default+ to set a variable to its DEFAULT value. (See MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/set-statement.html).
# * <tt>:sslca</tt> - Necessary to use MySQL with an SSL connection.
# * <tt>:sslkey</tt> - Necessary to use MySQL with an SSL connection.
# * <tt>:sslcert</tt> - Necessary to use MySQL with an SSL connection.
@@ -137,7 +137,9 @@ module ActiveRecord
@connection.quote(string)
end
+ #--
# CONNECTION MANAGEMENT ====================================
+ #++
def active?
if @connection.respond_to?(:stat)
@@ -178,7 +180,9 @@ module ActiveRecord
end
end
+ #--
# DATABASE STATEMENTS ======================================
+ #++
def select_rows(sql, name = nil, binds = [])
@connection.query_with_result = true
@@ -419,9 +423,7 @@ module ActiveRecord
cols = nil
if metadata = stmt.result_metadata
- cols = cache[:cols] ||= metadata.fetch_fields.map { |field|
- field.name
- }
+ cols = cache[:cols] ||= metadata.fetch_fields.map(&:name)
metadata.free
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 cf379ab210..d09468329a 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb
@@ -156,10 +156,6 @@ module ActiveRecord
end
end
- def substitute_at(column, index = 0)
- Arel::Nodes::BindParam.new "$#{index + 1}"
- end
-
def exec_query(sql, name = 'SQL', binds = [])
execute_and_clear(sql, name, binds) do |result|
types = {}
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb b/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb
index f95f45c689..991c41327f 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb
@@ -14,22 +14,6 @@ module ActiveRecord
@connection.unescape_bytea(value) if value
end
- # Quotes PostgreSQL-specific data types for SQL input.
- def quote(value, column = nil) #:nodoc:
- return super unless column
-
- case value
- when Float
- if value.infinite? || value.nan?
- "'#{value}'"
- else
- super
- end
- else
- super
- end
- end
-
# Quotes strings for use in SQL input.
def quote_string(s) #:nodoc:
@connection.escape(s)
@@ -94,6 +78,12 @@ module ActiveRecord
elsif value.hex?
"X'#{value}'"
end
+ when Float
+ if value.infinite? || value.nan?
+ "'#{value}'"
+ else
+ super
+ end
else
super
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 51853c6812..f29b793a3f 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
@@ -4,12 +4,6 @@ module ActiveRecord
class SchemaCreation < AbstractAdapter::SchemaCreation
private
- def visit_AddColumn(o)
- sql_type = type_to_sql(o.type, o.limit, o.precision, o.scale)
- sql = "ADD COLUMN #{quote_column_name(o.name)} #{sql_type}"
- add_column_options!(sql, column_options(o))
- end
-
def visit_ColumnDefinition(o)
sql = super
if o.primary_key? && o.type != :primary_key
@@ -19,14 +13,22 @@ module ActiveRecord
sql
end
+ def column_options(o)
+ column_options = super
+ column_options[:array] = o.array
+ column_options
+ end
+
def add_column_options!(sql, options)
- if options[:array] || options[:column].try(:array)
+ if options[:array]
sql << '[]'
end
+ super
+ end
- column = options.fetch(:column) { return super }
- if column.type == :uuid && options[:default] =~ /\(\)/
- sql << " DEFAULT #{options[:default]}"
+ def quote_default_expression(value, column)
+ if column.type == :uuid && value =~ /\(\)/
+ value
else
super
end
@@ -411,7 +413,10 @@ module ActiveRecord
pk, seq = pk_and_sequence_for(new_name)
if seq && seq.identifier == "#{table_name}_#{pk}_seq"
new_seq = "#{new_name}_#{pk}_seq"
+ idx = "#{table_name}_pkey"
+ new_idx = "#{new_name}_pkey"
execute "ALTER TABLE #{quote_table_name(seq)} RENAME TO #{quote_table_name(new_seq)}"
+ execute "ALTER INDEX #{quote_table_name(idx)} RENAME TO #{quote_table_name(new_idx)}"
end
rename_table_indexes(table_name, new_name)
@@ -430,7 +435,12 @@ module ActiveRecord
quoted_table_name = quote_table_name(table_name)
sql_type = type_to_sql(type, options[:limit], options[:precision], options[:scale])
sql_type << "[]" if options[:array]
- execute "ALTER TABLE #{quoted_table_name} ALTER COLUMN #{quote_column_name(column_name)} TYPE #{sql_type}"
+ sql = "ALTER TABLE #{quoted_table_name} ALTER COLUMN #{quote_column_name(column_name)} TYPE #{sql_type}"
+ sql << " USING #{options[:using]}" if options[:using]
+ if options[:cast_as]
+ sql << " USING CAST(#{quote_column_name(column_name)} AS #{type_to_sql(options[:cast_as], options[:limit], options[:precision], options[:scale])})"
+ end
+ execute sql
change_column_default(table_name, column_name, options[:default]) if options_include_default?(options)
change_column_null(table_name, column_name, options[:null], options[:default]) if options.key?(:null)
@@ -478,6 +488,9 @@ module ActiveRecord
end
def rename_index(table_name, old_name, new_name)
+ if new_name.length > allowed_index_name_length
+ raise ArgumentError, "Index name '#{new_name}' on table '#{table_name}' is too long; the limit is #{allowed_index_name_length} characters"
+ end
execute "ALTER INDEX #{quote_column_name(old_name)} RENAME TO #{quote_table_name(new_name)}"
end
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/utils.rb b/activerecord/lib/active_record/connection_adapters/postgresql/utils.rb
index 0290bcb48c..9a0b80d7d3 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/utils.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/utils.rb
@@ -18,7 +18,11 @@ module ActiveRecord
end
def quoted
- parts.map { |p| PGconn.quote_ident(p) }.join SEPARATOR
+ if schema
+ PGconn.quote_ident(schema) << SEPARATOR << PGconn.quote_ident(identifier)
+ else
+ PGconn.quote_ident(identifier)
+ end
end
def ==(o)
@@ -32,8 +36,11 @@ module ActiveRecord
protected
def unquote(part)
- return unless part
- part.gsub(/(^"|"$)/,'')
+ if part && part.start_with?('"')
+ part[1..-2]
+ else
+ part
+ end
end
def parts
@@ -57,7 +64,11 @@ module ActiveRecord
# * <tt>"schema_name".table_name</tt>
# * <tt>"schema.name"."table name"</tt>
def extract_schema_qualified_name(string)
- table, schema = string.scan(/[^".\s]+|"[^"]*"/)[0..1].reverse
+ schema, table = string.scan(/[^".\s]+|"[^"]*"/)
+ if table.nil?
+ table = schema
+ schema = nil
+ end
PostgreSQL::Name.new(schema, table)
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
index e472741660..3698957d8d 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
@@ -13,7 +13,7 @@ require 'active_record/connection_adapters/postgresql/database_statements'
require 'arel/visitors/bind_visitor'
# Make sure we're using pg high enough for PGResult#values
-gem 'pg', '~> 0.11'
+gem 'pg', '~> 0.15'
require 'pg'
require 'ipaddr'
@@ -104,6 +104,7 @@ module ActiveRecord
macaddr: { name: "macaddr" },
uuid: { name: "uuid" },
json: { name: "json" },
+ jsonb: { name: "jsonb" },
ltree: { name: "ltree" },
citext: { name: "citext" },
point: { name: "point" },
@@ -124,7 +125,7 @@ module ActiveRecord
PostgreSQL::SchemaCreation.new self
end
- # Adds `:array` option to the default set provided by the
+ # Adds +:array+ option to the default set provided by the
# AbstractAdapter
def prepare_column_options(column, types) # :nodoc:
spec = super
@@ -133,7 +134,7 @@ module ActiveRecord
spec
end
- # Adds `:array` as a valid migration key
+ # Adds +:array+ as a valid migration key
def migration_keys
super + [:array]
end
@@ -595,9 +596,7 @@ module ActiveRecord
}
log(sql, name, type_casted_binds, stmt_key) do
- @connection.send_query_prepared(stmt_key, type_casted_binds.map { |_, val| val })
- @connection.block
- @connection.get_last_result
+ @connection.exec_prepared(stmt_key, type_casted_binds.map { |_, val| val })
end
rescue ActiveRecord::StatementInvalid => e
pgerror = e.original_exception
diff --git a/activerecord/lib/active_record/connection_adapters/schema_cache.rb b/activerecord/lib/active_record/connection_adapters/schema_cache.rb
index a10ce330c7..37ff4e4613 100644
--- a/activerecord/lib/active_record/connection_adapters/schema_cache.rb
+++ b/activerecord/lib/active_record/connection_adapters/schema_cache.rb
@@ -61,9 +61,7 @@ module ActiveRecord
end
def size
- [@columns, @columns_hash, @primary_keys, @tables].map { |x|
- x.size
- }.inject :+
+ [@columns, @columns_hash, @primary_keys, @tables].map(&:size).inject :+
end
# Clear out internal caches for table with +table_name+.
diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
index 1b5e3bdbac..c3865a8fdd 100644
--- a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
@@ -88,11 +88,11 @@ module ActiveRecord
include Comparable
def initialize(version_string)
- @version = version_string.split('.').map { |v| v.to_i }
+ @version = version_string.split('.').map(&:to_i)
end
def <=>(version_string)
- @version <=> version_string.split('.').map { |v| v.to_i }
+ @version <=> version_string.split('.').map(&:to_i)
end
end
@@ -179,10 +179,6 @@ module ActiveRecord
true
end
- def supports_add_column?
- true
- end
-
def supports_views?
true
end
@@ -270,7 +266,9 @@ module ActiveRecord
end
end
+ #--
# DATABASE STATEMENTS ======================================
+ #++
def explain(arel, binds = [])
sql = "EXPLAIN QUERY PLAN #{to_sql(arel, binds)}"
@@ -451,12 +449,12 @@ module ActiveRecord
# See: http://www.sqlite.org/lang_altertable.html
# SQLite has an additional restriction on the ALTER TABLE statement
- def valid_alter_table_options( type, options)
+ def valid_alter_table_type?(type)
type.to_sym != :primary_key
end
def add_column(table_name, column_name, type, options = {}) #:nodoc:
- if supports_add_column? && valid_alter_table_options( type, options )
+ if valid_alter_table_type?(type)
super(table_name, column_name, type, options)
else
alter_table(table_name) do |definition|
@@ -558,7 +556,7 @@ module ActiveRecord
end
copy_table_indexes(from, to, options[:rename] || {})
copy_table_contents(from, to,
- @definition.columns.map {|column| column.name},
+ @definition.columns.map(&:name),
options[:rename] || {})
end
@@ -571,7 +569,7 @@ module ActiveRecord
name = name[1..-1]
end
- to_column_names = columns(to).map { |c| c.name }
+ to_column_names = columns(to).map(&:name)
columns = index.columns.map {|c| rename[c] || c }.select do |column|
to_column_names.include?(column)
end
@@ -588,7 +586,7 @@ module ActiveRecord
def copy_table_contents(from, to, columns, rename = {}) #:nodoc:
column_mappings = Hash[columns.map {|name| [name, name]}]
rename.each { |a| column_mappings[a.last] = a.first }
- from_columns = columns(from).collect {|col| col.name}
+ from_columns = columns(from).collect(&:name)
columns = columns.find_all{|col| from_columns.include?(column_mappings[col])}
quoted_columns = columns.map { |col| quote_column_name(col) } * ','
diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb
index 952aeaa703..c812e7842a 100644
--- a/activerecord/lib/active_record/core.rb
+++ b/activerecord/lib/active_record/core.rb
@@ -235,7 +235,7 @@ module ActiveRecord
# scope :published_and_commented, -> { published.and(self.arel_table[:comments_count].gt(0)) }
# end
def arel_table # :nodoc:
- @arel_table ||= Arel::Table.new(table_name, arel_engine)
+ @arel_table ||= Arel::Table.new(table_name)
end
# Returns the Arel engine.
@@ -536,8 +536,6 @@ module ActiveRecord
end
def init_internals
- @attributes.ensure_initialized(self.class.primary_key)
-
@aggregation_cache = {}
@association_cache = {}
@readonly = false
diff --git a/activerecord/lib/active_record/enum.rb b/activerecord/lib/active_record/enum.rb
index 5958373e88..f053372cfb 100644
--- a/activerecord/lib/active_record/enum.rb
+++ b/activerecord/lib/active_record/enum.rb
@@ -142,7 +142,7 @@ module ActiveRecord
private
def save_changed_attribute(attr_name, old)
if (mapping = self.class.defined_enums[attr_name.to_s])
- value = read_attribute(attr_name)
+ value = _read_attribute(attr_name)
if attribute_changed?(attr_name)
if mapping[old] == value
clear_attribute_changes([attr_name])
diff --git a/activerecord/lib/active_record/errors.rb b/activerecord/lib/active_record/errors.rb
index 5b3fdf16f5..fc28ab585f 100644
--- a/activerecord/lib/active_record/errors.rb
+++ b/activerecord/lib/active_record/errors.rb
@@ -52,10 +52,29 @@ module ActiveRecord
# Raised by ActiveRecord::Base.save! and ActiveRecord::Base.create! methods when record cannot be
# saved because record is invalid.
class RecordNotSaved < ActiveRecordError
+ attr_reader :record
+
+ def initialize(message, record = nil)
+ @record = record
+ super(message)
+ end
end
# Raised by ActiveRecord::Base.destroy! when a call to destroy would return false.
+ #
+ # begin
+ # complex_operation_that_internally_calls_destroy!
+ # rescue ActiveRecord::RecordNotDestroyed => invalid
+ # puts invalid.record.errors
+ # end
+ #
class RecordNotDestroyed < ActiveRecordError
+ attr_reader :record
+
+ def initialize(record)
+ @record = record
+ super()
+ end
end
# Superclass for all database execution errors.
@@ -177,6 +196,7 @@ module ActiveRecord
# offending attribute.
class AttributeAssignmentError < ActiveRecordError
attr_reader :exception, :attribute
+
def initialize(message, exception, attribute)
super(message)
@exception = exception
@@ -189,6 +209,7 @@ module ActiveRecord
# objects, each corresponding to the error while assigning to an attribute.
class MultiparameterAssignmentErrors < ActiveRecordError
attr_reader :errors
+
def initialize(errors)
@errors = errors
end
diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb
index db6421dacb..4732462b05 100644
--- a/activerecord/lib/active_record/fixtures.rb
+++ b/activerecord/lib/active_record/fixtures.rb
@@ -745,7 +745,7 @@ module ActiveRecord
end
def column_names
- @column_names ||= @connection.columns(@table_name).collect { |c| c.name }
+ @column_names ||= @connection.columns(@table_name).collect(&:name)
end
def read_fixture_files(path, model_class)
@@ -806,7 +806,9 @@ module ActiveRecord
def find
if model_class
- model_class.find(fixture[model_class.primary_key])
+ model_class.unscoped do
+ model_class.find(fixture[model_class.primary_key])
+ end
else
raise FixtureClassNotFound, "No class attached to find."
end
@@ -866,7 +868,7 @@ module ActiveRecord
fixture_set_names = Dir["#{fixture_path}/{**,*}/*.{yml}"]
fixture_set_names.map! { |f| f[(fixture_path.to_s.size + 1)..-5] }
else
- fixture_set_names = fixture_set_names.flatten.map { |n| n.to_s }
+ fixture_set_names = fixture_set_names.flatten.map(&:to_s)
end
self.fixture_table_names |= fixture_set_names
@@ -906,7 +908,7 @@ module ActiveRecord
def uses_transaction(*methods)
@uses_transaction = [] unless defined?(@uses_transaction)
- @uses_transaction.concat methods.map { |m| m.to_s }
+ @uses_transaction.concat methods.map(&:to_s)
end
def uses_transaction?(method)
diff --git a/activerecord/lib/active_record/gem_version.rb b/activerecord/lib/active_record/gem_version.rb
index e820835626..a388b529c9 100644
--- a/activerecord/lib/active_record/gem_version.rb
+++ b/activerecord/lib/active_record/gem_version.rb
@@ -5,10 +5,10 @@ module ActiveRecord
end
module VERSION
- MAJOR = 4
- MINOR = 2
+ MAJOR = 5
+ MINOR = 0
TINY = 0
- PRE = "beta4"
+ PRE = "alpha"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/activerecord/lib/active_record/inheritance.rb b/activerecord/lib/active_record/inheritance.rb
index f58145ab05..b91e9ac137 100644
--- a/activerecord/lib/active_record/inheritance.rb
+++ b/activerecord/lib/active_record/inheritance.rb
@@ -192,7 +192,7 @@ module ActiveRecord
def type_condition(table = arel_table)
sti_column = table[inheritance_column]
- sti_names = ([self] + descendants).map { |model| model.sti_name }
+ sti_names = ([self] + descendants).map(&:sti_name)
sti_column.in(sti_names)
end
diff --git a/activerecord/lib/active_record/locking/optimistic.rb b/activerecord/lib/active_record/locking/optimistic.rb
index 52eeb8ae1f..ced694ba9a 100644
--- a/activerecord/lib/active_record/locking/optimistic.rb
+++ b/activerecord/lib/active_record/locking/optimistic.rb
@@ -120,7 +120,7 @@ module ActiveRecord
if locking_enabled?
column_name = self.class.locking_column
column = self.class.columns_hash[column_name]
- substitute = self.class.connection.substitute_at(column, relation.bind_values.length)
+ substitute = self.class.connection.substitute_at(column)
relation = relation.where(self.class.arel_table[column_name].eq(substitute))
relation.bind_values << [column, self[column_name].to_i]
diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb
index 2024b225e4..3cac465440 100644
--- a/activerecord/lib/active_record/migration.rb
+++ b/activerecord/lib/active_record/migration.rb
@@ -184,8 +184,8 @@ module ActiveRecord
# you wish to downgrade. Alternatively, you can also use the STEP option if you
# wish to rollback last few migrations. <tt>rake db:migrate STEP=2</tt> will rollback
# the latest two migrations.
- #
- # If any of the migrations throw an <tt>ActiveRecord::IrreversibleMigration</tt> exception,
+ #
+ # If any of the migrations throw an <tt>ActiveRecord::IrreversibleMigration</tt> exception,
# that step will fail and you'll have some manual work to do.
#
# == Database support
@@ -395,7 +395,14 @@ module ActiveRecord
def load_schema_if_pending!
if ActiveRecord::Migrator.needs_migration? || !ActiveRecord::Migrator.any_migrations?
- ActiveRecord::Tasks::DatabaseTasks.load_schema_current_if_exists
+ # Roundrip to Rake to allow plugins to hook into database initialization.
+ FileUtils.cd Rails.root do
+ current_config = Base.connection_config
+ Base.clear_all_connections!
+ system("bin/rake db:test:prepare")
+ # Establish a new connection, the old database may be gone (db:test:prepare uses purge)
+ Base.establish_connection(current_config)
+ end
check_pending!
end
end
@@ -640,7 +647,7 @@ module ActiveRecord
end
def method_missing(method, *arguments, &block)
- arg_list = arguments.map{ |a| a.inspect } * ', '
+ arg_list = arguments.map(&:inspect) * ', '
say_with_time "#{method}(#{arg_list})" do
unless @connection.respond_to? :revert
diff --git a/activerecord/lib/active_record/model_schema.rb b/activerecord/lib/active_record/model_schema.rb
index a444aac23c..92ad9c9101 100644
--- a/activerecord/lib/active_record/model_schema.rb
+++ b/activerecord/lib/active_record/model_schema.rb
@@ -231,7 +231,7 @@ module ActiveRecord
end
def attributes_builder # :nodoc:
- @attributes_builder ||= AttributeSet::Builder.new(column_types)
+ @attributes_builder ||= AttributeSet::Builder.new(column_types, primary_key)
end
def column_types # :nodoc:
@@ -257,7 +257,7 @@ module ActiveRecord
# Returns an array of column names as strings.
def column_names
- @column_names ||= columns.map { |column| column.name }
+ @column_names ||= columns.map(&:name)
end
# Returns an array of column objects where the primary id, all columns ending in "_id" or "_count",
diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb
index 755ff2b2f1..99e104598b 100644
--- a/activerecord/lib/active_record/persistence.rb
+++ b/activerecord/lib/active_record/persistence.rb
@@ -139,7 +139,7 @@ module ActiveRecord
# Attributes marked as readonly are silently ignored if the record is
# being updated.
def save!(*)
- create_or_update || raise(RecordNotSaved)
+ create_or_update || raise(RecordNotSaved.new(nil, self))
end
# Deletes the record in the database and freezes this instance to
@@ -166,7 +166,7 @@ module ActiveRecord
# and <tt>destroy</tt> returns +false+. See
# ActiveRecord::Callbacks for further details.
def destroy
- raise ReadOnlyRecord if readonly?
+ raise ReadOnlyRecord, "#{self.class} is marked as readonly" if readonly?
destroy_associations
destroy_row if persisted?
@destroyed = true
@@ -181,7 +181,7 @@ module ActiveRecord
# and <tt>destroy!</tt> raises ActiveRecord::RecordNotDestroyed. See
# ActiveRecord::Callbacks for further details.
def destroy!
- destroy || raise(ActiveRecord::RecordNotDestroyed)
+ destroy || raise(ActiveRecord::RecordNotDestroyed, self)
end
# Returns an instance of the specified +klass+ with the attributes of the
@@ -487,7 +487,7 @@ module ActiveRecord
def relation_for_destroy
pk = self.class.primary_key
column = self.class.columns_hash[pk]
- substitute = self.class.connection.substitute_at(column, 0)
+ substitute = self.class.connection.substitute_at(column)
relation = self.class.unscoped.where(
self.class.arel_table[pk].eq(substitute))
@@ -497,7 +497,7 @@ module ActiveRecord
end
def create_or_update
- raise ReadOnlyRecord if readonly?
+ raise ReadOnlyRecord, "#{self.class} is marked as readonly" if readonly?
result = new_record? ? _create_record : _update_record
result != false
end
diff --git a/activerecord/lib/active_record/railtie.rb b/activerecord/lib/active_record/railtie.rb
index a4ceacbf44..f1bdbc845c 100644
--- a/activerecord/lib/active_record/railtie.rb
+++ b/activerecord/lib/active_record/railtie.rb
@@ -36,8 +36,6 @@ module ActiveRecord
config.eager_load_namespaces << ActiveRecord
rake_tasks do
- require "active_record/base"
-
namespace :db do
task :load_config do
ActiveRecord::Tasks::DatabaseTasks.database_configuration = Rails.application.config.database_configuration
diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake
index 3ec25f9f17..6c09456c4d 100644
--- a/activerecord/lib/active_record/railties/databases.rake
+++ b/activerecord/lib/active_record/railties/databases.rake
@@ -305,7 +305,7 @@ db_namespace = namespace :db do
end
# desc "Recreate the test database from the current schema"
- task :load => %w(db:test:deprecated db:test:purge) do
+ task :load => %w(db:test:purge) do
case ActiveRecord::Base.schema_format
when :ruby
db_namespace["test:load_schema"].invoke
@@ -315,7 +315,7 @@ db_namespace = namespace :db do
end
# desc "Recreate the test database from an existent schema.rb file"
- task :load_schema => %w(db:test:deprecated db:test:purge) do
+ task :load_schema => %w(db:test:purge) do
begin
should_reconnect = ActiveRecord::Base.connection_pool.active_connection?
ActiveRecord::Schema.verbose = false
@@ -328,7 +328,7 @@ db_namespace = namespace :db do
end
# desc "Recreate the test database from an existent structure.sql file"
- task :load_structure => %w(db:test:deprecated db:test:purge) do
+ task :load_structure => %w(db:test:purge) do
ActiveRecord::Tasks::DatabaseTasks.load_schema_for ActiveRecord::Base.configurations['test'], :sql, ENV['SCHEMA']
end
@@ -349,12 +349,12 @@ db_namespace = namespace :db do
task :clone_structure => %w(db:test:deprecated db:structure:dump db:test:load_structure)
# desc "Empty the test database"
- task :purge => %w(db:test:deprecated environment load_config) do
+ task :purge => %w(environment load_config) do
ActiveRecord::Tasks::DatabaseTasks.purge ActiveRecord::Base.configurations['test']
end
# desc 'Check for pending migrations and load the test schema'
- task :prepare => %w(db:test:deprecated environment load_config) do
+ task :prepare => %w(environment load_config) do
unless ActiveRecord::Base.configurations.blank?
db_namespace['test:load'].invoke
end
@@ -366,7 +366,7 @@ namespace :railties do
namespace :install do
# desc "Copies missing migrations from Railties (e.g. engines). You can specify Railties to use with FROM=railtie1,railtie2"
task :migrations => :'db:load_config' do
- to_load = ENV['FROM'].blank? ? :all : ENV['FROM'].split(",").map {|n| n.strip }
+ to_load = ENV['FROM'].blank? ? :all : ENV['FROM'].split(",").map(&:strip)
railties = {}
Rails.application.migration_railties.each do |railtie|
next unless to_load == :all || to_load.include?(railtie.railtie_name)
diff --git a/activerecord/lib/active_record/readonly_attributes.rb b/activerecord/lib/active_record/readonly_attributes.rb
index 85bbac43e4..ce78f1756d 100644
--- a/activerecord/lib/active_record/readonly_attributes.rb
+++ b/activerecord/lib/active_record/readonly_attributes.rb
@@ -11,7 +11,7 @@ module ActiveRecord
# Attributes listed as readonly will be used to create a new record but update operations will
# ignore these fields.
def attr_readonly(*attributes)
- self._attr_readonly = Set.new(attributes.map { |a| a.to_s }) + (self._attr_readonly || [])
+ self._attr_readonly = Set.new(attributes.map(&:to_s)) + (self._attr_readonly || [])
end
# Returns an array of all the attributes that have been specified as readonly.
diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb
index 4b58f2deb7..96520d1d49 100644
--- a/activerecord/lib/active_record/reflection.rb
+++ b/activerecord/lib/active_record/reflection.rb
@@ -63,7 +63,7 @@ module ActiveRecord
# Returns a Hash of name of the reflection as the key and a AssociationReflection as the value.
#
- # Account.reflections # => {balance: AggregateReflection}
+ # Account.reflections # => {"balance" => AggregateReflection}
#
# @api public
def reflections
@@ -287,7 +287,7 @@ module ActiveRecord
def association_scope_cache(conn, owner)
key = conn.prepared_statements
if polymorphic?
- key = [key, owner.read_attribute(@foreign_type)]
+ key = [key, owner._read_attribute(@foreign_type)]
end
@association_scope_cache[key] ||= @scope_lock.synchronize {
@association_scope_cache[key] ||= yield
@@ -791,7 +791,7 @@ module ActiveRecord
def source_reflection_name # :nodoc:
return @source_reflection_name if @source_reflection_name
- names = [name.to_s.singularize, name].collect { |n| n.to_sym }.uniq
+ names = [name.to_s.singularize, name].collect(&:to_sym).uniq
names = names.find_all { |n|
through_reflection.klass._reflect_on_association(n)
}
diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb
index 03bce4f5b7..7df50f7c97 100644
--- a/activerecord/lib/active_record/relation.rb
+++ b/activerecord/lib/active_record/relation.rb
@@ -84,7 +84,6 @@ module ActiveRecord
um = relation
.arel
.compile_update(substitutes, @klass.primary_key)
- reorder_bind_params(um.ast, bvs)
@klass.connection.update(
um,
@@ -99,7 +98,7 @@ module ActiveRecord
end
substitutes = values.each_with_index.map do |(arel_attr, _), i|
- [arel_attr, @klass.connection.substitute_at(binds[i][0], i)]
+ [arel_attr, @klass.connection.substitute_at(binds[i][0])]
end
[substitutes, binds]
@@ -305,11 +304,11 @@ module ActiveRecord
klass.current_scope = previous
end
- # Updates all records with details given if they match a set of conditions supplied, limits and order can
- # also be supplied. This method constructs a single SQL UPDATE statement and sends it straight to the
- # database. It does not instantiate the involved models and it does not trigger Active Record callbacks
- # or validations. Values passed to `update_all` will not go through ActiveRecord's type-casting behavior.
- # It should receive only values that can be passed as-is to the SQL database.
+ # Updates all records in the current relation with details given. This method constructs a single SQL UPDATE
+ # statement and sends it straight to the database. It does not instantiate the involved models and it does not
+ # trigger Active Record callbacks or validations. Values passed to `update_all` will not go through
+ # ActiveRecord's type-casting behavior. It should receive only values that can be passed as-is to the SQL
+ # database.
#
# ==== Parameters
#
@@ -328,7 +327,7 @@ module ActiveRecord
def update_all(updates)
raise ArgumentError, "Empty list of attributes to change" if updates.blank?
- stmt = Arel::UpdateManager.new(arel.engine)
+ stmt = Arel::UpdateManager.new
stmt.set Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates))
stmt.table(table)
@@ -401,7 +400,7 @@ module ActiveRecord
if conditions
where(conditions).destroy_all
else
- to_a.each {|object| object.destroy }.tap { reset }
+ to_a.each(&:destroy).tap { reset }
end
end
@@ -466,7 +465,7 @@ module ActiveRecord
if conditions
where(conditions).delete_all
else
- stmt = Arel::DeleteManager.new(arel.engine)
+ stmt = Arel::DeleteManager.new
stmt.from(table)
if joins_values.any?
@@ -640,17 +639,21 @@ module ActiveRecord
preload = preload_values
preload += includes_values unless eager_loading?
- preloader = ActiveRecord::Associations::Preloader.new
+ preloader = build_preloader
preload.each do |associations|
preloader.preload @records, associations
end
- @records.each { |record| record.readonly! } if readonly_value
+ @records.each(&:readonly!) if readonly_value
@loaded = true
@records
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)
@@ -663,7 +666,7 @@ module ActiveRecord
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 { |t| t.downcase }.uniq
+ joined_tables = joined_tables.flatten.compact.map(&:downcase).uniq
(references_values - joined_tables).any?
end
@@ -672,7 +675,7 @@ module ActiveRecord
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{ |s| s.downcase }.uniq - ['raw_sql_']
+ string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map(&:downcase).uniq - ['raw_sql_']
end
end
end
diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb
index eacae73ebb..357861caaa 100644
--- a/activerecord/lib/active_record/relation/finder_methods.rb
+++ b/activerecord/lib/active_record/relation/finder_methods.rb
@@ -108,7 +108,7 @@ module ActiveRecord
# Same as +take+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
# is found. Note that <tt>take!</tt> accepts no arguments.
def take!
- take or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql}]")
+ take or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql(@klass.arel_engine)}]")
end
# Find the first record (or first N records if a parameter is supplied).
@@ -176,7 +176,7 @@ module ActiveRecord
# Same as +last+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record
# is found. Note that <tt>last!</tt> accepts no arguments.
def last!
- last or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql}]")
+ last or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql(@klass.arel_engine)}]")
end
# Find the second record.
@@ -323,7 +323,7 @@ module ActiveRecord
# the expected number of results should be provided in the +expected_size+
# argument.
def raise_record_not_found_exception!(ids, result_size, expected_size) #:nodoc:
- conditions = arel.where_sql
+ conditions = arel.where_sql(@klass.arel_engine)
conditions = " [#{conditions}]" if conditions
if Array(ids).size == 1
@@ -415,7 +415,7 @@ module ActiveRecord
end
def using_limitable_reflections?(reflections)
- reflections.none? { |r| r.collection? }
+ reflections.none?(&:collection?)
end
protected
@@ -498,7 +498,7 @@ module ActiveRecord
end
def find_nth!(index)
- find_nth(index, offset_index) or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql}]")
+ find_nth(index, offset_index) or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql(@klass.arel_engine)}]")
end
def find_nth_with_limit(offset, limit)
diff --git a/activerecord/lib/active_record/relation/merger.rb b/activerecord/lib/active_record/relation/merger.rb
index a8febf6a18..a27f990f74 100644
--- a/activerecord/lib/active_record/relation/merger.rb
+++ b/activerecord/lib/active_record/relation/merger.rb
@@ -118,18 +118,6 @@ module ActiveRecord
where_values = kept + rhs_wheres
bind_values = filter_binds(lhs_binds, removed) + rhs_binds
- conn = relation.klass.connection
- bv_index = 0
- where_values.map! do |node|
- if Arel::Nodes::Equality === node && Arel::Nodes::BindParam === node.right
- substitute = conn.substitute_at(bind_values[bv_index].first, bv_index)
- bv_index += 1
- Arel::Nodes::Equality.new(node.left, substitute)
- else
- node
- end
- end
-
relation.where_values = where_values
relation.bind_values = bind_values
diff --git a/activerecord/lib/active_record/relation/predicate_builder.rb b/activerecord/lib/active_record/relation/predicate_builder.rb
index e4b6b49087..938bf55c6d 100644
--- a/activerecord/lib/active_record/relation/predicate_builder.rb
+++ b/activerecord/lib/active_record/relation/predicate_builder.rb
@@ -25,7 +25,7 @@ module ActiveRecord
if value.empty?
queries << '1=0'
else
- table = Arel::Table.new(column, default_table.engine)
+ table = Arel::Table.new(column)
association = klass._reflect_on_association(column)
value.each do |k, v|
@@ -37,7 +37,7 @@ module ActiveRecord
if column.include?('.')
table_name, column = column.split('.', 2)
- table = Arel::Table.new(table_name, default_table.engine)
+ table = Arel::Table.new(table_name)
end
queries.concat expand(klass, table, column, value)
diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb
index a686e3263b..d58af01339 100644
--- a/activerecord/lib/active_record/relation/query_methods.rb
+++ b/activerecord/lib/active_record/relation/query_methods.rb
@@ -427,14 +427,12 @@ module ActiveRecord
# => SELECT "users".* FROM "users" LEFT JOIN bookmarks ON bookmarks.bookmarkable_type = 'Post' AND bookmarks.user_id = users.id
def joins(*args)
check_if_method_has_arguments!(:joins, args)
-
- args.compact!
- args.flatten!
-
spawn.joins!(*args)
end
def joins!(*args) # :nodoc:
+ args.compact!
+ args.flatten!
self.joins_values += args
self
end
@@ -860,7 +858,7 @@ module ActiveRecord
private
def build_arel
- arel = Arel::SelectManager.new(table.engine, table)
+ arel = Arel::SelectManager.new(table)
build_joins(arel, joins_values.flatten) unless joins_values.empty?
@@ -881,19 +879,9 @@ module ActiveRecord
arel.from(build_from) if from_value
arel.lock(lock_value) if lock_value
- # Reorder bind indexes if joins produced bind values
- bvs = arel.bind_values + bind_values
- reorder_bind_params(arel.ast, bvs)
arel
end
- def reorder_bind_params(ast, bvs)
- ast.grep(Arel::Nodes::BindParam).each_with_index do |bp, i|
- column = bvs[i].first
- bp.replace connection.substitute_at(column, i)
- end
- 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(", :")}."
@@ -1069,8 +1057,13 @@ module ActiveRecord
def build_select(arel, selects)
if !selects.empty?
expanded_select = selects.map do |field|
- columns_hash.key?(field.to_s) ? arel_table[field] : field
+ if (Symbol === field || String === field) && columns_hash.key?(field.to_s)
+ arel_table[field]
+ else
+ field
+ end
end
+
arel.project(*expanded_select)
else
arel.project(@klass.arel_table[Arel.star])
diff --git a/activerecord/lib/active_record/sanitization.rb b/activerecord/lib/active_record/sanitization.rb
index 6a130c145b..88dfddebcc 100644
--- a/activerecord/lib/active_record/sanitization.rb
+++ b/activerecord/lib/active_record/sanitization.rb
@@ -93,7 +93,7 @@ sanitize_sql_hash_for_conditions is deprecated, and will be removed in Rails 5.0
attrs = PredicateBuilder.resolve_column_aliases self, attrs
attrs = expand_hash_conditions_for_aggregates(attrs)
- table = Arel::Table.new(table_name, arel_engine).alias(default_table_name)
+ table = Arel::Table.new(table_name).alias(default_table_name)
PredicateBuilder.build_from_hash(self, attrs, table).map { |b|
connection.visitor.compile b
}.join(' AND ')
diff --git a/activerecord/lib/active_record/schema_dumper.rb b/activerecord/lib/active_record/schema_dumper.rb
index 261fb9d992..1dd2cadc01 100644
--- a/activerecord/lib/active_record/schema_dumper.rb
+++ b/activerecord/lib/active_record/schema_dumper.rb
@@ -244,12 +244,7 @@ HEADER
def ignored?(table_name)
['schema_migrations', ignore_tables].flatten.any? do |ignored|
- case ignored
- when String; remove_prefix_and_suffix(table_name) == ignored
- when Regexp; remove_prefix_and_suffix(table_name) =~ ignored
- else
- raise StandardError, 'ActiveRecord::SchemaDumper.ignore_tables accepts an array of String and / or Regexp values.'
- end
+ ignored === remove_prefix_and_suffix(table_name)
end
end
end
diff --git a/activerecord/lib/active_record/scoping/named.rb b/activerecord/lib/active_record/scoping/named.rb
index ec1edf0e01..35420e6551 100644
--- a/activerecord/lib/active_record/scoping/named.rb
+++ b/activerecord/lib/active_record/scoping/named.rb
@@ -139,7 +139,7 @@ module ActiveRecord
# Article.published.featured.latest_article
# Article.featured.titles
def scope(name, body, &block)
- unless body.respond_to?:call
+ unless body.respond_to?(:call)
raise ArgumentError, 'The scope body needs to be callable.'
end
diff --git a/activerecord/lib/active_record/serialization.rb b/activerecord/lib/active_record/serialization.rb
index bd9079b596..48c12dcf9f 100644
--- a/activerecord/lib/active_record/serialization.rb
+++ b/activerecord/lib/active_record/serialization.rb
@@ -11,7 +11,7 @@ module ActiveRecord #:nodoc:
def serializable_hash(options = nil)
options = options.try(:clone) || {}
- options[:except] = Array(options[:except]).map { |n| n.to_s }
+ options[:except] = Array(options[:except]).map(&:to_s)
options[:except] |= Array(self.class.inheritance_column)
super(options)
diff --git a/activerecord/lib/active_record/statement_cache.rb b/activerecord/lib/active_record/statement_cache.rb
index aece446384..192a19f05d 100644
--- a/activerecord/lib/active_record/statement_cache.rb
+++ b/activerecord/lib/active_record/statement_cache.rb
@@ -1,22 +1,33 @@
module ActiveRecord
# Statement cache is used to cache a single statement in order to avoid creating the AST again.
- # Initializing the cache is done by passing the statement in the initialization block:
+ # Initializing the cache is done by passing the statement in the create block:
#
- # cache = ActiveRecord::StatementCache.new do
- # Book.where(name: "my book").limit(100)
+ # cache = StatementCache.create(Book.connection) do |params|
+ # Book.where(name: "my book").where("author_id > 3")
# end
#
# The cached statement is executed by using the +execute+ method:
#
- # cache.execute
+ # cache.execute([], Book, Book.connection)
#
# The relation returned by the block is cached, and for each +execute+ call the cached relation gets duped.
# Database is queried when +to_a+ is called on the relation.
- class StatementCache
- class Substitute; end
+ #
+ # If you want to cache the statement without the values you can use the +bind+ method of the
+ # block parameter.
+ #
+ # cache = StatementCache.create(Book.connection) do |params|
+ # Book.where(name: params.bind)
+ # end
+ #
+ # And pass the bind values as the first argument of +execute+ call.
+ #
+ # cache.execute(["my book"], Book, Book.connection)
+ class StatementCache # :nodoc:
+ class Substitute; end # :nodoc:
- class Query
+ class Query # :nodoc:
def initialize(sql)
@sql = sql
end
@@ -26,7 +37,7 @@ module ActiveRecord
end
end
- class PartialQuery < Query
+ class PartialQuery < Query # :nodoc:
def initialize values
@values = values
@indexes = values.each_with_index.find_all { |thing,i|
@@ -51,11 +62,11 @@ module ActiveRecord
PartialQuery.new collected
end
- class Params
+ class Params # :nodoc:
def bind; Substitute.new; end
end
- class BindMap
+ class BindMap # :nodoc:
def initialize(bind_values)
@indexes = []
@bind_values = bind_values
@@ -68,7 +79,7 @@ module ActiveRecord
end
def bind(values)
- bvs = @bind_values.map { |pair| pair.dup }
+ bvs = @bind_values.map(&:dup)
@indexes.each_with_index { |offset,i| bvs[offset][1] = values[i] }
bvs
end
diff --git a/activerecord/lib/active_record/tasks/mysql_database_tasks.rb b/activerecord/lib/active_record/tasks/mysql_database_tasks.rb
index d890196f47..eafbb2c249 100644
--- a/activerecord/lib/active_record/tasks/mysql_database_tasks.rb
+++ b/activerecord/lib/active_record/tasks/mysql_database_tasks.rb
@@ -31,6 +31,7 @@ module ActiveRecord
end
establish_connection configuration
else
+ $stderr.puts error.inspect
$stderr.puts "Couldn't create database for #{configuration.inspect}, #{creation_options.inspect}"
$stderr.puts "(If you set the charset manually, make sure you have a matching collation)" if configuration['encoding']
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 bf92680268..82d9327fc0 100644
--- a/activerecord/lib/active_record/type/hash_lookup_type_map.rb
+++ b/activerecord/lib/active_record/type/hash_lookup_type_map.rb
@@ -3,16 +3,14 @@ module ActiveRecord
class HashLookupTypeMap < TypeMap # :nodoc:
delegate :key?, to: :@mapping
- def lookup(type, *args)
- @mapping.fetch(type, proc { default_value }).call(type, *args)
+ def alias_type(type, alias_type)
+ register_type(type) { |_, *args| lookup(alias_type, *args) }
end
- def fetch(type, *args, &block)
- @mapping.fetch(type, block).call(type, *args)
- end
+ private
- def alias_type(type, alias_type)
- register_type(type) { |_, *args| lookup(alias_type, *args) }
+ def perform_fetch(type, *args, &block)
+ @mapping.fetch(type, block).call(type, *args)
end
end
end
diff --git a/activerecord/lib/active_record/type/integer.rb b/activerecord/lib/active_record/type/integer.rb
index d69e5b3f28..750f353472 100644
--- a/activerecord/lib/active_record/type/integer.rb
+++ b/activerecord/lib/active_record/type/integer.rb
@@ -14,6 +14,11 @@ module ActiveRecord
alias type_cast_for_database type_cast
+ def type_cast_from_database(value)
+ return if value.nil?
+ value.to_i
+ end
+
protected
attr_reader :range
@@ -33,7 +38,7 @@ module ActiveRecord
def ensure_in_range(value)
unless range.cover?(value)
- raise RangeError, "#{value} is too large for #{self.class} with limit #{limit || 4}"
+ raise RangeError, "#{value} is out of range for #{self.class} with limit #{limit || 4}"
end
end
diff --git a/activerecord/lib/active_record/type/serialized.rb b/activerecord/lib/active_record/type/serialized.rb
index 17004b3593..3191a868ef 100644
--- a/activerecord/lib/active_record/type/serialized.rb
+++ b/activerecord/lib/active_record/type/serialized.rb
@@ -1,6 +1,6 @@
module ActiveRecord
module Type
- class Serialized < SimpleDelegator # :nodoc:
+ class Serialized < DelegateClass(Type::Value) # :nodoc:
include Mutable
include Decorator
diff --git a/activerecord/lib/active_record/type/string.rb b/activerecord/lib/active_record/type/string.rb
index 150defb106..fbc0af2c5a 100644
--- a/activerecord/lib/active_record/type/string.rb
+++ b/activerecord/lib/active_record/type/string.rb
@@ -15,8 +15,8 @@ module ActiveRecord
case value
when ::Numeric, ActiveSupport::Duration then value.to_s
when ::String then ::String.new(value)
- when true then "1"
- when false then "0"
+ when true then "t"
+ when false then "f"
else super
end
end
@@ -25,8 +25,8 @@ module ActiveRecord
def cast_value(value)
case value
- when true then "1"
- when false then "0"
+ when true then "t"
+ when false then "f"
# String.new is slightly faster than dup
else ::String.new(value.to_s)
end
diff --git a/activerecord/lib/active_record/type/type_map.rb b/activerecord/lib/active_record/type/type_map.rb
index 88c5f9c497..09f5ba6b74 100644
--- a/activerecord/lib/active_record/type/type_map.rb
+++ b/activerecord/lib/active_record/type/type_map.rb
@@ -1,24 +1,28 @@
+require 'thread_safe'
+
module ActiveRecord
module Type
class TypeMap # :nodoc:
def initialize
@mapping = {}
+ @cache = ThreadSafe::Cache.new do |h, key|
+ h.fetch_or_store(key, ThreadSafe::Cache.new)
+ end
end
def lookup(lookup_key, *args)
- matching_pair = @mapping.reverse_each.detect do |key, _|
- key === lookup_key
- end
+ fetch(lookup_key, *args) { default_value }
+ end
- if matching_pair
- matching_pair.last.call(lookup_key, *args)
- else
- default_value
+ def fetch(lookup_key, *args, &block)
+ @cache[lookup_key].fetch_or_store(args) do
+ perform_fetch(lookup_key, *args, &block)
end
end
def register_type(key, value = nil, &block)
raise ::ArgumentError unless value || block
+ @cache.clear
if block
@mapping[key] = block
@@ -40,6 +44,18 @@ module ActiveRecord
private
+ 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
+ end
+ end
+
def default_value
@default_value ||= Value.new
end
diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb
index 7f7d49cdb4..a6c8ff7f3a 100644
--- a/activerecord/lib/active_record/validations.rb
+++ b/activerecord/lib/active_record/validations.rb
@@ -5,13 +5,14 @@ module ActiveRecord
# +record+ method to retrieve the record which did not validate.
#
# begin
- # complex_operation_that_calls_save!_internally
+ # complex_operation_that_internally_calls_save!
# rescue ActiveRecord::RecordInvalid => invalid
# puts invalid.record.errors
# end
class RecordInvalid < ActiveRecordError
- attr_reader :record # :nodoc:
- def initialize(record) # :nodoc:
+ attr_reader :record
+
+ def initialize(record)
@record = record
errors = @record.errors.full_messages.join(", ")
super(I18n.t(:"#{@record.class.i18n_scope}.errors.messages.record_invalid", :errors => errors, :default => :"errors.messages.record_invalid"))
diff --git a/activerecord/lib/active_record/validations/presence.rb b/activerecord/lib/active_record/validations/presence.rb
index c7aa814ba8..61b30749d9 100644
--- a/activerecord/lib/active_record/validations/presence.rb
+++ b/activerecord/lib/active_record/validations/presence.rb
@@ -8,7 +8,7 @@ module ActiveRecord
associated_records = Array.wrap(record.send(attribute))
# Superclass validates presence. Ensure present records aren't about to be destroyed.
- if associated_records.present? && associated_records.all? { |r| r.marked_for_destruction? }
+ if associated_records.present? && associated_records.all?(&:marked_for_destruction?)
record.errors.add(attribute, :blank, options)
end
end
diff --git a/activerecord/lib/active_record/validations/uniqueness.rb b/activerecord/lib/active_record/validations/uniqueness.rb
index 2dba4c7b94..3e8afe37a8 100644
--- a/activerecord/lib/active_record/validations/uniqueness.rb
+++ b/activerecord/lib/active_record/validations/uniqueness.rb
@@ -79,7 +79,7 @@ module ActiveRecord
scope_value = record.send(reflection.foreign_key)
scope_item = reflection.foreign_key
else
- scope_value = record.read_attribute(scope_item)
+ scope_value = record._read_attribute(scope_item)
end
relation = relation.and(table[scope_item].eq(scope_value))
end
diff --git a/activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb b/activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb
index f7bf6987c4..fb0fbb4759 100644
--- a/activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb
+++ b/activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb
@@ -15,5 +15,8 @@ class <%= migration_class_name %> < ActiveRecord::Migration
<% attributes_with_index.each do |attribute| -%>
add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %>
<% end -%>
+<% attributes.select(&:reference?).reject(&:polymorphic?).each do |attribute| -%>
+ add_foreign_key :<%= table_name %>, :<%= attribute.name.pluralize %>
+<% end -%>
end
end
diff --git a/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb b/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb
index ae9c74fd05..7df9bcad25 100644
--- a/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb
+++ b/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb
@@ -4,6 +4,9 @@ class <%= migration_class_name %> < ActiveRecord::Migration
<% attributes.each do |attribute| -%>
<%- if attribute.reference? -%>
add_reference :<%= table_name %>, :<%= attribute.name %><%= attribute.inject_options %>
+ <%- unless attribute.polymorphic? -%>
+ add_foreign_key :<%= table_name %>, :<%= attribute.name.pluralize %>
+ <%- end -%>
<%- else -%>
add_column :<%= table_name %>, :<%= attribute.name %>, :<%= attribute.type %><%= attribute.inject_options %>
<%- if attribute.has_index? -%>
@@ -26,6 +29,9 @@ class <%= migration_class_name %> < ActiveRecord::Migration
<%- if migration_action -%>
<%- if attribute.reference? -%>
remove_reference :<%= table_name %>, :<%= attribute.name %><%= attribute.inject_options %>
+ <%- unless attribute.polymorphic? -%>
+ remove_foreign_key :<%= table_name %>, :<%= attribute.name.pluralize %>
+ <%- end -%>
<%- else -%>
<%- if attribute.has_index? -%>
remove_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %>
diff --git a/activerecord/test/cases/adapters/mysql/active_schema_test.rb b/activerecord/test/cases/adapters/mysql/active_schema_test.rb
index a84673e452..413f67da26 100644
--- a/activerecord/test/cases/adapters/mysql/active_schema_test.rb
+++ b/activerecord/test/cases/adapters/mysql/active_schema_test.rb
@@ -92,7 +92,7 @@ class ActiveSchemaTest < ActiveRecord::TestCase
with_real_execute do
begin
ActiveRecord::Base.connection.create_table :delete_me
- ActiveRecord::Base.connection.add_timestamps :delete_me
+ ActiveRecord::Base.connection.add_timestamps :delete_me, null: true
assert column_present?('delete_me', 'updated_at', 'datetime')
assert column_present?('delete_me', 'created_at', 'datetime')
ensure
diff --git a/activerecord/test/cases/adapters/mysql/connection_test.rb b/activerecord/test/cases/adapters/mysql/connection_test.rb
index 3dabb1104a..ce01b16362 100644
--- a/activerecord/test/cases/adapters/mysql/connection_test.rb
+++ b/activerecord/test/cases/adapters/mysql/connection_test.rb
@@ -47,9 +47,7 @@ class MysqlConnectionTest < ActiveRecord::TestCase
assert !@connection.active?
# Repair all fixture connections so other tests won't break.
- @fixture_connections.each do |c|
- c.verify!
- end
+ @fixture_connections.each(&:verify!)
end
def test_successful_reconnection_after_timeout_with_manual_reconnect
@@ -69,8 +67,8 @@ class MysqlConnectionTest < ActiveRecord::TestCase
end
def test_bind_value_substitute
- bind_param = @connection.substitute_at('foo', 0)
- assert_equal Arel.sql('?'), bind_param
+ bind_param = @connection.substitute_at('foo')
+ assert_equal Arel.sql('?'), bind_param.to_sql
end
def test_exec_no_binds
diff --git a/activerecord/test/cases/adapters/mysql/reserved_word_test.rb b/activerecord/test/cases/adapters/mysql/reserved_word_test.rb
index 61ae0abfd1..403f7cbc74 100644
--- a/activerecord/test/cases/adapters/mysql/reserved_word_test.rb
+++ b/activerecord/test/cases/adapters/mysql/reserved_word_test.rb
@@ -101,7 +101,7 @@ class MysqlReservedWordTest < ActiveRecord::TestCase
gs = nil
assert_nothing_raised { gs = Select.find(2).groups }
assert_equal gs.length, 2
- assert(gs.collect{|x| x.id}.sort == [2, 3])
+ assert(gs.collect(&:id).sort == [2, 3])
end
# has_and_belongs_to_many with reserved-word table name
@@ -110,7 +110,7 @@ class MysqlReservedWordTest < ActiveRecord::TestCase
s = nil
assert_nothing_raised { s = Distinct.find(1).selects }
assert_equal s.length, 2
- assert(s.collect{|x|x.id}.sort == [1, 2])
+ assert(s.collect(&:id).sort == [1, 2])
end
# activerecord model introspection with reserved-word table and column names
diff --git a/activerecord/test/cases/adapters/mysql/schema_test.rb b/activerecord/test/cases/adapters/mysql/schema_test.rb
index 87c5277e64..ab547747df 100644
--- a/activerecord/test/cases/adapters/mysql/schema_test.rb
+++ b/activerecord/test/cases/adapters/mysql/schema_test.rb
@@ -81,7 +81,7 @@ module ActiveRecord
table = 'key_tests'
- indexes = @connection.indexes(table).sort_by {|i| i.name}
+ indexes = @connection.indexes(table).sort_by(&:name)
assert_equal 3,indexes.size
index_a = indexes.select{|i| i.name == index_a_name}[0]
diff --git a/activerecord/test/cases/adapters/mysql2/active_schema_test.rb b/activerecord/test/cases/adapters/mysql2/active_schema_test.rb
index 49cfafd7a5..3d97182356 100644
--- a/activerecord/test/cases/adapters/mysql2/active_schema_test.rb
+++ b/activerecord/test/cases/adapters/mysql2/active_schema_test.rb
@@ -92,7 +92,7 @@ class ActiveSchemaTest < ActiveRecord::TestCase
with_real_execute do
begin
ActiveRecord::Base.connection.create_table :delete_me
- ActiveRecord::Base.connection.add_timestamps :delete_me
+ ActiveRecord::Base.connection.add_timestamps :delete_me, null: true
assert column_present?('delete_me', 'updated_at', 'datetime')
assert column_present?('delete_me', 'created_at', 'datetime')
ensure
diff --git a/activerecord/test/cases/adapters/mysql2/connection_test.rb b/activerecord/test/cases/adapters/mysql2/connection_test.rb
index 62c5abbf41..d261e2db55 100644
--- a/activerecord/test/cases/adapters/mysql2/connection_test.rb
+++ b/activerecord/test/cases/adapters/mysql2/connection_test.rb
@@ -44,9 +44,7 @@ class MysqlConnectionTest < ActiveRecord::TestCase
assert !@connection.active?
# Repair all fixture connections so other tests won't break.
- @fixture_connections.each do |c|
- c.verify!
- end
+ @fixture_connections.each(&:verify!)
end
def test_successful_reconnection_after_timeout_with_manual_reconnect
diff --git a/activerecord/test/cases/adapters/mysql2/explain_test.rb b/activerecord/test/cases/adapters/mysql2/explain_test.rb
index 675703caa1..f67f21fab1 100644
--- a/activerecord/test/cases/adapters/mysql2/explain_test.rb
+++ b/activerecord/test/cases/adapters/mysql2/explain_test.rb
@@ -1,5 +1,6 @@
require "cases/helper"
require 'models/developer'
+require 'models/computer'
module ActiveRecord
module ConnectionAdapters
diff --git a/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb
index 799d927ee4..7f97b454bb 100644
--- a/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb
+++ b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb
@@ -100,7 +100,7 @@ class MysqlReservedWordTest < ActiveRecord::TestCase
gs = nil
assert_nothing_raised { gs = Select.find(2).groups }
assert_equal gs.length, 2
- assert(gs.collect{|x| x.id}.sort == [2, 3])
+ assert(gs.collect(&:id).sort == [2, 3])
end
# has_and_belongs_to_many with reserved-word table name
@@ -109,7 +109,7 @@ class MysqlReservedWordTest < ActiveRecord::TestCase
s = nil
assert_nothing_raised { s = Distinct.find(1).selects }
assert_equal s.length, 2
- assert(s.collect{|x|x.id}.sort == [1, 2])
+ assert(s.collect(&:id).sort == [1, 2])
end
# activerecord model introspection with reserved-word table and column names
diff --git a/activerecord/test/cases/adapters/mysql2/schema_test.rb b/activerecord/test/cases/adapters/mysql2/schema_test.rb
index 1b7e60565d..47707b7d4f 100644
--- a/activerecord/test/cases/adapters/mysql2/schema_test.rb
+++ b/activerecord/test/cases/adapters/mysql2/schema_test.rb
@@ -51,7 +51,7 @@ module ActiveRecord
table = 'key_tests'
- indexes = @connection.indexes(table).sort_by {|i| i.name}
+ indexes = @connection.indexes(table).sort_by(&:name)
assert_equal 3,indexes.size
index_a = indexes.select{|i| i.name == index_a_name}[0]
diff --git a/activerecord/test/cases/adapters/postgresql/bytea_test.rb b/activerecord/test/cases/adapters/postgresql/bytea_test.rb
index 7872f91943..aeebec034d 100644
--- a/activerecord/test/cases/adapters/postgresql/bytea_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/bytea_test.rb
@@ -17,7 +17,6 @@ class PostgresqlByteaTest < ActiveRecord::TestCase
end
end
@column = ByteaDataType.columns_hash['payload']
- assert(@column.is_a?(ActiveRecord::ConnectionAdapters::PostgreSQLColumn))
end
teardown do
@@ -25,9 +24,17 @@ class PostgresqlByteaTest < ActiveRecord::TestCase
end
def test_column
+ assert @column.is_a?(ActiveRecord::ConnectionAdapters::PostgreSQLColumn)
assert_equal :binary, @column.type
end
+ def test_binary_columns_are_limitless_the_upper_limit_is_one_GB
+ assert_equal 'bytea', @connection.type_to_sql(:binary, 100_000)
+ assert_raise ActiveRecord::ActiveRecordError do
+ @connection.type_to_sql :binary, 4294967295
+ end
+ end
+
def test_type_cast_binary_converts_the_encoding
assert @column
diff --git a/activerecord/test/cases/adapters/postgresql/change_schema_test.rb b/activerecord/test/cases/adapters/postgresql/change_schema_test.rb
new file mode 100644
index 0000000000..ec1b446dab
--- /dev/null
+++ b/activerecord/test/cases/adapters/postgresql/change_schema_test.rb
@@ -0,0 +1,26 @@
+require 'cases/helper'
+
+module ActiveRecord
+ class Migration
+ class PGChangeSchemaTest < ActiveRecord::TestCase
+ attr_reader :connection
+
+ def setup
+ super
+ @connection = ActiveRecord::Base.connection
+ connection.create_table(:strings) do |t|
+ t.string :somedate
+ end
+ end
+
+ def teardown
+ connection.drop_table :strings
+ end
+
+ def test_change_string_to_date
+ connection.change_column :strings, :somedate, :timestamp, using: 'CAST("somedate" AS timestamp)'
+ assert_equal :datetime, connection.columns(:strings).find { |c| c.name == 'somedate' }.type
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/adapters/postgresql/connection_test.rb b/activerecord/test/cases/adapters/postgresql/connection_test.rb
index 7d179944d4..ab7fd3c6d5 100644
--- a/activerecord/test/cases/adapters/postgresql/connection_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/connection_test.rb
@@ -177,9 +177,7 @@ module ActiveRecord
"successfully querying with the same connection pid."
# Repair all fixture connections so other tests won't break.
- @fixture_connections.each do |c|
- c.verify!
- end
+ @fixture_connections.each(&:verify!)
end
def test_set_session_variable_true
diff --git a/activerecord/test/cases/adapters/postgresql/datatype_test.rb b/activerecord/test/cases/adapters/postgresql/datatype_test.rb
index a0a34e4b87..2c4839338c 100644
--- a/activerecord/test/cases/adapters/postgresql/datatype_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/datatype_test.rb
@@ -94,6 +94,13 @@ class PostgresqlDataTypeTest < ActiveRecord::TestCase
assert @first_oid.reload
assert_equal new_value, @first_oid.obj_id
end
+
+ def test_text_columns_are_limitless_the_upper_limit_is_one_GB
+ assert_equal 'text', @connection.type_to_sql(:text, 100_000)
+ assert_raise ActiveRecord::ActiveRecordError do
+ @connection.type_to_sql :text, 4294967295
+ end
+ end
end
class PostgresqlInternalDataTypeTest < ActiveRecord::TestCase
diff --git a/activerecord/test/cases/adapters/postgresql/enum_test.rb b/activerecord/test/cases/adapters/postgresql/enum_test.rb
index d99c4a292e..83cedc5a7b 100644
--- a/activerecord/test/cases/adapters/postgresql/enum_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/enum_test.rb
@@ -1,8 +1,6 @@
# -*- coding: utf-8 -*-
require "cases/helper"
require 'support/connection_helper'
-require 'active_record/base'
-require 'active_record/connection_adapters/postgresql_adapter'
class PostgresqlEnumTest < ActiveRecord::TestCase
include ConnectionHelper
diff --git a/activerecord/test/cases/adapters/postgresql/explain_test.rb b/activerecord/test/cases/adapters/postgresql/explain_test.rb
index 19053b6732..d2dd04b84b 100644
--- a/activerecord/test/cases/adapters/postgresql/explain_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/explain_test.rb
@@ -1,5 +1,6 @@
require "cases/helper"
require 'models/developer'
+require 'models/computer'
module ActiveRecord
module ConnectionAdapters
diff --git a/activerecord/test/cases/adapters/postgresql/hstore_test.rb b/activerecord/test/cases/adapters/postgresql/hstore_test.rb
index 1296eb72c0..6a9c6483fe 100644
--- a/activerecord/test/cases/adapters/postgresql/hstore_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/hstore_test.rb
@@ -1,41 +1,38 @@
# encoding: utf-8
-
require "cases/helper"
-require 'active_record/base'
-require 'active_record/connection_adapters/postgresql_adapter'
-class PostgresqlHstoreTest < ActiveRecord::TestCase
- class Hstore < ActiveRecord::Base
- self.table_name = 'hstores'
+if ActiveRecord::Base.connection.supports_extensions?
+ class PostgresqlHstoreTest < ActiveRecord::TestCase
+ class Hstore < ActiveRecord::Base
+ self.table_name = 'hstores'
- store_accessor :settings, :language, :timezone
- end
+ store_accessor :settings, :language, :timezone
+ end
- def setup
- @connection = ActiveRecord::Base.connection
+ def setup
+ @connection = ActiveRecord::Base.connection
- unless @connection.extension_enabled?('hstore')
- @connection.enable_extension 'hstore'
- @connection.commit_db_transaction
- end
+ unless @connection.extension_enabled?('hstore')
+ @connection.enable_extension 'hstore'
+ @connection.commit_db_transaction
+ end
- @connection.reconnect!
+ @connection.reconnect!
- @connection.transaction do
- @connection.create_table('hstores') do |t|
- t.hstore 'tags', :default => ''
- t.hstore 'payload', array: true
- t.hstore 'settings'
+ @connection.transaction do
+ @connection.create_table('hstores') do |t|
+ t.hstore 'tags', :default => ''
+ t.hstore 'payload', array: true
+ t.hstore 'settings'
+ end
end
+ @column = Hstore.columns_hash['tags']
end
- @column = Hstore.columns_hash['tags']
- end
- teardown do
- @connection.execute 'drop table if exists hstores'
- end
+ teardown do
+ @connection.execute 'drop table if exists hstores'
+ end
- if ActiveRecord::Base.connection.supports_extensions?
def test_hstore_included_in_extensions
assert @connection.respond_to?(:extensions), "connection should have a list of extensions"
assert @connection.extensions.include?('hstore'), "extension list should include hstore"
@@ -315,10 +312,8 @@ class PostgresqlHstoreTest < ActiveRecord::TestCase
dupe = record.dup
assert_equal({"one" => "two"}, dupe.tags.to_hash)
end
- end
-
- private
+ private
def assert_array_cycle(array)
# test creation
x = Hstore.create!(payload: array)
@@ -346,4 +341,5 @@ class PostgresqlHstoreTest < ActiveRecord::TestCase
x.reload
assert_equal(hash, x.tags)
end
+ end
end
diff --git a/activerecord/test/cases/adapters/postgresql/json_test.rb b/activerecord/test/cases/adapters/postgresql/json_test.rb
index 86ba849445..340ca29c0e 100644
--- a/activerecord/test/cases/adapters/postgresql/json_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/json_test.rb
@@ -1,10 +1,10 @@
# encoding: utf-8
-
require "cases/helper"
-require 'active_record/base'
-require 'active_record/connection_adapters/postgresql_adapter'
+require 'support/schema_dumping_helper'
module PostgresqlJSONSharedTestCases
+ include SchemaDumpingHelper
+
class JsonDataType < ActiveRecord::Base
self.table_name = 'json_data_type'
@@ -64,6 +64,11 @@ module PostgresqlJSONSharedTestCases
JsonDataType.reset_column_information
end
+ def test_schema_dumping
+ output = dump_table_schema("json_data_type")
+ assert_match(/t.#{column_type.to_s}\s+"payload",\s+default: {}/, 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)
diff --git a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb
index a71c0dfb26..c3c696b871 100644
--- a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb
@@ -304,11 +304,8 @@ module ActiveRecord
end
def test_substitute_at
- bind = @connection.substitute_at(nil, 0)
- assert_equal Arel.sql('$1'), bind
-
- bind = @connection.substitute_at(nil, 1)
- assert_equal Arel.sql('$2'), bind
+ bind = @connection.substitute_at(nil)
+ assert_equal Arel.sql('$1'), bind.to_sql
end
def test_partial_index
diff --git a/activerecord/test/cases/adapters/postgresql/rename_table_test.rb b/activerecord/test/cases/adapters/postgresql/rename_table_test.rb
new file mode 100644
index 0000000000..056a035622
--- /dev/null
+++ b/activerecord/test/cases/adapters/postgresql/rename_table_test.rb
@@ -0,0 +1,34 @@
+require "cases/helper"
+
+class PostgresqlRenameTableTest < ActiveRecord::TestCase
+ def setup
+ @connection = ActiveRecord::Base.connection
+ @connection.create_table :before_rename, force: true
+ end
+
+ def teardown
+ @connection.execute 'DROP TABLE IF EXISTS "before_rename"'
+ @connection.execute 'DROP TABLE IF EXISTS "after_rename"'
+ end
+
+ test "renaming a table also renames the primary key index" do
+ # sanity check
+ assert_equal 1, num_indices_named("before_rename_pkey")
+ assert_equal 0, num_indices_named("after_rename_pkey")
+
+ @connection.rename_table :before_rename, :after_rename
+
+ assert_equal 0, num_indices_named("before_rename_pkey")
+ assert_equal 1, num_indices_named("after_rename_pkey")
+ end
+
+ private
+
+ 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
diff --git a/activerecord/test/cases/adapters/postgresql/schema_test.rb b/activerecord/test/cases/adapters/postgresql/schema_test.rb
index 350cb3e065..92c9a13ee3 100644
--- a/activerecord/test/cases/adapters/postgresql/schema_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/schema_test.rb
@@ -412,7 +412,7 @@ class SchemaTest < ActiveRecord::TestCase
def do_dump_index_tests_for_schema(this_schema_name, first_index_column_name, second_index_column_name, third_index_column_name, fourth_index_column_name)
with_schema_search_path(this_schema_name) do
- indexes = @connection.indexes(TABLE_NAME).sort_by {|i| i.name}
+ indexes = @connection.indexes(TABLE_NAME).sort_by(&:name)
assert_equal 4,indexes.size
do_dump_index_assertions_for_one_index(indexes[0], INDEX_A_NAME, first_index_column_name)
diff --git a/activerecord/test/cases/adapters/postgresql/sql_types_test.rb b/activerecord/test/cases/adapters/postgresql/sql_types_test.rb
deleted file mode 100644
index d7d40f6385..0000000000
--- a/activerecord/test/cases/adapters/postgresql/sql_types_test.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-require "cases/helper"
-
-class SqlTypesTest < ActiveRecord::TestCase
- def test_binary_types
- assert_equal 'bytea', type_to_sql(:binary, 100_000)
- assert_raise ActiveRecord::ActiveRecordError do
- type_to_sql :binary, 4294967295
- end
- assert_equal 'text', type_to_sql(:text, 100_000)
- assert_raise ActiveRecord::ActiveRecordError do
- type_to_sql :text, 4294967295
- end
- end
-
- def type_to_sql(*args)
- ActiveRecord::Base.connection.type_to_sql(*args)
- end
-end
diff --git a/activerecord/test/cases/adapters/postgresql/uuid_test.rb b/activerecord/test/cases/adapters/postgresql/uuid_test.rb
index 376dc2490e..5753da1173 100644
--- a/activerecord/test/cases/adapters/postgresql/uuid_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/uuid_test.rb
@@ -1,8 +1,6 @@
# encoding: utf-8
-
require "cases/helper"
-require 'active_record/base'
-require 'active_record/connection_adapters/postgresql_adapter'
+require 'support/schema_dumping_helper'
module PostgresqlUUIDHelper
def connection
@@ -112,6 +110,8 @@ end
class PostgresqlLargeKeysTest < ActiveRecord::TestCase
include PostgresqlUUIDHelper
+ include SchemaDumpingHelper
+
def setup
connection.create_table('big_serials', id: :bigserial) do |t|
t.string 'name'
@@ -119,10 +119,8 @@ class PostgresqlLargeKeysTest < ActiveRecord::TestCase
end
def test_omg
- schema = StringIO.new
- ActiveRecord::SchemaDumper.dump(connection, schema)
- assert_match "create_table \"big_serials\", id: :bigserial, force: true",
- schema.string
+ schema = dump_table_schema "big_serials"
+ assert_match "create_table \"big_serials\", id: :bigserial, force: true", schema
end
def teardown
@@ -132,6 +130,7 @@ end
class PostgresqlUUIDGenerationTest < ActiveRecord::TestCase
include PostgresqlUUIDHelper
+ include SchemaDumpingHelper
class UUID < ActiveRecord::Base
self.table_name = 'pg_uuids'
@@ -191,17 +190,15 @@ class PostgresqlUUIDGenerationTest < ActiveRecord::TestCase
end
def test_schema_dumper_for_uuid_primary_key
- schema = StringIO.new
- ActiveRecord::SchemaDumper.dump(connection, schema)
- assert_match(/\bcreate_table "pg_uuids", id: :uuid, default: "uuid_generate_v1\(\)"/, schema.string)
- assert_match(/t\.uuid "other_uuid", default: "uuid_generate_v4\(\)"/, schema.string)
+ schema = dump_table_schema "pg_uuids"
+ assert_match(/\bcreate_table "pg_uuids", id: :uuid, default: "uuid_generate_v1\(\)"/, schema)
+ assert_match(/t\.uuid "other_uuid", default: "uuid_generate_v4\(\)"/, schema)
end
def test_schema_dumper_for_uuid_primary_key_with_custom_default
- schema = StringIO.new
- ActiveRecord::SchemaDumper.dump(connection, schema)
- assert_match(/\bcreate_table "pg_uuids_2", id: :uuid, default: "my_uuid_generator\(\)"/, schema.string)
- assert_match(/t\.uuid "other_uuid_2", default: "my_uuid_generator\(\)"/, schema.string)
+ schema = dump_table_schema "pg_uuids_2"
+ assert_match(/\bcreate_table "pg_uuids_2", id: :uuid, default: "my_uuid_generator\(\)"/, schema)
+ assert_match(/t\.uuid "other_uuid_2", default: "my_uuid_generator\(\)"/, schema)
end
end
end
diff --git a/activerecord/test/cases/adapters/sqlite3/explain_test.rb b/activerecord/test/cases/adapters/sqlite3/explain_test.rb
index f1d6119d2e..de6e35ef57 100644
--- a/activerecord/test/cases/adapters/sqlite3/explain_test.rb
+++ b/activerecord/test/cases/adapters/sqlite3/explain_test.rb
@@ -1,5 +1,6 @@
require "cases/helper"
require 'models/developer'
+require 'models/computer'
module ActiveRecord
module ConnectionAdapters
diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
index 8c1c22d3bf..9d09ff49c7 100644
--- a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
+++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
@@ -133,8 +133,8 @@ module ActiveRecord
end
def test_bind_value_substitute
- bind_param = @conn.substitute_at('foo', 0)
- assert_equal Arel.sql('?'), bind_param
+ bind_param = @conn.substitute_at('foo')
+ assert_equal Arel.sql('?'), bind_param.to_sql
end
def test_exec_no_binds
@@ -327,11 +327,11 @@ module ActiveRecord
def test_columns
with_example_table do
- columns = @conn.columns('ex').sort_by { |x| x.name }
+ columns = @conn.columns('ex').sort_by(&:name)
assert_equal 2, columns.length
- assert_equal %w{ id number }.sort, columns.map { |x| x.name }
- assert_equal [nil, nil], columns.map { |x| x.default }
- assert_equal [true, true], columns.map { |x| x.null }
+ assert_equal %w{ id number }.sort, columns.map(&:name)
+ assert_equal [nil, nil], columns.map(&:default)
+ assert_equal [true, true], columns.map(&:null)
end
end
diff --git a/activerecord/test/cases/ar_schema_test.rb b/activerecord/test/cases/ar_schema_test.rb
index b6333240a8..025c9fe6f9 100644
--- a/activerecord/test/cases/ar_schema_test.rb
+++ b/activerecord/test/cases/ar_schema_test.rb
@@ -115,6 +115,15 @@ if ActiveRecord::Base.connection.supports_migrations?
end
end
+ def test_timestamps_without_null_is_deprecated_on_add_timestamps
+ assert_deprecated do
+ ActiveRecord::Schema.define do
+ create_table :has_timestamps
+ add_timestamps :has_timestamps
+ end
+ end
+ end
+
def test_no_deprecation_warning_from_timestamps_on_create_table
assert_not_deprecated do
ActiveRecord::Schema.define do
diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb
index 25555bd75c..17394cb6f7 100644
--- a/activerecord/test/cases/associations/belongs_to_associations_test.rb
+++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb
@@ -1,5 +1,6 @@
require 'cases/helper'
require 'models/developer'
+require 'models/computer'
require 'models/project'
require 'models/company'
require 'models/topic'
@@ -57,6 +58,35 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
end
end
+ def test_default_scope_on_relations_is_not_cached
+ counter = 0
+
+ comments = Class.new(ActiveRecord::Base) {
+ self.table_name = 'comments'
+ self.inheritance_column = 'not_there'
+
+ posts = Class.new(ActiveRecord::Base) {
+ self.table_name = 'posts'
+ self.inheritance_column = 'not_there'
+
+ default_scope -> {
+ counter += 1
+ where("id = :inc", :inc => counter)
+ }
+
+ has_many :comments, :class => comments
+ }
+ belongs_to :post, :class => posts, :inverse_of => false
+ }
+
+ assert_equal 0, counter
+ comment = comments.first
+ assert_equal 0, counter
+ sql = capture_sql { comment.post }
+ comment.reload
+ assert_not_equal sql, capture_sql { comment.post }
+ end
+
def test_proxy_assignment
account = Account.find(1)
assert_nothing_raised { account.firm = account.firm }
diff --git a/activerecord/test/cases/associations/callbacks_test.rb b/activerecord/test/cases/associations/callbacks_test.rb
index 5b7e462f64..a531e0e02c 100644
--- a/activerecord/test/cases/associations/callbacks_test.rb
+++ b/activerecord/test/cases/associations/callbacks_test.rb
@@ -3,6 +3,7 @@ require 'models/post'
require 'models/author'
require 'models/project'
require 'models/developer'
+require 'models/computer'
require 'models/company'
class AssociationCallbacksTest < ActiveRecord::TestCase
diff --git a/activerecord/test/cases/associations/eager_load_nested_include_test.rb b/activerecord/test/cases/associations/eager_load_nested_include_test.rb
index 0ff87d53ea..f571198079 100644
--- a/activerecord/test/cases/associations/eager_load_nested_include_test.rb
+++ b/activerecord/test/cases/associations/eager_load_nested_include_test.rb
@@ -70,9 +70,7 @@ class EagerLoadPolyAssocsTest < ActiveRecord::TestCase
teardown do
[Circle, Square, Triangle, PaintColor, PaintTexture,
- ShapeExpression, NonPolyOne, NonPolyTwo].each do |c|
- c.delete_all
- end
+ ShapeExpression, NonPolyOne, NonPolyTwo].each(&:delete_all)
end
def generate_test_object_graphs
diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb
index 8234ee95be..4321a198ca 100644
--- a/activerecord/test/cases/associations/eager_test.rb
+++ b/activerecord/test/cases/associations/eager_test.rb
@@ -17,6 +17,7 @@ require 'models/subscriber'
require 'models/subscription'
require 'models/book'
require 'models/developer'
+require 'models/computer'
require 'models/project'
require 'models/member'
require 'models/membership'
@@ -269,6 +270,14 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
end
+ def test_three_level_nested_preloading_does_not_raise_exception_when_association_does_not_exist
+ post_id = Comment.where(author_id: nil).where.not(post_id: nil).first.post_id
+
+ assert_nothing_raised do
+ Post.preload(:comments => [{:author => :essays}]).find(post_id)
+ end
+ end
+
def test_nested_loading_through_has_one_association
aa = AuthorAddress.all.merge!(:includes => {:author => :posts}).find(author_addresses(:david_address).id)
assert_equal aa.author.posts.count, aa.author.posts.length
@@ -329,31 +338,31 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_association_loading_with_belongs_to_and_limit
comments = Comment.all.merge!(:includes => :post, :limit => 5, :order => 'comments.id').to_a
assert_equal 5, comments.length
- assert_equal [1,2,3,5,6], comments.collect { |c| c.id }
+ assert_equal [1,2,3,5,6], comments.collect(&:id)
end
def test_eager_association_loading_with_belongs_to_and_limit_and_conditions
comments = Comment.all.merge!(:includes => :post, :where => 'post_id = 4', :limit => 3, :order => 'comments.id').to_a
assert_equal 3, comments.length
- assert_equal [5,6,7], comments.collect { |c| c.id }
+ assert_equal [5,6,7], comments.collect(&:id)
end
def test_eager_association_loading_with_belongs_to_and_limit_and_offset
comments = Comment.all.merge!(:includes => :post, :limit => 3, :offset => 2, :order => 'comments.id').to_a
assert_equal 3, comments.length
- assert_equal [3,5,6], comments.collect { |c| c.id }
+ assert_equal [3,5,6], comments.collect(&:id)
end
def test_eager_association_loading_with_belongs_to_and_limit_and_offset_and_conditions
comments = Comment.all.merge!(:includes => :post, :where => 'post_id = 4', :limit => 3, :offset => 1, :order => 'comments.id').to_a
assert_equal 3, comments.length
- assert_equal [6,7,8], comments.collect { |c| c.id }
+ assert_equal [6,7,8], comments.collect(&:id)
end
def test_eager_association_loading_with_belongs_to_and_limit_and_offset_and_conditions_array
comments = Comment.all.merge!(:includes => :post, :where => ['post_id = ?',4], :limit => 3, :offset => 1, :order => 'comments.id').to_a
assert_equal 3, comments.length
- assert_equal [6,7,8], comments.collect { |c| c.id }
+ assert_equal [6,7,8], comments.collect(&:id)
end
def test_eager_association_loading_with_belongs_to_and_conditions_string_with_unquoted_table_name
@@ -368,7 +377,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
comments = Comment.all.merge!(:includes => :post, :where => {:posts => {:id => 4}}, :limit => 3, :order => 'comments.id').to_a
end
assert_equal 3, comments.length
- assert_equal [5,6,7], comments.collect { |c| c.id }
+ assert_equal [5,6,7], comments.collect(&:id)
assert_no_queries do
comments.first.post
end
@@ -397,13 +406,13 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_association_loading_with_belongs_to_and_limit_and_multiple_associations
posts = Post.all.merge!(:includes => [:author, :very_special_comment], :limit => 1, :order => 'posts.id').to_a
assert_equal 1, posts.length
- assert_equal [1], posts.collect { |p| p.id }
+ assert_equal [1], posts.collect(&:id)
end
def test_eager_association_loading_with_belongs_to_and_limit_and_offset_and_multiple_associations
posts = Post.all.merge!(:includes => [:author, :very_special_comment], :limit => 1, :offset => 1, :order => 'posts.id').to_a
assert_equal 1, posts.length
- assert_equal [2], posts.collect { |p| p.id }
+ assert_equal [2], posts.collect(&:id)
end
def test_eager_association_loading_with_belongs_to_inferred_foreign_key_from_association_name
@@ -536,13 +545,13 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_has_many_and_limit_and_conditions
posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => "posts.body = 'hello'", :order => "posts.id").to_a
assert_equal 2, posts.size
- assert_equal [4,5], posts.collect { |p| p.id }
+ assert_equal [4,5], posts.collect(&:id)
end
def test_eager_with_has_many_and_limit_and_conditions_array
posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => [ "posts.body = ?", 'hello' ], :order => "posts.id").to_a
assert_equal 2, posts.size
- assert_equal [4,5], posts.collect { |p| p.id }
+ assert_equal [4,5], posts.collect(&:id)
end
def test_eager_with_has_many_and_limit_and_conditions_array_on_the_eagers
@@ -903,6 +912,12 @@ class EagerAssociationTest < ActiveRecord::TestCase
assert_no_queries {assert_equal posts(:sti_comments), comment.post}
end
+ def test_eager_association_with_scope_with_joins
+ assert_nothing_raised do
+ Post.includes(:very_special_comment_with_post_with_joins).to_a
+ end
+ end
+
def test_preconfigured_includes_with_has_many
posts = authors(:david).posts_with_comments
one = posts.detect { |p| p.id == 1 }
diff --git a/activerecord/test/cases/associations/extension_test.rb b/activerecord/test/cases/associations/extension_test.rb
index 4c1fdfdd9a..9d373cd73b 100644
--- a/activerecord/test/cases/associations/extension_test.rb
+++ b/activerecord/test/cases/associations/extension_test.rb
@@ -3,6 +3,7 @@ require 'models/post'
require 'models/comment'
require 'models/project'
require 'models/developer'
+require 'models/computer'
require 'models/company_in_module'
class AssociationsExtensionsTest < ActiveRecord::TestCase
diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
index 859310575e..aea9207bfe 100644
--- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
@@ -1,5 +1,6 @@
require "cases/helper"
require 'models/developer'
+require 'models/computer'
require 'models/project'
require 'models/company'
require 'models/customer'
@@ -78,9 +79,13 @@ class SubDeveloper < Developer
:association_foreign_key => "developer_id"
end
+class DeveloperWithSymbolClassName < Developer
+ has_and_belongs_to_many :projects, class_name: :ProjectWithSymbolsForKeys
+end
+
class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
fixtures :accounts, :companies, :categories, :posts, :categories_posts, :developers, :projects, :developers_projects,
- :parrots, :pirates, :parrots_pirates, :treasures, :price_estimates, :tags, :taggings
+ :parrots, :pirates, :parrots_pirates, :treasures, :price_estimates, :tags, :taggings, :computers
def setup_data_for_habtm_case
ActiveRecord::Base.connection.execute('delete from countries_treaties')
@@ -550,7 +555,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
def test_dynamic_find_all_should_respect_readonly_access
projects(:active_record).readonly_developers.each { |d| assert_raise(ActiveRecord::ReadOnlyRecord) { d.save! } if d.valid?}
- projects(:active_record).readonly_developers.each { |d| d.readonly? }
+ projects(:active_record).readonly_developers.each(&:readonly?)
end
def test_new_with_values_in_collection
@@ -883,4 +888,18 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
child.special_projects << SpecialProject.new("name" => "Special Project")
assert child.save, 'child object should be saved'
end
+
+ def test_habtm_with_reflection_using_class_name_and_fixtures
+ assert_not_nil Developer._reflections['shared_computers']
+ # Checking the fixture for named association is important here, because it's the only way
+ # we've been able to reproduce this bug
+ assert_not_nil File.read(File.expand_path("../../../fixtures/developers.yml", __FILE__)).index("shared_computers")
+ assert_equal developers(:david).shared_computers.first, computers(:laptop)
+ end
+
+ def test_with_symbol_class_name
+ assert_nothing_raised NoMethodError do
+ DeveloperWithSymbolClassName.new
+ end
+ end
end
diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb
index e34b993029..c075872617 100644
--- a/activerecord/test/cases/associations/has_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -1,5 +1,6 @@
require "cases/helper"
require 'models/developer'
+require 'models/computer'
require 'models/project'
require 'models/company'
require 'models/contract'
@@ -76,6 +77,32 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
dev.developer_projects.map(&:project_id).sort
end
+ def test_default_scope_on_relations_is_not_cached
+ counter = 0
+ posts = Class.new(ActiveRecord::Base) {
+ self.table_name = 'posts'
+ self.inheritance_column = 'not_there'
+ post = self
+
+ comments = Class.new(ActiveRecord::Base) {
+ self.table_name = 'comments'
+ self.inheritance_column = 'not_there'
+ belongs_to :post, :class => post
+ default_scope -> {
+ counter += 1
+ where("id = :inc", :inc => counter)
+ }
+ }
+ has_many :comments, :class => comments, :foreign_key => 'post_id'
+ }
+ assert_equal 0, counter
+ post = posts.first
+ assert_equal 0, counter
+ sql = capture_sql { post.comments.to_a }
+ post.comments.reset
+ assert_not_equal sql, capture_sql { post.comments.to_a }
+ end
+
def test_has_many_build_with_options
college = College.create(name: 'UFMT')
Student.create(active: true, college_id: college.id, name: 'Sarah')
@@ -387,6 +414,13 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal "Summit", Firm.all.merge!(:order => "id").first.clients_using_primary_key.first.name
end
+ def test_update_all_on_association_accessed_before_save
+ firm = Firm.new(name: 'Firm')
+ firm.clients << Client.first
+ firm.save!
+ assert_equal firm.clients.count, firm.clients.update_all(description: 'Great!')
+ end
+
def test_belongs_to_sanity
c = Client.new
assert_nil c.firm, "belongs_to failed sanity check on new object"
@@ -555,17 +589,21 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_create_with_bang_on_has_many_when_parent_is_new_raises
- assert_raise(ActiveRecord::RecordNotSaved) do
+ error = assert_raise(ActiveRecord::RecordNotSaved) do
firm = Firm.new
firm.plain_clients.create! :name=>"Whoever"
end
+
+ assert_equal "You cannot call create unless the parent is saved", error.message
end
def test_regular_create_on_has_many_when_parent_is_new_raises
- assert_raise(ActiveRecord::RecordNotSaved) do
+ error = assert_raise(ActiveRecord::RecordNotSaved) do
firm = Firm.new
firm.plain_clients.create :name=>"Whoever"
end
+
+ assert_equal "You cannot call create unless the parent is saved", error.message
end
def test_create_with_bang_on_has_many_raises_when_record_not_saved
@@ -576,9 +614,11 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_create_with_bang_on_habtm_when_parent_is_new_raises
- assert_raise(ActiveRecord::RecordNotSaved) do
+ error = assert_raise(ActiveRecord::RecordNotSaved) do
Developer.new("name" => "Aredridel").projects.create!
end
+
+ assert_equal "You cannot call create unless the parent is saved", error.message
end
def test_adding_a_mismatch_class
@@ -1179,7 +1219,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert !clients.empty?, "37signals has clients after load"
destroyed = companies(:first_firm).clients_of_firm.destroy_all
assert_equal clients.sort_by(&:id), destroyed.sort_by(&:id)
- assert destroyed.all? { |client| client.frozen? }, "destroyed clients should be frozen"
+ assert destroyed.all?(&:frozen?), "destroyed clients should be frozen"
assert companies(:first_firm).clients_of_firm.empty?, "37signals has no clients after destroy all"
assert companies(:first_firm).clients_of_firm(true).empty?, "37signals has no clients after destroy all and refresh"
end
@@ -1319,10 +1359,13 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert !account.valid?
assert !orig_accounts.empty?
- assert_raise ActiveRecord::RecordNotSaved do
+ error = assert_raise ActiveRecord::RecordNotSaved do
firm.accounts = [account]
end
+
assert_equal orig_accounts, firm.accounts
+ assert_equal "Failed to replace accounts because one or more of the " \
+ "new records could not be saved.", error.message
end
def test_replace_with_same_content
@@ -1895,6 +1938,14 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal [bulb1, bulb2], car.all_bulbs.sort_by(&:id)
end
+ test 'unscopes the default scope of associated model when used with include' do
+ car = Car.create!
+ bulb = Bulb.create! name: "other", car: car
+
+ assert_equal bulb, Car.find(car.id).all_bulbs.first
+ assert_equal bulb, Car.includes(:all_bulbs).find(car.id).all_bulbs.first
+ end
+
test "raises RecordNotDestroyed when replaced child can't be destroyed" do
car = Car.create!
original_child = FailedBulb.create!(car: car)
@@ -1955,4 +2006,68 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal 1, car.bulbs.count
assert_equal 1, car.tyres.count
end
+
+ test 'associations replace in memory when records have the same id' do
+ bulb = Bulb.create!
+ car = Car.create!(bulbs: [bulb])
+
+ new_bulb = Bulb.find(bulb.id)
+ new_bulb.name = "foo"
+ car.bulbs = [new_bulb]
+
+ assert_equal "foo", car.bulbs.first.name
+ end
+
+ test 'in memory replacement executes no queries' do
+ bulb = Bulb.create!
+ car = Car.create!(bulbs: [bulb])
+
+ new_bulb = Bulb.find(bulb.id)
+
+ assert_no_queries do
+ car.bulbs = [new_bulb]
+ end
+ end
+
+ test 'in memory replacements do not execute callbacks' do
+ raise_after_add = false
+ klass = Class.new(ActiveRecord::Base) do
+ self.table_name = :cars
+ has_many :bulbs, after_add: proc { raise if raise_after_add }
+
+ def self.name
+ "Car"
+ end
+ end
+ bulb = Bulb.create!
+ car = klass.create!(bulbs: [bulb])
+
+ new_bulb = Bulb.find(bulb.id)
+ raise_after_add = true
+
+ assert_nothing_raised do
+ car.bulbs = [new_bulb]
+ end
+ end
+
+ test 'in memory replacements sets inverse instance' do
+ bulb = Bulb.create!
+ car = Car.create!(bulbs: [bulb])
+
+ new_bulb = Bulb.find(bulb.id)
+ car.bulbs = [new_bulb]
+
+ assert_same car, new_bulb.car
+ end
+
+ test 'in memory replacement maintains order' do
+ first_bulb = Bulb.create!
+ second_bulb = Bulb.create!
+ car = Car.create!(bulbs: [first_bulb, second_bulb])
+
+ same_bulb = Bulb.find(first_bulb.id)
+ car.bulbs = [second_bulb, same_bulb]
+
+ assert_equal [first_bulb, second_bulb], car.bulbs
+ end
end
diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb
index cddf1a1f72..589a232bdb 100644
--- a/activerecord/test/cases/associations/has_many_through_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb
@@ -15,6 +15,7 @@ require 'models/toy'
require 'models/contract'
require 'models/company'
require 'models/developer'
+require 'models/computer'
require 'models/subscriber'
require 'models/book'
require 'models/subscription'
@@ -40,7 +41,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
def test_preload_sti_rhs_class
developers = Developer.includes(:firms).all.to_a
assert_no_queries do
- developers.each { |d| d.firms }
+ developers.each(&:firms)
end
end
@@ -614,8 +615,11 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
def test_create_on_new_record
p = Post.new
- assert_raises(ActiveRecord::RecordNotSaved) { p.people.create(:first_name => "mew") }
- assert_raises(ActiveRecord::RecordNotSaved) { p.people.create!(:first_name => "snow") }
+ error = assert_raises(ActiveRecord::RecordNotSaved) { p.people.create(:first_name => "mew") }
+ assert_equal "You cannot call create unless the parent is saved", error.message
+
+ error = assert_raises(ActiveRecord::RecordNotSaved) { p.people.create!(:first_name => "snow") }
+ assert_equal "You cannot call create unless the parent is saved", error.message
end
def test_associate_with_create_and_invalid_options
diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb
index d412b3168e..1a6d25f7d0 100644
--- a/activerecord/test/cases/associations/has_one_associations_test.rb
+++ b/activerecord/test/cases/associations/has_one_associations_test.rb
@@ -1,5 +1,6 @@
require "cases/helper"
require 'models/developer'
+require 'models/computer'
require 'models/project'
require 'models/company'
require 'models/ship'
@@ -409,9 +410,11 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
pirate = pirates(:redbeard)
new_ship = Ship.new
- assert_raise(ActiveRecord::RecordNotSaved) do
+ error = assert_raise(ActiveRecord::RecordNotSaved) do
pirate.ship = new_ship
end
+
+ assert_equal "Failed to save the new associated ship.", error.message
assert_nil pirate.ship
assert_nil new_ship.pirate_id
end
@@ -421,20 +424,25 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
pirate.ship.name = nil
assert !pirate.ship.valid?
- assert_raise(ActiveRecord::RecordNotSaved) do
+ error = assert_raise(ActiveRecord::RecordNotSaved) do
pirate.ship = ships(:interceptor)
end
+
assert_equal ships(:black_pearl), pirate.ship
assert_equal pirate.id, pirate.ship.pirate_id
+ assert_equal "Failed to remove the existing associated ship. " +
+ "The record failed to save after its foreign key was set to nil.", error.message
end
def test_replacement_failure_due_to_new_record_should_raise_error
pirate = pirates(:blackbeard)
new_ship = Ship.new
- assert_raise(ActiveRecord::RecordNotSaved) do
+ error = assert_raise(ActiveRecord::RecordNotSaved) do
pirate.ship = new_ship
end
+
+ assert_equal "Failed to save the new associated ship.", error.message
assert_equal ships(:black_pearl), pirate.ship
assert_equal pirate.id, pirate.ship.pirate_id
assert_equal pirate.id, ships(:black_pearl).reload.pirate_id
diff --git a/activerecord/test/cases/associations/inner_join_association_test.rb b/activerecord/test/cases/associations/inner_join_association_test.rb
index 07cf65a760..9938302885 100644
--- a/activerecord/test/cases/associations/inner_join_association_test.rb
+++ b/activerecord/test/cases/associations/inner_join_association_test.rb
@@ -54,7 +54,7 @@ class InnerJoinAssociationTest < ActiveRecord::TestCase
def test_find_with_implicit_inner_joins_without_select_does_not_imply_readonly
authors = Author.joins(:posts)
assert_not authors.empty?, "expected authors to be non-empty"
- assert authors.none? {|a| a.readonly? }, "expected no authors to be readonly"
+ assert authors.none?(&:readonly?), "expected no authors to be readonly"
end
def test_find_with_implicit_inner_joins_honors_readonly_with_select
diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb
index cace7ba142..140ccdac72 100644
--- a/activerecord/test/cases/associations/join_model_test.rb
+++ b/activerecord/test/cases/associations/join_model_test.rb
@@ -393,18 +393,18 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_has_many_through_polymorphic_has_one
- assert_equal Tagging.find(1,2).sort_by { |t| t.id }, authors(:david).taggings_2
+ assert_equal Tagging.find(1,2).sort_by(&:id), authors(:david).taggings_2
end
def test_has_many_through_polymorphic_has_many
- assert_equal taggings(:welcome_general, :thinking_general), authors(:david).taggings.distinct.sort_by { |t| t.id }
+ assert_equal taggings(:welcome_general, :thinking_general), authors(:david).taggings.distinct.sort_by(&:id)
end
def test_include_has_many_through_polymorphic_has_many
author = Author.includes(:taggings).find authors(:david).id
expected_taggings = taggings(:welcome_general, :thinking_general)
assert_no_queries do
- assert_equal expected_taggings, author.taggings.distinct.sort_by { |t| t.id }
+ assert_equal expected_taggings, author.taggings.distinct.sort_by(&:id)
end
end
diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb
index 9b0cf4c18f..c6769edcbf 100644
--- a/activerecord/test/cases/associations_test.rb
+++ b/activerecord/test/cases/associations_test.rb
@@ -1,6 +1,7 @@
require "cases/helper"
require 'models/computer'
require 'models/developer'
+require 'models/computer'
require 'models/project'
require 'models/company'
require 'models/categorization'
@@ -47,7 +48,7 @@ class AssociationsTest < ActiveRecord::TestCase
assert_kind_of Firm, firm
firm.clear_association_cache
- assert_equal Firm.find(1).clients.collect{ |x| x.name }.sort, firm.clients.collect{ |x| x.name }.sort
+ assert_equal Firm.find(1).clients.collect(&:name).sort, firm.clients.collect(&:name).sort
end
def test_clear_association_cache_new_record
diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb
index c3e8ceb0da..731d433706 100644
--- a/activerecord/test/cases/attribute_methods_test.rb
+++ b/activerecord/test/cases/attribute_methods_test.rb
@@ -1,6 +1,7 @@
require "cases/helper"
require 'models/minimalistic'
require 'models/developer'
+require 'models/computer'
require 'models/auto_id'
require 'models/boolean'
require 'models/computer'
diff --git a/activerecord/test/cases/attribute_set_test.rb b/activerecord/test/cases/attribute_set_test.rb
index dc20c3c676..de63672963 100644
--- a/activerecord/test/cases/attribute_set_test.rb
+++ b/activerecord/test/cases/attribute_set_test.rb
@@ -109,7 +109,15 @@ module ActiveRecord
test "fetch_value returns nil for unknown attributes" do
attributes = attributes_with_uninitialized_key
- assert_nil attributes.fetch_value(:wibble)
+ assert_nil attributes.fetch_value(:wibble) { "hello" }
+ end
+
+ test "fetch_value returns nil for unknown attributes when types has a default" do
+ types = Hash.new(Type::Value.new)
+ builder = AttributeSet::Builder.new(types)
+ attributes = builder.build_from_database
+
+ assert_nil attributes.fetch_value(:wibble) { "hello" }
end
test "fetch_value uses the given block for uninitialized attributes" do
@@ -123,6 +131,15 @@ module ActiveRecord
assert_nil attributes.fetch_value(:bar)
end
+ test "the primary_key is always initialized" do
+ builder = AttributeSet::Builder.new({ foo: Type::Integer.new }, :foo)
+ attributes = builder.build_from_database
+
+ assert attributes.key?(:foo)
+ assert_equal [:foo], attributes.keys
+ assert attributes[:foo].initialized?
+ end
+
class MyType
def type_cast_from_user(value)
return if value.nil?
diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb
index 734fd5fe18..04d5a2869c 100644
--- a/activerecord/test/cases/autosave_association_test.rb
+++ b/activerecord/test/cases/autosave_association_test.rb
@@ -4,6 +4,7 @@ require 'models/comment'
require 'models/company'
require 'models/customer'
require 'models/developer'
+require 'models/computer'
require 'models/invoice'
require 'models/line_item'
require 'models/order'
@@ -773,13 +774,13 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase
def test_should_destroy_has_many_as_part_of_the_save_transaction_if_they_were_marked_for_destruction
2.times { |i| @pirate.birds.create!(:name => "birds_#{i}") }
- assert !@pirate.birds.any? { |child| child.marked_for_destruction? }
+ assert !@pirate.birds.any?(&:marked_for_destruction?)
- @pirate.birds.each { |child| child.mark_for_destruction }
+ @pirate.birds.each(&:mark_for_destruction)
klass = @pirate.birds.first.class
ids = @pirate.birds.map(&:id)
- assert @pirate.birds.all? { |child| child.marked_for_destruction? }
+ assert @pirate.birds.all?(&:marked_for_destruction?)
ids.each { |id| assert klass.find_by_id(id) }
@pirate.save
@@ -813,14 +814,14 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase
@pirate.birds.each { |bird| bird.name = '' }
assert !@pirate.valid?
- @pirate.birds.each { |bird| bird.destroy }
+ @pirate.birds.each(&:destroy)
assert @pirate.valid?
end
def test_a_child_marked_for_destruction_should_not_be_destroyed_twice_while_saving_has_many
@pirate.birds.create!(:name => "birds_1")
- @pirate.birds.each { |bird| bird.mark_for_destruction }
+ @pirate.birds.each(&:mark_for_destruction)
assert @pirate.save
@pirate.birds.each { |bird| bird.expects(:destroy).never }
@@ -887,7 +888,7 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase
association_name_with_callbacks = "birds_with_#{callback_type}_callbacks"
@pirate.send(association_name_with_callbacks).create!(:name => "Crowe the One-Eyed")
- @pirate.send(association_name_with_callbacks).each { |c| c.mark_for_destruction }
+ @pirate.send(association_name_with_callbacks).each(&:mark_for_destruction)
child_id = @pirate.send(association_name_with_callbacks).first.id
@pirate.ship_log.clear
@@ -905,8 +906,8 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase
def test_should_destroy_habtm_as_part_of_the_save_transaction_if_they_were_marked_for_destruction
2.times { |i| @pirate.parrots.create!(:name => "parrots_#{i}") }
- assert !@pirate.parrots.any? { |parrot| parrot.marked_for_destruction? }
- @pirate.parrots.each { |parrot| parrot.mark_for_destruction }
+ assert !@pirate.parrots.any?(&:marked_for_destruction?)
+ @pirate.parrots.each(&:mark_for_destruction)
assert_no_difference "Parrot.count" do
@pirate.save
@@ -939,14 +940,14 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase
@pirate.parrots.each { |parrot| parrot.name = '' }
assert !@pirate.valid?
- @pirate.parrots.each { |parrot| parrot.destroy }
+ @pirate.parrots.each(&:destroy)
assert @pirate.valid?
end
def test_a_child_marked_for_destruction_should_not_be_destroyed_twice_while_saving_habtm
@pirate.parrots.create!(:name => "parrots_1")
- @pirate.parrots.each { |parrot| parrot.mark_for_destruction }
+ @pirate.parrots.each(&:mark_for_destruction)
assert @pirate.save
Pirate.transaction do
@@ -991,7 +992,7 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase
association_name_with_callbacks = "parrots_with_#{callback_type}_callbacks"
@pirate.send(association_name_with_callbacks).create!(:name => "Crowe the One-Eyed")
- @pirate.send(association_name_with_callbacks).each { |c| c.mark_for_destruction }
+ @pirate.send(association_name_with_callbacks).each(&:mark_for_destruction)
child_id = @pirate.send(association_name_with_callbacks).first.id
@pirate.ship_log.clear
diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb
index 3675401555..098d5b8451 100644
--- a/activerecord/test/cases/base_test.rb
+++ b/activerecord/test/cases/base_test.rb
@@ -10,6 +10,7 @@ require 'models/category'
require 'models/company'
require 'models/customer'
require 'models/developer'
+require 'models/computer'
require 'models/project'
require 'models/default'
require 'models/auto_id'
diff --git a/activerecord/test/cases/bind_parameter_test.rb b/activerecord/test/cases/bind_parameter_test.rb
index 0bc7ee6d64..c4634d11e2 100644
--- a/activerecord/test/cases/bind_parameter_test.rb
+++ b/activerecord/test/cases/bind_parameter_test.rb
@@ -31,9 +31,9 @@ module ActiveRecord
if ActiveRecord::Base.connection.supports_statement_cache?
def test_binds_are_logged
- sub = @connection.substitute_at(@pk, 0)
+ sub = @connection.substitute_at(@pk)
binds = [[@pk, 1]]
- sql = "select * from topics where id = #{sub}"
+ sql = "select * from topics where id = #{sub.to_sql}"
@connection.exec_query(sql, 'SQL', binds)
@@ -42,9 +42,9 @@ module ActiveRecord
end
def test_binds_are_logged_after_type_cast
- sub = @connection.substitute_at(@pk, 0)
+ sub = @connection.substitute_at(@pk)
binds = [[@pk, "3"]]
- sql = "select * from topics where id = #{sub}"
+ sql = "select * from topics where id = #{sub.to_sql}"
@connection.exec_query(sql, 'SQL', binds)
diff --git a/activerecord/test/cases/callbacks_test.rb b/activerecord/test/cases/callbacks_test.rb
index c8f56e3c73..e3c3c2fcdf 100644
--- a/activerecord/test/cases/callbacks_test.rb
+++ b/activerecord/test/cases/callbacks_test.rb
@@ -1,4 +1,6 @@
require "cases/helper"
+require 'models/developer'
+require 'models/computer'
class CallbackDeveloper < ActiveRecord::Base
self.table_name = 'developers'
@@ -441,7 +443,8 @@ class CallbacksTest < ActiveRecord::TestCase
david = ImmutableDeveloper.find(1)
assert david.valid?
assert !david.save
- assert_raise(ActiveRecord::RecordNotSaved) { david.save! }
+ exc = assert_raise(ActiveRecord::RecordNotSaved) { david.save! }
+ assert_equal exc.record, david
david = ImmutableDeveloper.find(1)
david.salary = 10_000_000
@@ -475,7 +478,8 @@ class CallbacksTest < ActiveRecord::TestCase
def test_before_destroy_returning_false
david = ImmutableDeveloper.find(1)
assert !david.destroy
- assert_raise(ActiveRecord::RecordNotDestroyed) { david.destroy! }
+ exc = assert_raise(ActiveRecord::RecordNotDestroyed) { david.destroy! }
+ assert_equal exc.record, david
assert_not_nil ImmutableDeveloper.find_by_id(1)
someone = CallbackCancellationDeveloper.find(1)
diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb
index dc73faa5be..a607c1319f 100644
--- a/activerecord/test/cases/finder_test.rb
+++ b/activerecord/test/cases/finder_test.rb
@@ -10,6 +10,7 @@ require 'models/reply'
require 'models/entrant'
require 'models/project'
require 'models/developer'
+require 'models/computer'
require 'models/customer'
require 'models/toy'
require 'models/matey'
@@ -933,7 +934,7 @@ class FinderTest < ActiveRecord::TestCase
joins('LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id').
where('project_id=1').to_a
assert_equal 3, developers_on_project_one.length
- developer_names = developers_on_project_one.map { |d| d.name }
+ developer_names = developers_on_project_one.map(&:name)
assert developer_names.include?('David')
assert developer_names.include?('Jamis')
end
@@ -988,7 +989,7 @@ class FinderTest < ActiveRecord::TestCase
end
def test_select_values
- assert_equal ["1","2","3","4","5","6","7","8","9", "10", "11"], Company.connection.select_values("SELECT id FROM companies ORDER BY id").map! { |i| i.to_s }
+ assert_equal ["1","2","3","4","5","6","7","8","9", "10", "11"], Company.connection.select_values("SELECT id FROM companies ORDER BY id").map!(&:to_s)
assert_equal ["37signals","Summit","Microsoft", "Flamboyant Software", "Ex Nihilo", "RailsCore", "Leetsoft", "Jadedpixel", "Odegy", "Ex Nihilo Part Deux", "Apex"], Company.connection.select_values("SELECT name FROM companies ORDER BY id")
end
@@ -1014,7 +1015,7 @@ class FinderTest < ActiveRecord::TestCase
where(client_of: [2, 1, nil],
name: ['37signals', 'Summit', 'Microsoft']).
order('client_of DESC').
- map { |x| x.client_of }
+ map(&:client_of)
assert client_of.include?(nil)
assert_equal [2, 1].sort, client_of.compact.sort
@@ -1024,7 +1025,7 @@ class FinderTest < ActiveRecord::TestCase
client_of = Company.
where(client_of: [nil]).
order('client_of DESC').
- map { |x| x.client_of }
+ map(&:client_of)
assert_equal [], client_of.compact
end
diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb
index 7141d3ee7f..9edeb8b47f 100644
--- a/activerecord/test/cases/fixtures_test.rb
+++ b/activerecord/test/cases/fixtures_test.rb
@@ -5,11 +5,13 @@ require 'models/admin/randomly_named_c1'
require 'models/admin/user'
require 'models/binary'
require 'models/book'
+require 'models/bulb'
require 'models/category'
require 'models/company'
require 'models/computer'
require 'models/course'
require 'models/developer'
+require 'models/computer'
require 'models/joke'
require 'models/matey'
require 'models/parrot'
@@ -852,3 +854,16 @@ class CustomNameForFixtureOrModelTest < ActiveRecord::TestCase
assert_equal 'randomly_named_table', Admin::ClassNameThatDoesNotFollowCONVENTIONS.table_name
end
end
+
+class FixturesWithDefaultScopeTest < ActiveRecord::TestCase
+ fixtures :bulbs
+
+ test "inserts fixtures excluded by a default scope" do
+ assert_equal 1, Bulb.count
+ assert_equal 2, Bulb.unscoped.count
+ end
+
+ test "allows access to fixtures excluded by a default scope" do
+ assert_equal "special", bulbs(:special).name
+ end
+end
diff --git a/activerecord/test/cases/inheritance_test.rb b/activerecord/test/cases/inheritance_test.rb
index 792950d24d..0338669016 100644
--- a/activerecord/test/cases/inheritance_test.rb
+++ b/activerecord/test/cases/inheritance_test.rb
@@ -22,7 +22,7 @@ class InheritanceTest < ActiveRecord::TestCase
company = Company.first
company = company.dup
company.extend(Module.new {
- def read_attribute(name)
+ def _read_attribute(name)
return ' ' if name == 'type'
super
end
diff --git a/activerecord/test/cases/integration_test.rb b/activerecord/test/cases/integration_test.rb
index dfb8a608cb..0021988083 100644
--- a/activerecord/test/cases/integration_test.rb
+++ b/activerecord/test/cases/integration_test.rb
@@ -3,6 +3,7 @@
require 'cases/helper'
require 'models/company'
require 'models/developer'
+require 'models/computer'
require 'models/owner'
require 'models/pet'
diff --git a/activerecord/test/cases/migration/change_table_test.rb b/activerecord/test/cases/migration/change_table_test.rb
index 777a48ad14..6613783fba 100644
--- a/activerecord/test/cases/migration/change_table_test.rb
+++ b/activerecord/test/cases/migration/change_table_test.rb
@@ -213,6 +213,12 @@ module ActiveRecord
t.rename :bar, :baz
end
end
+
+ def test_table_name_set
+ with_change_table do |t|
+ assert_equal :delete_me, t.name
+ end
+ end
end
end
end
diff --git a/activerecord/test/cases/migration/column_positioning_test.rb b/activerecord/test/cases/migration/column_positioning_test.rb
index 77a752f050..62186e13a5 100644
--- a/activerecord/test/cases/migration/column_positioning_test.rb
+++ b/activerecord/test/cases/migration/column_positioning_test.rb
@@ -25,30 +25,30 @@ module ActiveRecord
if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
def test_column_positioning
- assert_equal %w(first second third), conn.columns(:testings).map {|c| c.name }
+ assert_equal %w(first second third), conn.columns(:testings).map(&:name)
end
def test_add_column_with_positioning
conn.add_column :testings, :new_col, :integer
- assert_equal %w(first second third new_col), conn.columns(:testings).map {|c| c.name }
+ assert_equal %w(first second third new_col), conn.columns(:testings).map(&:name)
end
def test_add_column_with_positioning_first
conn.add_column :testings, :new_col, :integer, :first => true
- assert_equal %w(new_col first second third), conn.columns(:testings).map {|c| c.name }
+ assert_equal %w(new_col first second third), conn.columns(:testings).map(&:name)
end
def test_add_column_with_positioning_after
conn.add_column :testings, :new_col, :integer, :after => :first
- assert_equal %w(first new_col second third), conn.columns(:testings).map {|c| c.name }
+ assert_equal %w(first new_col second third), conn.columns(:testings).map(&:name)
end
def test_change_column_with_positioning
conn.change_column :testings, :second, :integer, :first => true
- assert_equal %w(second first third), conn.columns(:testings).map {|c| c.name }
+ assert_equal %w(second first third), conn.columns(:testings).map(&:name)
conn.change_column :testings, :second, :integer, :after => :third
- assert_equal %w(first third second), conn.columns(:testings).map {|c| c.name }
+ assert_equal %w(first third second), conn.columns(:testings).map(&:name)
end
end
end
diff --git a/activerecord/test/cases/migration/foreign_key_test.rb b/activerecord/test/cases/migration/foreign_key_test.rb
index 406dd70c37..51e21528c2 100644
--- a/activerecord/test/cases/migration/foreign_key_test.rb
+++ b/activerecord/test/cases/migration/foreign_key_test.rb
@@ -17,11 +17,11 @@ module ActiveRecord
setup do
@connection = ActiveRecord::Base.connection
- @connection.create_table "rockets" do |t|
+ @connection.create_table "rockets", force: true do |t|
t.string :name
end
- @connection.create_table "astronauts" do |t|
+ @connection.create_table "astronauts", force: true do |t|
t.string :name
t.references :rocket
end
@@ -162,6 +162,14 @@ module ActiveRecord
assert_equal [], @connection.foreign_keys("astronauts")
end
+ 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
+
def test_remove_foreign_key_by_name
@connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", name: "fancy_named_fk"
diff --git a/activerecord/test/cases/migration/index_test.rb b/activerecord/test/cases/migration/index_test.rb
index ac932378fd..b23b9a679f 100644
--- a/activerecord/test/cases/migration/index_test.rb
+++ b/activerecord/test/cases/migration/index_test.rb
@@ -36,6 +36,20 @@ module ActiveRecord
assert connection.index_name_exists?(table_name, 'new_idx', true)
end
+ def test_rename_index_too_long
+ too_long_index_name = good_index_name + 'x'
+ # keep the names short to make Oracle and similar behave
+ connection.add_index(table_name, [:foo], :name => 'old_idx')
+ e = assert_raises(ArgumentError) {
+ connection.rename_index(table_name, 'old_idx', too_long_index_name)
+ }
+ assert_match(/too long; the limit is #{connection.allowed_index_name_length} characters/, e.message)
+
+ # if the adapter doesn't support the indexes call, pick defaults that let the test pass
+ assert connection.index_name_exists?(table_name, 'old_idx', false)
+ end
+
+
def test_double_add_index
connection.add_index(table_name, [:foo], :name => 'some_idx')
assert_raises(ArgumentError) {
diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb
index 6b7a0a9000..3192b797b4 100644
--- a/activerecord/test/cases/migration_test.rb
+++ b/activerecord/test/cases/migration_test.rb
@@ -5,6 +5,7 @@ require 'bigdecimal/util'
require 'models/person'
require 'models/topic'
require 'models/developer'
+require 'models/computer'
require MIGRATIONS_ROOT + "/valid/2_we_need_reminders"
require MIGRATIONS_ROOT + "/rename/1_we_need_things"
diff --git a/activerecord/test/cases/migrator_test.rb b/activerecord/test/cases/migrator_test.rb
index f05ca900aa..c0daa83e9c 100644
--- a/activerecord/test/cases/migrator_test.rb
+++ b/activerecord/test/cases/migrator_test.rb
@@ -149,7 +149,7 @@ class MigratorTest < ActiveRecord::TestCase
def test_up_calls_up
migrations = [Sensor.new(nil, 0), Sensor.new(nil, 1), Sensor.new(nil, 2)]
ActiveRecord::Migrator.new(:up, migrations).migrate
- assert migrations.all? { |m| m.went_up }
+ assert migrations.all?(&:went_up)
assert migrations.all? { |m| !m.went_down }
assert_equal 2, ActiveRecord::Migrator.current_version
end
@@ -160,7 +160,7 @@ class MigratorTest < ActiveRecord::TestCase
migrations = [Sensor.new(nil, 0), Sensor.new(nil, 1), Sensor.new(nil, 2)]
ActiveRecord::Migrator.new(:down, migrations).migrate
assert migrations.all? { |m| !m.went_up }
- assert migrations.all? { |m| m.went_down }
+ assert migrations.all?(&:went_down)
assert_equal 0, ActiveRecord::Migrator.current_version
end
diff --git a/activerecord/test/cases/modules_test.rb b/activerecord/test/cases/modules_test.rb
index e87773df94..6f65bf80eb 100644
--- a/activerecord/test/cases/modules_test.rb
+++ b/activerecord/test/cases/modules_test.rb
@@ -2,6 +2,7 @@ require "cases/helper"
require 'models/company_in_module'
require 'models/shop'
require 'models/developer'
+require 'models/computer'
class ModulesTest < ActiveRecord::TestCase
fixtures :accounts, :companies, :projects, :developers, :collections, :products, :variants
diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb
index cf96c3fccf..5c7e8a65d2 100644
--- a/activerecord/test/cases/nested_attributes_test.rb
+++ b/activerecord/test/cases/nested_attributes_test.rb
@@ -13,7 +13,7 @@ require 'active_support/hash_with_indifferent_access'
class TestNestedAttributesInGeneral < ActiveRecord::TestCase
teardown do
- Pirate.accepts_nested_attributes_for :ship, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
+ Pirate.accepts_nested_attributes_for :ship, :allow_destroy => true, :reject_if => proc(&:empty?)
end
def test_base_should_have_an_empty_nested_attributes_options
@@ -300,13 +300,13 @@ class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
end
def test_should_not_destroy_an_existing_record_if_allow_destroy_is_false
- Pirate.accepts_nested_attributes_for :ship, :allow_destroy => false, :reject_if => proc { |attributes| attributes.empty? }
+ Pirate.accepts_nested_attributes_for :ship, :allow_destroy => false, :reject_if => proc(&:empty?)
@pirate.update(ship_attributes: { id: @pirate.ship.id, _destroy: '1' })
assert_equal @ship, @pirate.reload.ship
- Pirate.accepts_nested_attributes_for :ship, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
+ Pirate.accepts_nested_attributes_for :ship, :allow_destroy => true, :reject_if => proc(&:empty?)
end
def test_should_also_work_with_a_HashWithIndifferentAccess
@@ -494,12 +494,12 @@ class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase
end
def test_should_not_destroy_an_existing_record_if_allow_destroy_is_false
- Ship.accepts_nested_attributes_for :pirate, :allow_destroy => false, :reject_if => proc { |attributes| attributes.empty? }
+ Ship.accepts_nested_attributes_for :pirate, :allow_destroy => false, :reject_if => proc(&:empty?)
@ship.update(pirate_attributes: { id: @ship.pirate.id, _destroy: '1' })
assert_nothing_raised(ActiveRecord::RecordNotFound) { @ship.pirate.reload }
ensure
- Ship.accepts_nested_attributes_for :pirate, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
+ Ship.accepts_nested_attributes_for :pirate, :allow_destroy => true, :reject_if => proc(&:empty?)
end
def test_should_work_with_update_as_well
@@ -855,7 +855,7 @@ end
module NestedAttributesLimitTests
def teardown
- Pirate.accepts_nested_attributes_for :parrots, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
+ Pirate.accepts_nested_attributes_for :parrots, :allow_destroy => true, :reject_if => proc(&:empty?)
end
def test_limit_with_less_records
diff --git a/activerecord/test/cases/persistence_test.rb b/activerecord/test/cases/persistence_test.rb
index 2170fe6118..6fc4731f01 100644
--- a/activerecord/test/cases/persistence_test.rb
+++ b/activerecord/test/cases/persistence_test.rb
@@ -8,6 +8,7 @@ require 'models/reply'
require 'models/category'
require 'models/company'
require 'models/developer'
+require 'models/computer'
require 'models/project'
require 'models/minimalistic'
require 'models/warehouse_thing'
@@ -126,7 +127,7 @@ class PersistenceTest < ActiveRecord::TestCase
assert_difference('Topic.count', -topics_by_mary.size) do
destroyed = Topic.destroy_all(conditions).sort_by(&:id)
assert_equal topics_by_mary, destroyed
- assert destroyed.all? { |topic| topic.frozen? }, "destroyed topics should be frozen"
+ assert destroyed.all?(&:frozen?), "destroyed topics should be frozen"
end
end
@@ -136,7 +137,7 @@ class PersistenceTest < ActiveRecord::TestCase
assert_difference('Client.count', -2) do
destroyed = Client.destroy([2, 3]).sort_by(&:id)
assert_equal clients, destroyed
- assert destroyed.all? { |client| client.frozen? }, "destroyed clients should be frozen"
+ assert destroyed.all?(&:frozen?), "destroyed clients should be frozen"
end
end
diff --git a/activerecord/test/cases/pooled_connections_test.rb b/activerecord/test/cases/pooled_connections_test.rb
index 8eea10143f..98888150a8 100644
--- a/activerecord/test/cases/pooled_connections_test.rb
+++ b/activerecord/test/cases/pooled_connections_test.rb
@@ -13,7 +13,7 @@ class PooledConnectionsTest < ActiveRecord::TestCase
teardown do
ActiveRecord::Base.clear_all_connections!
ActiveRecord::Base.establish_connection(@connection)
- @per_test_teardown.each {|td| td.call }
+ @per_test_teardown.each(&:call)
end
# Will deadlock due to lack of Monitor timeouts in 1.9
diff --git a/activerecord/test/cases/readonly_test.rb b/activerecord/test/cases/readonly_test.rb
index 2afd25c989..1c919f0b57 100644
--- a/activerecord/test/cases/readonly_test.rb
+++ b/activerecord/test/cases/readonly_test.rb
@@ -3,6 +3,7 @@ require 'models/author'
require 'models/post'
require 'models/comment'
require 'models/developer'
+require 'models/computer'
require 'models/project'
require 'models/reader'
require 'models/person'
@@ -22,9 +23,15 @@ class ReadOnlyTest < ActiveRecord::TestCase
assert !dev.save
dev.name = 'Forbidden.'
end
- assert_raise(ActiveRecord::ReadOnlyRecord) { dev.save }
- assert_raise(ActiveRecord::ReadOnlyRecord) { dev.save! }
- assert_raise(ActiveRecord::ReadOnlyRecord) { dev.destroy }
+
+ e = assert_raise(ActiveRecord::ReadOnlyRecord) { dev.save }
+ assert_equal "Developer is marked as readonly", e.message
+
+ e = assert_raise(ActiveRecord::ReadOnlyRecord) { dev.save! }
+ assert_equal "Developer is marked as readonly", e.message
+
+ e = assert_raise(ActiveRecord::ReadOnlyRecord) { dev.destroy }
+ assert_equal "Developer is marked as readonly", e.message
end
diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb
index 84abaf0291..e86b892a0a 100644
--- a/activerecord/test/cases/reflection_test.rb
+++ b/activerecord/test/cases/reflection_test.rb
@@ -50,13 +50,13 @@ class ReflectionTest < ActiveRecord::TestCase
end
def test_columns_are_returned_in_the_order_they_were_declared
- column_names = Topic.columns.map { |column| column.name }
+ column_names = Topic.columns.map(&:name)
assert_equal %w(id title author_name author_email_address written_on bonus_time last_read content important approved replies_count unique_replies_count parent_id parent_title type group created_at updated_at), column_names
end
def test_content_columns
content_columns = Topic.content_columns
- content_column_names = content_columns.map {|column| column.name}
+ content_column_names = content_columns.map(&:name)
assert_equal 13, content_columns.length
assert_equal %w(title author_name author_email_address written_on bonus_time last_read content important group approved parent_title created_at updated_at).sort, content_column_names.sort
end
@@ -209,6 +209,10 @@ class ReflectionTest < ActiveRecord::TestCase
assert_not_equal Object.new, Firm._reflections['clients']
end
+ def test_reflections_should_return_keys_as_strings
+ assert Category.reflections.keys.all? { |key| key.is_a? String }, "Model.reflections is expected to return string for keys"
+ end
+
def test_has_and_belongs_to_many_reflection
assert_equal :has_and_belongs_to_many, Category.reflections['posts'].macro
assert_equal :posts, Category.reflect_on_all_associations(:has_and_belongs_to_many).first.name
diff --git a/activerecord/test/cases/relation/merging_test.rb b/activerecord/test/cases/relation/merging_test.rb
index 8f40a1890d..eb76ef6328 100644
--- a/activerecord/test/cases/relation/merging_test.rb
+++ b/activerecord/test/cases/relation/merging_test.rb
@@ -2,6 +2,7 @@ require 'cases/helper'
require 'models/author'
require 'models/comment'
require 'models/developer'
+require 'models/computer'
require 'models/post'
require 'models/project'
require 'models/rating'
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index 410b5ba5a3..fc9637a167 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -7,6 +7,7 @@ require 'models/comment'
require 'models/author'
require 'models/entrant'
require 'models/developer'
+require 'models/computer'
require 'models/reply'
require 'models/company'
require 'models/bird'
@@ -248,7 +249,7 @@ class RelationTest < ActiveRecord::TestCase
def test_finding_with_reorder
topics = Topic.order('author_name').order('title').reorder('id').to_a
- topics_titles = topics.map{ |t| t.title }
+ topics_titles = topics.map(&:title)
assert_equal ['The First Topic', 'The Second Topic of the day', 'The Third Topic of the day', 'The Fourth Topic of the day', 'The Fifth Topic of the day'], topics_titles
end
@@ -440,7 +441,7 @@ class RelationTest < ActiveRecord::TestCase
where('project_id=1').to_a
assert_equal 3, developers_on_project_one.length
- developer_names = developers_on_project_one.map { |d| d.name }
+ developer_names = developers_on_project_one.map(&:name)
assert developer_names.include?('David')
assert developer_names.include?('Jamis')
end
@@ -651,8 +652,8 @@ class RelationTest < ActiveRecord::TestCase
expected_taggings = taggings(:welcome_general, :thinking_general)
assert_no_queries do
- assert_equal expected_taggings, author.taggings.distinct.sort_by { |t| t.id }
- assert_equal expected_taggings, author.taggings.uniq.sort_by { |t| t.id }
+ assert_equal expected_taggings, author.taggings.distinct.sort_by(&:id)
+ assert_equal expected_taggings, author.taggings.uniq.sort_by(&:id)
end
authors = Author.all
@@ -1702,7 +1703,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_unscope_removes_binds
- left = Post.where(id: Arel::Nodes::BindParam.new('?'))
+ left = Post.where(id: Arel::Nodes::BindParam.new)
column = Post.columns_hash['id']
left.bind_values += [[column, 20]]
diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb
index 2241c41f36..8731531f54 100644
--- a/activerecord/test/cases/schema_dumper_test.rb
+++ b/activerecord/test/cases/schema_dumper_test.rb
@@ -162,16 +162,6 @@ class SchemaDumperTest < ActiveRecord::TestCase
assert_no_match %r{create_table "schema_migrations"}, output
end
- def test_schema_dump_illegal_ignored_table_value
- stream = StringIO.new
- old_ignore_tables, ActiveRecord::SchemaDumper.ignore_tables = ActiveRecord::SchemaDumper.ignore_tables, [5]
- assert_raise(StandardError) do
- ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, stream)
- end
- ensure
- ActiveRecord::SchemaDumper.ignore_tables = old_ignore_tables
- end
-
def test_schema_dumps_index_columns_in_right_order
index_definition = standard_dump.split(/\n/).grep(/add_index.*companies/).first.strip
if current_adapter?(:MysqlAdapter, :Mysql2Adapter, :PostgreSQLAdapter)
@@ -271,13 +261,6 @@ class SchemaDumperTest < ActiveRecord::TestCase
end
end
- def test_schema_dump_includes_json_shorthand_definition
- output = standard_dump
- if %r{create_table "postgresql_json_data_type"} =~ output
- assert_match %r|t.json "json_data", default: {}|, output
- end
- end
-
def test_schema_dump_includes_inet_shorthand_definition
output = standard_dump
if %r{create_table "postgresql_network_addresses"} =~ output
diff --git a/activerecord/test/cases/scoping/default_scoping_test.rb b/activerecord/test/cases/scoping/default_scoping_test.rb
index a5c4404175..5bdebe6ac7 100644
--- a/activerecord/test/cases/scoping/default_scoping_test.rb
+++ b/activerecord/test/cases/scoping/default_scoping_test.rb
@@ -2,13 +2,14 @@ require 'cases/helper'
require 'models/post'
require 'models/comment'
require 'models/developer'
+require 'models/computer'
class DefaultScopingTest < ActiveRecord::TestCase
fixtures :developers, :posts, :comments
def test_default_scope
- expected = Developer.all.merge!(:order => 'salary DESC').to_a.collect { |dev| dev.salary }
- received = DeveloperOrderedBySalary.all.collect { |dev| dev.salary }
+ expected = Developer.all.merge!(:order => 'salary DESC').to_a.collect(&:salary)
+ received = DeveloperOrderedBySalary.all.collect(&:salary)
assert_equal expected, received
end
@@ -85,14 +86,14 @@ class DefaultScopingTest < ActiveRecord::TestCase
end
def test_scope_overwrites_default
- expected = Developer.all.merge!(order: 'salary DESC, name DESC').to_a.collect { |dev| dev.name }
- received = DeveloperOrderedBySalary.by_name.to_a.collect { |dev| dev.name }
+ expected = Developer.all.merge!(order: 'salary DESC, name DESC').to_a.collect(&:name)
+ received = DeveloperOrderedBySalary.by_name.to_a.collect(&:name)
assert_equal expected, received
end
def test_reorder_overrides_default_scope_order
- expected = Developer.order('name DESC').collect { |dev| dev.name }
- received = DeveloperOrderedBySalary.reorder('name DESC').collect { |dev| dev.name }
+ expected = Developer.order('name DESC').collect(&:name)
+ received = DeveloperOrderedBySalary.reorder('name DESC').collect(&:name)
assert_equal expected, received
end
@@ -145,34 +146,34 @@ class DefaultScopingTest < ActiveRecord::TestCase
end
def test_unscope_multiple_where_clauses
- expected = Developer.order('salary DESC').collect { |dev| dev.name }
- received = DeveloperOrderedBySalary.where(name: 'Jamis').where(id: 1).unscope(where: [:name, :id]).collect { |dev| dev.name }
+ expected = Developer.order('salary DESC').collect(&:name)
+ received = DeveloperOrderedBySalary.where(name: 'Jamis').where(id: 1).unscope(where: [:name, :id]).collect(&:name)
assert_equal expected, received
end
def test_unscope_string_where_clauses_involved
dev_relation = Developer.order('salary DESC').where("created_at > ?", 1.year.ago)
- expected = dev_relation.collect { |dev| dev.name }
+ expected = dev_relation.collect(&:name)
dev_ordered_relation = DeveloperOrderedBySalary.where(name: 'Jamis').where("created_at > ?", 1.year.ago)
- received = dev_ordered_relation.unscope(where: [:name]).collect { |dev| dev.name }
+ received = dev_ordered_relation.unscope(where: [:name]).collect(&:name)
assert_equal expected, received
end
def test_unscope_with_grouping_attributes
- expected = Developer.order('salary DESC').collect { |dev| dev.name }
- received = DeveloperOrderedBySalary.group(:name).unscope(:group).collect { |dev| dev.name }
+ expected = Developer.order('salary DESC').collect(&:name)
+ received = DeveloperOrderedBySalary.group(:name).unscope(:group).collect(&:name)
assert_equal expected, received
- expected_2 = Developer.order('salary DESC').collect { |dev| dev.name }
- received_2 = DeveloperOrderedBySalary.group("name").unscope(:group).collect { |dev| dev.name }
+ expected_2 = Developer.order('salary DESC').collect(&:name)
+ received_2 = DeveloperOrderedBySalary.group("name").unscope(:group).collect(&:name)
assert_equal expected_2, received_2
end
def test_unscope_with_limit_in_query
- expected = Developer.order('salary DESC').collect { |dev| dev.name }
- received = DeveloperOrderedBySalary.limit(1).unscope(:limit).collect { |dev| dev.name }
+ expected = Developer.order('salary DESC').collect(&:name)
+ received = DeveloperOrderedBySalary.limit(1).unscope(:limit).collect(&:name)
assert_equal expected, received
end
@@ -182,42 +183,42 @@ class DefaultScopingTest < ActiveRecord::TestCase
end
def test_unscope_reverse_order
- expected = Developer.all.collect { |dev| dev.name }
- received = Developer.order('salary DESC').reverse_order.unscope(:order).collect { |dev| dev.name }
+ expected = Developer.all.collect(&:name)
+ received = Developer.order('salary DESC').reverse_order.unscope(:order).collect(&:name)
assert_equal expected, received
end
def test_unscope_select
- expected = Developer.order('salary ASC').collect { |dev| dev.name }
- received = Developer.order('salary DESC').reverse_order.select(:name).unscope(:select).collect { |dev| dev.name }
+ expected = Developer.order('salary ASC').collect(&:name)
+ received = Developer.order('salary DESC').reverse_order.select(:name).unscope(:select).collect(&:name)
assert_equal expected, received
- expected_2 = Developer.all.collect { |dev| dev.id }
- received_2 = Developer.select(:name).unscope(:select).collect { |dev| dev.id }
+ expected_2 = Developer.all.collect(&:id)
+ received_2 = Developer.select(:name).unscope(:select).collect(&:id)
assert_equal expected_2, received_2
end
def test_unscope_offset
- expected = Developer.all.collect { |dev| dev.name }
- received = Developer.offset(5).unscope(:offset).collect { |dev| dev.name }
+ expected = Developer.all.collect(&:name)
+ received = Developer.offset(5).unscope(:offset).collect(&:name)
assert_equal expected, received
end
def test_unscope_joins_and_select_on_developers_projects
- expected = Developer.all.collect { |dev| dev.name }
- received = Developer.joins('JOIN developers_projects ON id = developer_id').select(:id).unscope(:joins, :select).collect { |dev| dev.name }
+ expected = Developer.all.collect(&:name)
+ received = Developer.joins('JOIN developers_projects ON id = developer_id').select(:id).unscope(:joins, :select).collect(&:name)
assert_equal expected, received
end
def test_unscope_includes
- expected = Developer.all.collect { |dev| dev.name }
- received = Developer.includes(:projects).select(:id).unscope(:includes, :select).collect { |dev| dev.name }
+ expected = Developer.all.collect(&:name)
+ received = Developer.includes(:projects).select(:id).unscope(:includes, :select).collect(&:name)
assert_equal expected, received
end
def test_unscope_having
- expected = DeveloperOrderedBySalary.all.collect { |dev| dev.name }
- received = DeveloperOrderedBySalary.having("name IN ('Jamis', 'David')").unscope(:having).collect { |dev| dev.name }
+ expected = DeveloperOrderedBySalary.all.collect(&:name)
+ received = DeveloperOrderedBySalary.having("name IN ('Jamis', 'David')").unscope(:having).collect(&:name)
assert_equal expected, received
end
@@ -280,8 +281,8 @@ class DefaultScopingTest < ActiveRecord::TestCase
end
def test_order_in_default_scope_should_not_prevail
- expected = Developer.all.merge!(order: 'salary desc').to_a.collect { |dev| dev.salary }
- received = DeveloperOrderedBySalary.all.merge!(order: 'salary').to_a.collect { |dev| dev.salary }
+ expected = Developer.all.merge!(order: 'salary desc').to_a.collect(&:salary)
+ received = DeveloperOrderedBySalary.all.merge!(order: 'salary').to_a.collect(&:salary)
assert_equal expected, received
end
diff --git a/activerecord/test/cases/scoping/named_scoping_test.rb b/activerecord/test/cases/scoping/named_scoping_test.rb
index c2816c3670..41f3449828 100644
--- a/activerecord/test/cases/scoping/named_scoping_test.rb
+++ b/activerecord/test/cases/scoping/named_scoping_test.rb
@@ -5,6 +5,7 @@ require 'models/comment'
require 'models/reply'
require 'models/author'
require 'models/developer'
+require 'models/computer'
class NamedScopingTest < ActiveRecord::TestCase
fixtures :posts, :authors, :topics, :comments, :author_addresses
diff --git a/activerecord/test/cases/scoping/relation_scoping_test.rb b/activerecord/test/cases/scoping/relation_scoping_test.rb
index 73835c85a8..d7bcbf6203 100644
--- a/activerecord/test/cases/scoping/relation_scoping_test.rb
+++ b/activerecord/test/cases/scoping/relation_scoping_test.rb
@@ -2,6 +2,7 @@ require "cases/helper"
require 'models/post'
require 'models/author'
require 'models/developer'
+require 'models/computer'
require 'models/project'
require 'models/comment'
require 'models/category'
diff --git a/activerecord/test/cases/test_case.rb b/activerecord/test/cases/test_case.rb
index eb44c4a83c..5ba17359f0 100644
--- a/activerecord/test/cases/test_case.rb
+++ b/activerecord/test/cases/test_case.rb
@@ -43,7 +43,7 @@ module ActiveRecord
patterns_to_match.each do |pattern|
failed_patterns << pattern unless SQLCounter.log_all.any?{ |sql| pattern === sql }
end
- assert failed_patterns.empty?, "Query pattern(s) #{failed_patterns.map{ |p| p.inspect }.join(', ')} not found.#{SQLCounter.log.size == 0 ? '' : "\nQueries:\n#{SQLCounter.log.join("\n")}"}"
+ assert failed_patterns.empty?, "Query pattern(s) #{failed_patterns.map(&:inspect).join(', ')} not found.#{SQLCounter.log.size == 0 ? '' : "\nQueries:\n#{SQLCounter.log.join("\n")}"}"
end
def assert_queries(num = 1, options = {})
diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb
index abf6becc17..db474c63a4 100644
--- a/activerecord/test/cases/timestamp_test.rb
+++ b/activerecord/test/cases/timestamp_test.rb
@@ -1,6 +1,7 @@
require 'cases/helper'
require 'support/ddl_helper'
require 'models/developer'
+require 'models/computer'
require 'models/owner'
require 'models/pet'
require 'models/toy'
diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb
index 5cccf2dda5..72c07d8aea 100644
--- a/activerecord/test/cases/transactions_test.rb
+++ b/activerecord/test/cases/transactions_test.rb
@@ -2,6 +2,7 @@ require "cases/helper"
require 'models/topic'
require 'models/reply'
require 'models/developer'
+require 'models/computer'
require 'models/book'
require 'models/author'
require 'models/post'
@@ -12,7 +13,7 @@ class TransactionTest < ActiveRecord::TestCase
fixtures :topics, :developers, :authors, :posts
def setup
- @first, @second = Topic.find(1, 2).sort_by { |t| t.id }
+ @first, @second = Topic.find(1, 2).sort_by(&:id)
end
def test_persisted_in_a_model_with_custom_primary_key_after_failed_save
@@ -698,7 +699,7 @@ if current_adapter?(:PostgreSQLAdapter)
end
end
- threads.each { |t| t.join }
+ threads.each(&:join)
end
end
@@ -746,7 +747,7 @@ if current_adapter?(:PostgreSQLAdapter)
Developer.connection.close
end
- threads.each { |t| t.join }
+ threads.each(&:join)
end
assert_equal original_salary, Developer.find(1).salary
diff --git a/activerecord/test/cases/type/integer_test.rb b/activerecord/test/cases/type/integer_test.rb
index 53d6a3a6aa..5942f77e18 100644
--- a/activerecord/test/cases/type/integer_test.rb
+++ b/activerecord/test/cases/type/integer_test.rb
@@ -68,7 +68,7 @@ module ActiveRecord
end
end
- test "very large numbers are in range" do
+ test "very large numbers are out of range" do
assert_raises(::RangeError) do
Integer.new.type_cast_from_user("9999999999999999999999999999999")
end
diff --git a/activerecord/test/cases/type/string_test.rb b/activerecord/test/cases/type/string_test.rb
index 420177ed49..4d78f287f1 100644
--- a/activerecord/test/cases/type/string_test.rb
+++ b/activerecord/test/cases/type/string_test.rb
@@ -4,8 +4,8 @@ module ActiveRecord
class StringTypeTest < ActiveRecord::TestCase
test "type casting" do
type = Type::String.new
- assert_equal "1", type.type_cast_from_user(true)
- assert_equal "0", type.type_cast_from_user(false)
+ assert_equal "t", type.type_cast_from_user(true)
+ assert_equal "f", type.type_cast_from_user(false)
assert_equal "123", type.type_cast_from_user(123)
end
diff --git a/activerecord/test/cases/type/type_map_test.rb b/activerecord/test/cases/type/type_map_test.rb
index 4e32f92dd0..172c6dfc4c 100644
--- a/activerecord/test/cases/type/type_map_test.rb
+++ b/activerecord/test/cases/type/type_map_test.rb
@@ -124,6 +124,53 @@ module ActiveRecord
assert_equal mapping.lookup(3), 'string'
assert_kind_of Type::Value, mapping.lookup(4)
end
+
+ def test_fetch
+ mapping = TypeMap.new
+ mapping.register_type(1, "string")
+
+ assert_equal "string", mapping.fetch(1) { "int" }
+ assert_equal "int", mapping.fetch(2) { "int" }
+ end
+
+ def test_fetch_yields_args
+ mapping = TypeMap.new
+
+ assert_equal "foo-1-2-3", mapping.fetch("foo", 1, 2, 3) { |*args| args.join("-") }
+ assert_equal "bar-1-2-3", mapping.fetch("bar", 1, 2, 3) { |*args| args.join("-") }
+ end
+
+ def test_fetch_memoizes
+ mapping = TypeMap.new
+
+ looked_up = false
+ mapping.register_type(1) do
+ fail if looked_up
+ looked_up = true
+ "string"
+ end
+
+ assert_equal "string", mapping.fetch(1)
+ assert_equal "string", mapping.fetch(1)
+ end
+
+ def test_fetch_memoizes_on_args
+ mapping = TypeMap.new
+ mapping.register_type("foo") { |*args| args.join("-") }
+
+ assert_equal "foo-1-2-3", mapping.fetch("foo", 1, 2, 3) { |*args| args.join("-") }
+ assert_equal "foo-2-3-4", mapping.fetch("foo", 2, 3, 4) { |*args| args.join("-") }
+ end
+
+ def test_register_clears_cache
+ mapping = TypeMap.new
+
+ mapping.register_type(1, "string")
+ mapping.lookup(1)
+ mapping.register_type(1, "int")
+
+ assert_equal "int", mapping.lookup(1)
+ end
end
end
end
diff --git a/activerecord/test/cases/validations/uniqueness_validation_test.rb b/activerecord/test/cases/validations/uniqueness_validation_test.rb
index 18221cc73d..c6b58d469d 100644
--- a/activerecord/test/cases/validations/uniqueness_validation_test.rb
+++ b/activerecord/test/cases/validations/uniqueness_validation_test.rb
@@ -41,7 +41,7 @@ class TopicWithUniqEvent < Topic
end
class UniquenessValidationTest < ActiveRecord::TestCase
- fixtures :topics, 'warehouse-things', :developers
+ fixtures :topics, 'warehouse-things'
repair_validations(Topic, Reply)
diff --git a/activerecord/test/cases/validations_repair_helper.rb b/activerecord/test/cases/validations_repair_helper.rb
index 2bbf0f23b3..b30666d876 100644
--- a/activerecord/test/cases/validations_repair_helper.rb
+++ b/activerecord/test/cases/validations_repair_helper.rb
@@ -5,9 +5,7 @@ module ActiveRecord
module ClassMethods
def repair_validations(*model_classes)
teardown do
- model_classes.each do |k|
- k.clear_validators!
- end
+ model_classes.each(&:clear_validators!)
end
end
end
@@ -15,9 +13,7 @@ module ActiveRecord
def repair_validations(*model_classes)
yield if block_given?
ensure
- model_classes.each do |k|
- k.clear_validators!
- end
+ model_classes.each(&:clear_validators!)
end
end
end
diff --git a/activerecord/test/cases/validations_test.rb b/activerecord/test/cases/validations_test.rb
index 55804f9576..db8159eff8 100644
--- a/activerecord/test/cases/validations_test.rb
+++ b/activerecord/test/cases/validations_test.rb
@@ -4,6 +4,7 @@ require 'models/topic'
require 'models/reply'
require 'models/person'
require 'models/developer'
+require 'models/computer'
require 'models/parrot'
require 'models/company'
diff --git a/activerecord/test/config.example.yml b/activerecord/test/config.example.yml
index ce30cff9e7..e3b55d640e 100644
--- a/activerecord/test/config.example.yml
+++ b/activerecord/test/config.example.yml
@@ -69,12 +69,6 @@ connections:
username: rails
encoding: utf8
- openbase:
- arunit:
- username: admin
- arunit2:
- username: admin
-
oracle:
arunit:
adapter: oracle_enhanced
diff --git a/activerecord/test/fixtures/bulbs.yml b/activerecord/test/fixtures/bulbs.yml
new file mode 100644
index 0000000000..e5ce2b796c
--- /dev/null
+++ b/activerecord/test/fixtures/bulbs.yml
@@ -0,0 +1,5 @@
+defaulty:
+ name: defaulty
+
+special:
+ name: special
diff --git a/activerecord/test/fixtures/computers.yml b/activerecord/test/fixtures/computers.yml
index 7281a4d768..ad5ae2ec71 100644
--- a/activerecord/test/fixtures/computers.yml
+++ b/activerecord/test/fixtures/computers.yml
@@ -3,3 +3,8 @@ workstation:
system: 'Linux'
developer: 1
extendedWarranty: 1
+
+laptop:
+ system: 'MacOS 1'
+ developer: 1
+ extendedWarranty: 1
diff --git a/activerecord/test/fixtures/developers.yml b/activerecord/test/fixtures/developers.yml
index 1a74563dc6..54b74e7a74 100644
--- a/activerecord/test/fixtures/developers.yml
+++ b/activerecord/test/fixtures/developers.yml
@@ -2,6 +2,7 @@ david:
id: 1
name: David
salary: 80000
+ shared_computers: laptop
jamis:
id: 2
diff --git a/activerecord/test/models/customer.rb b/activerecord/test/models/customer.rb
index 7e8e82542f..afe4b3d707 100644
--- a/activerecord/test/models/customer.rb
+++ b/activerecord/test/models/customer.rb
@@ -2,7 +2,7 @@ class Customer < ActiveRecord::Base
cattr_accessor :gps_conversion_was_run
composed_of :address, :mapping => [ %w(address_street street), %w(address_city city), %w(address_country country) ], :allow_nil => true
- composed_of :balance, :class_name => "Money", :mapping => %w(balance amount), :converter => Proc.new { |balance| balance.to_money }
+ composed_of :balance, :class_name => "Money", :mapping => %w(balance amount), :converter => Proc.new(&:to_money)
composed_of :gps_location, :allow_nil => true
composed_of :non_blank_gps_location, :class_name => "GpsLocation", :allow_nil => true, :mapping => %w(gps_location gps_location),
:converter => lambda { |gps| self.gps_conversion_was_run = true; gps.blank? ? nil : GpsLocation.new(gps)}
diff --git a/activerecord/test/models/developer.rb b/activerecord/test/models/developer.rb
index 3627cfdd09..d2a5a7fc49 100644
--- a/activerecord/test/models/developer.rb
+++ b/activerecord/test/models/developer.rb
@@ -15,6 +15,8 @@ class Developer < ActiveRecord::Base
accepts_nested_attributes_for :projects
+ has_and_belongs_to_many :shared_computers, class_name: "Computer"
+
has_and_belongs_to_many :projects_extended_by_name,
-> { extending(DeveloperProjectsAssociationExtension) },
:class_name => "Project",
diff --git a/activerecord/test/models/pirate.rb b/activerecord/test/models/pirate.rb
index 90a3c3ecee..641a33f9be 100644
--- a/activerecord/test/models/pirate.rb
+++ b/activerecord/test/models/pirate.rb
@@ -36,8 +36,8 @@ class Pirate < ActiveRecord::Base
has_one :foo_bulb, -> { where :name => 'foo' }, :foreign_key => :car_id, :class_name => "Bulb"
- accepts_nested_attributes_for :parrots, :birds, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
- accepts_nested_attributes_for :ship, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
+ accepts_nested_attributes_for :parrots, :birds, :allow_destroy => true, :reject_if => proc(&:empty?)
+ accepts_nested_attributes_for :ship, :allow_destroy => true, :reject_if => proc(&:empty?)
accepts_nested_attributes_for :update_only_ship, :update_only => true
accepts_nested_attributes_for :parrots_with_method_callbacks, :parrots_with_proc_callbacks,
:birds_with_method_callbacks, :birds_with_proc_callbacks, :allow_destroy => true
diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb
index 36cf221d45..a9996e5236 100644
--- a/activerecord/test/models/post.rb
+++ b/activerecord/test/models/post.rb
@@ -78,6 +78,7 @@ class Post < ActiveRecord::Base
has_one :very_special_comment
has_one :very_special_comment_with_post, -> { includes(:post) }, :class_name => "VerySpecialComment"
+ has_one :very_special_comment_with_post_with_joins, -> { joins(:post).order('posts.id') }, class_name: "VerySpecialComment"
has_many :special_comments
has_many :nonexistant_comments, -> { where 'comments.id < 0' }, :class_name => 'Comment'
diff --git a/activerecord/test/models/ship.rb b/activerecord/test/models/ship.rb
index 77a4728d0b..5f618a50d2 100644
--- a/activerecord/test/models/ship.rb
+++ b/activerecord/test/models/ship.rb
@@ -6,7 +6,7 @@ class Ship < ActiveRecord::Base
has_many :parts, :class_name => 'ShipPart'
accepts_nested_attributes_for :parts, :allow_destroy => true
- accepts_nested_attributes_for :pirate, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? }
+ accepts_nested_attributes_for :pirate, :allow_destroy => true, :reject_if => proc(&:empty?)
accepts_nested_attributes_for :update_only_pirate, :update_only => true
validates_presence_of :name
diff --git a/activerecord/test/schema/postgresql_specific_schema.rb b/activerecord/test/schema/postgresql_specific_schema.rb
index e9294a11b9..7c3b170c08 100644
--- a/activerecord/test/schema/postgresql_specific_schema.rb
+++ b/activerecord/test/schema/postgresql_specific_schema.rb
@@ -1,7 +1,9 @@
ActiveRecord::Schema.define do
- %w(postgresql_tsvectors postgresql_hstores postgresql_arrays postgresql_moneys postgresql_numbers postgresql_times postgresql_network_addresses postgresql_uuids postgresql_ltrees
- postgresql_oids postgresql_xml_data_type defaults geometrics postgresql_timestamp_with_zones postgresql_partitioned_table postgresql_partitioned_table_parent postgresql_json_data_type postgresql_citext).each do |table_name|
+ %w(postgresql_tsvectors postgresql_hstores postgresql_arrays postgresql_moneys postgresql_numbers postgresql_times
+ postgresql_network_addresses postgresql_uuids postgresql_ltrees postgresql_oids postgresql_xml_data_type defaults
+ geometrics postgresql_timestamp_with_zones postgresql_partitioned_table postgresql_partitioned_table_parent
+ postgresql_citext).each do |table_name|
execute "DROP TABLE IF EXISTS #{quote_table_name table_name}"
end
@@ -108,15 +110,6 @@ _SQL
_SQL
end
- if 't' == select_value("select 'json'=ANY(select typname from pg_type)")
- execute <<_SQL
- CREATE TABLE postgresql_json_data_type (
- id SERIAL PRIMARY KEY,
- json_data json default '{}'::json
- );
-_SQL
- end
-
execute <<_SQL
CREATE TABLE postgresql_numbers (
id SERIAL PRIMARY KEY,
diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb
index 539a0d2a49..720a127585 100644
--- a/activerecord/test/schema/schema.rb
+++ b/activerecord/test/schema/schema.rb
@@ -228,6 +228,11 @@ ActiveRecord::Schema.define do
t.integer :extendedWarranty, null: false
end
+ create_table :computers_developers, id: false, force: true do |t|
+ t.references :computer
+ t.references :developer
+ end
+
create_table :contracts, force: true do |t|
t.integer :developer_id
t.integer :company_id
diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md
index b2b3cf4bd4..810fc22cf5 100644
--- a/activesupport/CHANGELOG.md
+++ b/activesupport/CHANGELOG.md
@@ -1,382 +1 @@
-* `String#remove` and `String#remove!` accept multiple arguments.
-
- *Pavel Pravosud*
-
-* TimeWithZone#strftime now delegates every directive to Time#strftime except for '%Z',
- it also now correctly handles escaped '%' characters placed just before time zone related directives.
-
- *Pablo Herrero*
-
-* Corrected Inflector#underscore handling of multiple successive acroynms.
-
- *James Le Cuirot*
-
-* Delegation now works with ruby reserved words passed to `:to` option.
-
- Fixes #16956.
-
- *Agis Anastasopoulos*
-
-* Added method `#eql?` to `ActiveSupport::Duration`, in addition to `#==`.
-
- Currently, the following returns `false`, contrary to expectation:
-
- 1.minute.eql?(1.minute)
-
- Adding method `#eql?` will make this behave like expected. Method `#eql?` is
- just a bit stricter than `#==`, as it checks whether the argument is also a duration. Their
- parts may be different though.
-
- 1.minute.eql?(60.seconds) # => true
- 1.minute.eql?(60) # => false
-
- *Joost Lubach*
-
-* `Time#change` can now change nanoseconds (`:nsec`) as a higher-precision
- alternative to microseconds (`:usec`).
-
- *Agis Anastasooulos*
-
-* `MessageVerifier.new` raises an appropriate exception if the secret is `nil`.
- This prevents `MessageVerifier#generate` from raising a cryptic error later on.
-
- *Kostiantyn Kahanskyi*
-
-* Introduced new configuration option `active_support.test_order` for
- specifying the order in which test cases are executed. This option currently defaults
- to `:sorted` but will be changed to `:random` in Rails 5.0.
-
- *Akira Matsuda*, *Godfrey Chan*
-
-* Fixed a bug in `Inflector#underscore` where acroynms in nested constant names
- are incorrectly parsed as camelCase.
-
- Fixes #8015.
-
- *Fred Wu*, *Matthew Draper*
-
-* Make `Time#change` throw an exception if the `:usec` option is out of range and
- the time has an offset other than UTC or local.
-
- *Agis Anastasopoulos*
-
-* `Method` objects now report themselves as not `duplicable?`. This allows
- hashes and arrays containing `Method` objects to be `deep_dup`ed.
-
- *Peter Jaros*
-
-* `determine_constant_from_test_name` does no longer shadow `NameError`s
- which happens during constant autoloading.
-
- Fixes #9933.
-
- *Guo Xiang Tan*
-
-* Added instance_eval version to Object#try and Object#try!, so you can do this:
-
- person.try { name.first }
-
- instead of:
-
- person.try { |person| person.name.first }
-
- *DHH*, *Ari Pollak*
-
-* Fix the `ActiveSupport::Duration#instance_of?` method to return the right
- value with the class itself since it was previously delegated to the
- internal value.
-
- *Robin Dupret*
-
-* Fix rounding errors with `#travel_to` by resetting the usec on any passed time to zero, so we only travel
- with per-second precision, not anything deeper than that.
-
- *DHH*
-
-* Fix DateTime comparison with `DateTime::Infinity` object.
-
- *Rafael Mendonça França*
-
-* Added Object#itself which returns the object itself. Useful when dealing with a chaining scenario, like Active Record scopes:
-
- Event.public_send(state.presence_in([ :trashed, :drafted ]) || :itself).order(:created_at)
-
- *DHH*
-
-* `Object#with_options` executes block in merging option context when
- explicit receiver in not passed.
-
- *Pavel Pravosud*
-
-* Fixed a compatibility issue with the `Oj` gem when cherry-picking the file
- `active_support/core_ext/object/json` without requiring `active_support/json`.
-
- Fixes #16131.
-
- *Godfrey Chan*
-
-* Make `Hash#with_indifferent_access` copy the default proc too.
-
- *arthurnn*, *Xanders*
-
-* Add `String#truncate_words` to truncate a string by a number of words.
-
- *Mohamed Osama*
-
-* Deprecate `capture` and `quietly`.
-
- These methods are not thread safe and may cause issues when used in threaded environments.
- To avoid problems we are deprecating them.
-
- *Tom Meier*
-
-* `DateTime#to_f` now preserves the fractional seconds instead of always
- rounding to `.0`.
-
- Fixes #15994.
-
- *John Paul Ashenfelter*
-
-* Add `Hash#transform_values` to simplify a common pattern where the values of a
- hash must change, but the keys are left the same.
-
- *Sean Griffin*
-
-* Always instrument `ActiveSupport::Cache`.
-
- Since `ActiveSupport::Notifications` only instruments items when there
- are attached subscribers, we don't need to disable instrumentation.
-
- *Peter Wagenet*
-
-* Make the `apply_inflections` method case-insensitive when checking
- whether a word is uncountable or not.
-
- *Robin Dupret*
-
-* Make Dependencies pass a name to NameError error.
-
- *arthurnn*
-
-* Fixed `ActiveSupport::Cache::FileStore` exploding with long paths.
-
- *Adam Panzer / Michael Grosser*
-
-* Fixed `ActiveSupport::TimeWithZone#-` so precision is not unnecessarily lost
- when working with objects with a nanosecond component.
-
- `ActiveSupport::TimeWithZone#-` should return the same result as if we were
- using `Time#-`:
-
- Time.now.end_of_day - Time.now.beginning_of_day # => 86399.999999999
-
- Before:
-
- Time.zone.now.end_of_day.nsec # => 999999999
- Time.zone.now.end_of_day - Time.zone.now.beginning_of_day # => 86400.0
-
- After:
-
- Time.zone.now.end_of_day - Time.zone.now.beginning_of_day
- # => 86399.999999999
-
- *Gordon Chan*
-
-* Fixed precision error in NumberHelper when using Rationals.
-
- Before:
-
- ActiveSupport::NumberHelper.number_to_rounded Rational(1000, 3), precision: 2
- # => "330.00"
-
- After:
-
- ActiveSupport::NumberHelper.number_to_rounded Rational(1000, 3), precision: 2
- # => "333.33"
-
- See #15379.
-
- *Juanjo Bazán*
-
-* Removed deprecated `Numeric#ago` and friends
-
- Replacements:
-
- 5.ago => 5.seconds.ago
- 5.until => 5.seconds.until
- 5.since => 5.seconds.since
- 5.from_now => 5.seconds.from_now
-
- See #12389 for the history and rationale behind this.
-
- *Godfrey Chan*
-
-* DateTime `advance` now supports partial days.
-
- Before:
-
- DateTime.now.advance(days: 1, hours: 12)
-
- After:
-
- DateTime.now.advance(days: 1.5)
-
- Fixes #12005.
-
- *Shay Davidson*
-
-* `Hash#deep_transform_keys` and `Hash#deep_transform_keys!` now transform hashes
- in nested arrays. This change also applies to `Hash#deep_stringify_keys`,
- `Hash#deep_stringify_keys!`, `Hash#deep_symbolize_keys` and
- `Hash#deep_symbolize_keys!`.
-
- *OZAWA Sakuro*
-
-* Fixed confusing `DelegationError` in `Module#delegate`.
-
- See #15186.
-
- *Vladimir Yarotsky*
-
-* Fixed `ActiveSupport::Subscriber` so that no duplicate subscriber is created
- when a subscriber method is redefined.
-
- *Dennis Schön*
-
-* Remove deprecated string based terminators for `ActiveSupport::Callbacks`.
-
- *Eileen M. Uchitelle*
-
-* Fixed an issue when using
- `ActiveSupport::NumberHelper::NumberToDelimitedConverter` to
- convert a value that is an `ActiveSupport::SafeBuffer` introduced
- in 2da9d67.
-
- See #15064.
-
- *Mark J. Titorenko*
-
-* `TimeZone#parse` defaults the day of the month to '1' if any other date
- components are specified. This is more consistent with the behavior of
- `Time#parse`.
-
- *Ulysse Carion*
-
-* `humanize` strips leading underscores, if any.
-
- Before:
-
- '_id'.humanize # => ""
-
- After:
-
- '_id'.humanize # => "Id"
-
- *Xavier Noria*
-
-* Fixed backward compatibility issues introduced in 326e652.
-
- Empty Hash or Array should not be present in serialization result.
-
- {a: []}.to_query # => ""
- {a: {}}.to_query # => ""
-
- For more info see #14948.
-
- *Bogdan Gusiev*
-
-* Add `Digest::UUID::uuid_v3` and `Digest::UUID::uuid_v5` to support stable
- UUID fixtures on PostgreSQL.
-
- *Roderick van Domburg*
-
-* Fixed `ActiveSupport::Duration#eql?` so that `1.second.eql?(1.second)` is
- true.
-
- This fixes the current situation of:
-
- 1.second.eql?(1.second) # => false
-
- `eql?` also requires that the other object is an `ActiveSupport::Duration`.
- This requirement makes `ActiveSupport::Duration`'s behavior consistent with
- the behavior of Ruby's numeric types:
-
- 1.eql?(1.0) # => false
- 1.0.eql?(1) # => false
-
- 1.second.eql?(1) # => false (was true)
- 1.eql?(1.second) # => false
-
- { 1 => "foo", 1.0 => "bar" }
- # => { 1 => "foo", 1.0 => "bar" }
-
- { 1 => "foo", 1.second => "bar" }
- # now => { 1 => "foo", 1.second => "bar" }
- # was => { 1 => "bar" }
-
- And though the behavior of these hasn't changed, for reference:
-
- 1 == 1.0 # => true
- 1.0 == 1 # => true
-
- 1 == 1.second # => true
- 1.second == 1 # => true
-
- *Emily Dobervich*
-
-* `ActiveSupport::SafeBuffer#prepend` acts like `String#prepend` and modifies
- instance in-place, returning self. `ActiveSupport::SafeBuffer#prepend!` is
- deprecated.
-
- *Pavel Pravosud*
-
-* `HashWithIndifferentAccess` better respects `#to_hash` on objects it
- receives. In particular, `.new`, `#update`, `#merge`, and `#replace` accept
- objects which respond to `#to_hash`, even if those objects are not hashes
- directly.
-
- *Peter Jaros*
-
-* Deprecate `Class#superclass_delegating_accessor`, use `Class#class_attribute` instead.
-
- *Akshay Vishnoi*
-
-* Ensure classes which `include Enumerable` get `#to_json` in addition to
- `#as_json`.
-
- *Sammy Larbi*
-
-* Change the signature of `fetch_multi` to return a hash rather than an
- array. This makes it consistent with the output of `read_multi`.
-
- *Parker Selbert*
-
-* Introduce `Concern#class_methods` as a sleek alternative to clunky
- `module ClassMethods`. Add `Kernel#concern` to define at the toplevel
- without chunky `module Foo; extend ActiveSupport::Concern` boilerplate.
-
- # app/models/concerns/authentication.rb
- concern :Authentication do
- included do
- after_create :generate_private_key
- end
-
- class_methods do
- def authenticate(credentials)
- # ...
- end
- end
-
- def generate_private_key
- # ...
- end
- end
-
- # app/models/user.rb
- class User < ActiveRecord::Base
- include Authentication
- end
-
- *Jeremy Kemper*
-
-Please check [4-1-stable](https://github.com/rails/rails/blob/4-1-stable/activesupport/CHANGELOG.md) for previous changes.
+Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/activesupport/CHANGELOG.md) for previous changes.
diff --git a/activesupport/activesupport.gemspec b/activesupport/activesupport.gemspec
index 80d1d35888..f86f5133fc 100644
--- a/activesupport/activesupport.gemspec
+++ b/activesupport/activesupport.gemspec
@@ -7,7 +7,7 @@ Gem::Specification.new do |s|
s.summary = 'A toolkit of support libraries and Ruby core extensions extracted from the Rails framework.'
s.description = 'A toolkit of support libraries and Ruby core extensions extracted from the Rails framework. Rich support for multibyte strings, internationalization, time zones, and testing.'
- s.required_ruby_version = '>= 1.9.3'
+ s.required_ruby_version = '>= 2.1.0'
s.license = 'MIT'
diff --git a/activesupport/bin/generate_tables b/activesupport/bin/generate_tables
index f39e89b7d0..71a6b78652 100755
--- a/activesupport/bin/generate_tables
+++ b/activesupport/bin/generate_tables
@@ -55,7 +55,7 @@ module ActiveSupport
codepoint.combining_class = Integer($4)
#codepoint.bidi_class = $5
codepoint.decomp_type = $7
- codepoint.decomp_mapping = ($8=='') ? nil : $8.split.collect { |element| element.hex }
+ codepoint.decomp_mapping = ($8=='') ? nil : $8.split.collect(&:hex)
#codepoint.bidi_mirrored = ($13=='Y') ? true : false
codepoint.uppercase_mapping = ($16=='') ? 0 : $16.hex
codepoint.lowercase_mapping = ($17=='') ? 0 : $17.hex
diff --git a/activesupport/lib/active_support/core_ext/array/conversions.rb b/activesupport/lib/active_support/core_ext/array/conversions.rb
index 76ffd23ed1..080e3b5ef7 100644
--- a/activesupport/lib/active_support/core_ext/array/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/array/conversions.rb
@@ -92,7 +92,7 @@ class Array
if empty?
'null'
else
- collect { |element| element.id }.join(',')
+ collect(&:id).join(',')
end
else
to_default_s
diff --git a/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb
index 843c592669..234283e792 100644
--- a/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb
@@ -3,14 +3,13 @@ require 'bigdecimal/util'
class BigDecimal
DEFAULT_STRING_FORMAT = 'F'
- def to_formatted_s(*args)
- if args[0].is_a?(Symbol)
- super
+ alias_method :to_default_s, :to_s
+
+ def to_s(format = nil, options = nil)
+ if format.is_a?(Symbol)
+ to_formatted_s(format, options || {})
else
- format = args[0] || DEFAULT_STRING_FORMAT
- _original_to_s(format)
+ to_default_s(format || DEFAULT_STRING_FORMAT)
end
end
- alias_method :_original_to_s, :to_s
- alias_method :to_s, :to_formatted_s
end
diff --git a/activesupport/lib/active_support/core_ext/hash/compact.rb b/activesupport/lib/active_support/core_ext/hash/compact.rb
index 6566215a4d..5dc9a05ec7 100644
--- a/activesupport/lib/active_support/core_ext/hash/compact.rb
+++ b/activesupport/lib/active_support/core_ext/hash/compact.rb
@@ -1,6 +1,6 @@
class Hash
# Returns a hash with non +nil+ values.
- #
+ #
# hash = { a: true, b: false, c: nil}
# hash.compact # => { a: true, b: false}
# hash # => { a: true, b: false, c: nil}
@@ -8,9 +8,9 @@ class Hash
def compact
self.select { |_, value| !value.nil? }
end
-
+
# Replaces current hash with non +nil+ values.
- #
+ #
# hash = { a: true, b: false, c: nil}
# hash.compact! # => { a: true, b: false}
# hash # => { a: true, b: false}
diff --git a/activesupport/lib/active_support/core_ext/hash/except.rb b/activesupport/lib/active_support/core_ext/hash/except.rb
index 682d089881..6e397abf51 100644
--- a/activesupport/lib/active_support/core_ext/hash/except.rb
+++ b/activesupport/lib/active_support/core_ext/hash/except.rb
@@ -1,13 +1,19 @@
class Hash
- # Returns a hash that includes everything but the given keys. This is useful for
- # limiting a set of parameters to everything but a few known toggles:
+ # Returns a hash that includes everything but the given keys.
+ # hash = { a: true, b: false, c: nil}
+ # hash.except(:c) # => { a: true, b: false}
+ # hash # => { a: true, b: false, c: nil}
#
+ # This is useful for limiting a set of parameters to everything but a few known toggles:
# @person.update(params[:person].except(:admin))
def except(*keys)
dup.except!(*keys)
end
# Replaces the hash without the given keys.
+ # hash = { a: true, b: false, c: nil}
+ # hash.except!(:c) # => { a: true, b: false}
+ # hash # => { a: true, b: false }
def except!(*keys)
keys.each { |key| delete(key) }
self
diff --git a/activesupport/lib/active_support/core_ext/hash/keys.rb b/activesupport/lib/active_support/core_ext/hash/keys.rb
index f4105f66b0..9297a59c46 100644
--- a/activesupport/lib/active_support/core_ext/hash/keys.rb
+++ b/activesupport/lib/active_support/core_ext/hash/keys.rb
@@ -31,13 +31,13 @@ class Hash
# hash.stringify_keys
# # => {"name"=>"Rob", "age"=>"28"}
def stringify_keys
- transform_keys{ |key| key.to_s }
+ transform_keys(&:to_s)
end
# Destructively convert all keys to strings. Same as
# +stringify_keys+, but modifies +self+.
def stringify_keys!
- transform_keys!{ |key| key.to_s }
+ transform_keys!(&:to_s)
end
# Returns a new hash with all keys converted to symbols, as long as
@@ -105,14 +105,14 @@ class Hash
# hash.deep_stringify_keys
# # => {"person"=>{"name"=>"Rob", "age"=>"28"}}
def deep_stringify_keys
- deep_transform_keys{ |key| key.to_s }
+ deep_transform_keys(&:to_s)
end
# Destructively convert all keys to strings.
# This includes the keys from the root hash and from all
# nested hashes and arrays.
def deep_stringify_keys!
- deep_transform_keys!{ |key| key.to_s }
+ deep_transform_keys!(&:to_s)
end
# Returns a new hash with all keys converted to symbols, as long as
diff --git a/activesupport/lib/active_support/core_ext/numeric/conversions.rb b/activesupport/lib/active_support/core_ext/numeric/conversions.rb
index 6d3635c69a..0c8ff79237 100644
--- a/activesupport/lib/active_support/core_ext/numeric/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/numeric/conversions.rb
@@ -118,18 +118,28 @@ class Numeric
end
end
- [Float, Fixnum, Bignum, BigDecimal].each do |klass|
- klass.send(:alias_method, :to_default_s, :to_s)
-
- klass.send(:define_method, :to_s) do |*args|
- if args[0].is_a?(Symbol)
- format = args[0]
- options = args[1] || {}
+ [Fixnum, Bignum].each do |klass|
+ klass.class_eval do
+ alias_method :to_default_s, :to_s
+ def to_s(base_or_format = 10, options = nil)
+ if base_or_format.is_a?(Symbol)
+ to_formatted_s(base_or_format, options || {})
+ else
+ to_default_s(base_or_format)
+ end
+ end
+ end
+ end
- self.to_formatted_s(format, options)
+ Float.class_eval do
+ alias_method :to_default_s, :to_s
+ def to_s(*args)
+ if args.empty?
+ to_default_s
else
- to_default_s(*args)
+ to_formatted_s(*args)
end
end
end
+
end
diff --git a/activesupport/lib/active_support/core_ext/object/deep_dup.rb b/activesupport/lib/active_support/core_ext/object/deep_dup.rb
index 2e99f4a1b8..0191d2e973 100644
--- a/activesupport/lib/active_support/core_ext/object/deep_dup.rb
+++ b/activesupport/lib/active_support/core_ext/object/deep_dup.rb
@@ -25,7 +25,7 @@ class Array
# array[1][2] # => nil
# dup[1][2] # => 4
def deep_dup
- map { |it| it.deep_dup }
+ map(&:deep_dup)
end
end
diff --git a/activesupport/lib/active_support/core_ext/object/instance_variables.rb b/activesupport/lib/active_support/core_ext/object/instance_variables.rb
index 755e1c6b16..593a7a4940 100644
--- a/activesupport/lib/active_support/core_ext/object/instance_variables.rb
+++ b/activesupport/lib/active_support/core_ext/object/instance_variables.rb
@@ -23,6 +23,6 @@ class Object
#
# C.new(0, 1).instance_variable_names # => ["@y", "@x"]
def instance_variable_names
- instance_variables.map { |var| var.to_s }
+ instance_variables.map(&:to_s)
end
end
diff --git a/activesupport/lib/active_support/core_ext/object/to_query.rb b/activesupport/lib/active_support/core_ext/object/to_query.rb
index ccd568bbf5..ec5ace4e16 100644
--- a/activesupport/lib/active_support/core_ext/object/to_query.rb
+++ b/activesupport/lib/active_support/core_ext/object/to_query.rb
@@ -38,7 +38,7 @@ class Array
# Calls <tt>to_param</tt> on all its elements and joins the result with
# slashes. This is used by <tt>url_for</tt> in Action Pack.
def to_param
- collect { |e| e.to_param }.join '/'
+ collect(&:to_param).join '/'
end
# Converts an array into a string suitable for use as a URL query string,
diff --git a/activesupport/lib/active_support/core_ext/string/filters.rb b/activesupport/lib/active_support/core_ext/string/filters.rb
index 499b9b26bc..096292dc58 100644
--- a/activesupport/lib/active_support/core_ext/string/filters.rb
+++ b/activesupport/lib/active_support/core_ext/string/filters.rb
@@ -13,6 +13,9 @@ class String
end
# Performs a destructive squish. See String#squish.
+ # str = " foo bar \n \t boo"
+ # str.squish! # => "foo bar boo"
+ # str # => "foo bar boo"
def squish!
gsub!(/\A[[:space:]]+/, '')
gsub!(/[[:space:]]+\z/, '')
@@ -21,11 +24,17 @@ class String
end
# Returns a new string with all occurrences of the patterns removed.
+ # str = "foo bar test"
+ # str.remove(" test") # => "foo bar"
+ # str # => "foo bar test"
def remove(*patterns)
dup.remove!(*patterns)
end
# Alters the string by removing all occurrences of the patterns.
+ # str = "foo bar test"
+ # str.remove!(" test") # => "foo bar"
+ # str # => "foo bar"
def remove!(*patterns)
patterns.each do |pattern|
gsub! pattern, ""
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 042283e4fc..ba92afd5f4 100644
--- a/activesupport/lib/active_support/core_ext/string/output_safety.rb
+++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb
@@ -247,6 +247,11 @@ module ActiveSupport #:nodoc:
end
class String
+ # Marks a string as trusted safe. It will be inserted into HTML with no
+ # additional escaping performed. It is your responsibilty to ensure that the
+ # string contains no malicious content. This method is equivalent to the
+ # `raw` helper in views. It is recommended that you use `sanitize` instead of
+ # this method. It should never be called on user input.
def html_safe
ActiveSupport::SafeBuffer.new(self)
end
diff --git a/activesupport/lib/active_support/core_ext/time/zones.rb b/activesupport/lib/active_support/core_ext/time/zones.rb
index bbda04d60c..64c3b7201b 100644
--- a/activesupport/lib/active_support/core_ext/time/zones.rb
+++ b/activesupport/lib/active_support/core_ext/time/zones.rb
@@ -1,4 +1,5 @@
require 'active_support/time_with_zone'
+require 'active_support/core_ext/time/acts_like'
require 'active_support/core_ext/date_and_time/zones'
class Time
diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb
index a89c769e34..ff8c0fd310 100644
--- a/activesupport/lib/active_support/dependencies.rb
+++ b/activesupport/lib/active_support/dependencies.rb
@@ -205,7 +205,10 @@ module ActiveSupport #:nodoc:
# Object includes this module.
module Loadable #:nodoc:
def self.exclude_from(base)
- base.class_eval { define_method(:load, Kernel.instance_method(:load)) }
+ base.class_eval do
+ define_method(:load, Kernel.instance_method(:load))
+ private :load
+ end
end
def require_or_load(file_name)
@@ -241,18 +244,6 @@ module ActiveSupport #:nodoc:
raise
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
-
# Mark the given constant as unloadable. Unloadable constants are removed
# each time dependencies are cleared.
#
@@ -269,6 +260,20 @@ module ActiveSupport #:nodoc:
def unloadable(const_desc)
Dependencies.mark_for_unload const_desc
end
+
+ private
+
+ 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
end
# Exception file-blaming.
@@ -737,7 +742,7 @@ module ActiveSupport #:nodoc:
protected
def log_call(*args)
if log_activity?
- arg_str = args.collect { |arg| arg.inspect } * ', '
+ arg_str = args.collect(&:inspect) * ', '
/in `([a-z_\?\!]+)'/ =~ caller(1).first
selector = $1 || '<unknown>'
log "called #{selector}(#{arg_str})"
diff --git a/activesupport/lib/active_support/duration.rb b/activesupport/lib/active_support/duration.rb
index 584fc1e1c5..0de1d2c7df 100644
--- a/activesupport/lib/active_support/duration.rb
+++ b/activesupport/lib/active_support/duration.rb
@@ -1,4 +1,3 @@
-require 'active_support/proxy_object'
require 'active_support/core_ext/array/conversions'
require 'active_support/core_ext/object/acts_like'
@@ -103,6 +102,8 @@ module ActiveSupport
@value.respond_to?(method, include_private)
end
+ delegate :<=>, to: :value
+
protected
def sum(sign, time = ::Time.current) #:nodoc:
diff --git a/activesupport/lib/active_support/gem_version.rb b/activesupport/lib/active_support/gem_version.rb
index bc7933e38b..7068f09d87 100644
--- a/activesupport/lib/active_support/gem_version.rb
+++ b/activesupport/lib/active_support/gem_version.rb
@@ -5,10 +5,10 @@ module ActiveSupport
end
module VERSION
- MAJOR = 4
- MINOR = 2
+ MAJOR = 5
+ MINOR = 0
TINY = 0
- PRE = "beta4"
+ PRE = "alpha"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/activesupport/lib/active_support/message_verifier.rb b/activesupport/lib/active_support/message_verifier.rb
index 4e0796f4f8..a8a8de5672 100644
--- a/activesupport/lib/active_support/message_verifier.rb
+++ b/activesupport/lib/active_support/message_verifier.rb
@@ -40,7 +40,7 @@ module ActiveSupport
data, digest = signed_message.split("--")
if data.present? && digest.present? && ActiveSupport::SecurityUtils.secure_compare(digest, generate_digest(data))
begin
- @serializer.load(::Base64.strict_decode64(data))
+ @serializer.load(decode(data))
rescue ArgumentError => argument_error
raise InvalidSignature if argument_error.message =~ %r{invalid base64}
raise
@@ -51,11 +51,19 @@ module ActiveSupport
end
def generate(value)
- data = ::Base64.strict_encode64(@serializer.dump(value))
+ data = encode(@serializer.dump(value))
"#{data}--#{generate_digest(data)}"
end
private
+ def encode(data)
+ ::Base64.strict_encode64(data)
+ end
+
+ def decode(data)
+ ::Base64.strict_decode64(data)
+ end
+
def generate_digest(data)
require 'openssl' unless defined?(OpenSSL)
OpenSSL::HMAC.hexdigest(OpenSSL::Digest.const_get(@digest).new, @secret, data)
diff --git a/activesupport/lib/active_support/multibyte/unicode.rb b/activesupport/lib/active_support/multibyte/unicode.rb
index 7d45961515..7ab6293b60 100644
--- a/activesupport/lib/active_support/multibyte/unicode.rb
+++ b/activesupport/lib/active_support/multibyte/unicode.rb
@@ -11,7 +11,7 @@ module ActiveSupport
NORMALIZATION_FORMS = [:c, :kc, :d, :kd]
# The Unicode version that is supported by the implementation
- UNICODE_VERSION = '6.3.0'
+ UNICODE_VERSION = '7.0.0'
# The default normalization used for operations that require
# normalization. It can be set to any of the normalizations
diff --git a/activesupport/lib/active_support/notifications.rb b/activesupport/lib/active_support/notifications.rb
index 325a3d75dc..b9f8e1ab2c 100644
--- a/activesupport/lib/active_support/notifications.rb
+++ b/activesupport/lib/active_support/notifications.rb
@@ -16,7 +16,7 @@ module ActiveSupport
# render text: 'Foo'
# end
#
- # That executes the block first and notifies all subscribers once done.
+ # That first executes the block and then notifies all subscribers once done.
#
# In the example above +render+ is the name of the event, and the rest is called
# the _payload_. The payload is a mechanism that allows instrumenters to pass
diff --git a/activesupport/lib/active_support/number_helper/number_to_human_converter.rb b/activesupport/lib/active_support/number_helper/number_to_human_converter.rb
index 9a3dc526ae..6940beb318 100644
--- a/activesupport/lib/active_support/number_helper/number_to_human_converter.rb
+++ b/activesupport/lib/active_support/number_helper/number_to_human_converter.rb
@@ -59,7 +59,7 @@ module ActiveSupport
translate_in_locale("human.decimal_units.units", raise: true)
else
raise ArgumentError, ":units must be a Hash or String translation scope."
- end.keys.map { |e_name| INVERTED_DECIMAL_UNITS[e_name] }.sort_by { |e| -e }
+ end.keys.map { |e_name| INVERTED_DECIMAL_UNITS[e_name] }.sort_by(&:-@)
end
end
end
diff --git a/activesupport/lib/active_support/testing/assertions.rb b/activesupport/lib/active_support/testing/assertions.rb
index 11cca82995..8b649c193f 100644
--- a/activesupport/lib/active_support/testing/assertions.rb
+++ b/activesupport/lib/active_support/testing/assertions.rb
@@ -66,7 +66,7 @@ module ActiveSupport
exps = expressions.map { |e|
e.respond_to?(:call) ? e : lambda { eval(e, block.binding) }
}
- before = exps.map { |e| e.call }
+ before = exps.map(&:call)
yield
diff --git a/activesupport/lib/active_support/values/time_zone.rb b/activesupport/lib/active_support/values/time_zone.rb
index 55533a5d40..fd05a5459c 100644
--- a/activesupport/lib/active_support/values/time_zone.rb
+++ b/activesupport/lib/active_support/values/time_zone.rb
@@ -237,7 +237,7 @@ module ActiveSupport
case arg
when String
begin
- @lazy_zones_map[arg] ||= create(arg).tap { |tz| tz.utc_offset }
+ @lazy_zones_map[arg] ||= create(arg).tap(&:utc_offset)
rescue TZInfo::InvalidTimezoneIdentifier
nil
end
diff --git a/activesupport/lib/active_support/values/unicode_tables.dat b/activesupport/lib/active_support/values/unicode_tables.dat
index 394ee95f4b..760be4c07a 100644
--- a/activesupport/lib/active_support/values/unicode_tables.dat
+++ b/activesupport/lib/active_support/values/unicode_tables.dat
Binary files differ
diff --git a/activesupport/lib/active_support/xml_mini/jdom.rb b/activesupport/lib/active_support/xml_mini/jdom.rb
index 27c64c4dca..f303daa1a7 100644
--- a/activesupport/lib/active_support/xml_mini/jdom.rb
+++ b/activesupport/lib/active_support/xml_mini/jdom.rb
@@ -141,7 +141,7 @@ module ActiveSupport
(0...attributes.length).each do |i|
attribute_hash[CONTENT_KEY] ||= ''
attribute_hash[attributes.item(i).name] = attributes.item(i).value
- end
+ end
attribute_hash
end
diff --git a/activesupport/test/core_ext/duration_test.rb b/activesupport/test/core_ext/duration_test.rb
index 5a2af7f943..2b893c7cd0 100644
--- a/activesupport/test/core_ext/duration_test.rb
+++ b/activesupport/test/core_ext/duration_test.rb
@@ -30,7 +30,6 @@ class DurationTest < ActiveSupport::TestCase
assert ActiveSupport::Duration === 1.day
assert !(ActiveSupport::Duration === 1.day.to_i)
assert !(ActiveSupport::Duration === 'foo')
- assert !(ActiveSupport::Duration === ActiveSupport::ProxyObject.new)
end
def test_equals
@@ -200,4 +199,16 @@ class DurationTest < ActiveSupport::TestCase
def test_hash
assert_equal 1.minute.hash, 60.seconds.hash
end
+
+ def test_comparable
+ assert_equal(-1, (0.seconds <=> 1.second))
+ assert_equal(-1, (1.second <=> 1.minute))
+ assert_equal(-1, (1 <=> 1.minute))
+ assert_equal(0, (0.seconds <=> 0.seconds))
+ assert_equal(0, (0.seconds <=> 0.minutes))
+ assert_equal(0, (1.second <=> 1.second))
+ assert_equal(1, (1.second <=> 0.second))
+ assert_equal(1, (1.minute <=> 1.second))
+ assert_equal(1, (61 <=> 1.minute))
+ end
end
diff --git a/activesupport/test/core_ext/enumerable_test.rb b/activesupport/test/core_ext/enumerable_test.rb
index 6fcf6e8743..346dc3d208 100644
--- a/activesupport/test/core_ext/enumerable_test.rb
+++ b/activesupport/test/core_ext/enumerable_test.rb
@@ -71,14 +71,14 @@ class EnumerableTests < ActiveSupport::TestCase
def test_index_by
payments = GenericEnumerable.new([ Payment.new(5), Payment.new(15), Payment.new(10) ])
assert_equal({ 5 => Payment.new(5), 15 => Payment.new(15), 10 => Payment.new(10) },
- payments.index_by { |p| p.price })
+ payments.index_by(&:price))
assert_equal Enumerator, payments.index_by.class
if Enumerator.method_defined? :size
assert_equal nil, payments.index_by.size
assert_equal 42, (1..42).index_by.size
end
assert_equal({ 5 => Payment.new(5), 15 => Payment.new(15), 10 => Payment.new(10) },
- payments.index_by.each { |p| p.price })
+ payments.index_by.each(&:price))
end
def test_many
diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb
index 5e9fdfd872..3d2f50ce49 100644
--- a/activesupport/test/core_ext/hash_ext_test.rb
+++ b/activesupport/test/core_ext/hash_ext_test.rb
@@ -365,7 +365,7 @@ class HashExtTest < ActiveSupport::TestCase
:member? => true }
hashes.each do |name, hash|
- method_map.sort_by { |m| m.to_s }.each do |meth, expected|
+ method_map.sort_by(&:to_s).each do |meth, expected|
assert_equal(expected, hash.__send__(meth, 'a'),
"Calling #{name}.#{meth} 'a'")
assert_equal(expected, hash.__send__(meth, :a),
diff --git a/activesupport/test/core_ext/object/try_test.rb b/activesupport/test/core_ext/object/try_test.rb
index efc6beaf02..89438675c1 100644
--- a/activesupport/test/core_ext/object/try_test.rb
+++ b/activesupport/test/core_ext/object/try_test.rb
@@ -52,11 +52,11 @@ class ObjectTryTest < ActiveSupport::TestCase
end
def test_try_only_block
- assert_equal @string.reverse, @string.try { |s| s.reverse }
+ assert_equal @string.reverse, @string.try(&:reverse)
end
def test_try_only_block_bang
- assert_equal @string.reverse, @string.try! { |s| s.reverse }
+ assert_equal @string.reverse, @string.try!(&:reverse)
end
def test_try_only_block_nil
diff --git a/activesupport/test/core_ext/range_ext_test.rb b/activesupport/test/core_ext/range_ext_test.rb
index 98c4ec6b5e..f096328cee 100644
--- a/activesupport/test/core_ext/range_ext_test.rb
+++ b/activesupport/test/core_ext/range_ext_test.rb
@@ -115,11 +115,11 @@ class RangeTest < ActiveSupport::TestCase
def test_date_time_with_each
datetime = DateTime.now
- assert ((datetime - 1.hour)..datetime).each {}
+ assert(((datetime - 1.hour)..datetime).each {})
end
def test_date_time_with_step
datetime = DateTime.now
- assert ((datetime - 1.hour)..datetime).step(1) {}
+ assert(((datetime - 1.hour)..datetime).step(1) {})
end
end
diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb
index 35095f2b2d..0af207fae9 100644
--- a/activesupport/test/core_ext/string_ext_test.rb
+++ b/activesupport/test/core_ext/string_ext_test.rb
@@ -266,6 +266,12 @@ class StringInflectionsTest < ActiveSupport::TestCase
assert_equal "This is a good day to die", original
end
+ def test_remove_for_multiple_occurrences
+ original = "This is a good day to die to die"
+ assert_equal "This is a good day", original.remove(" to die")
+ assert_equal "This is a good day to die to die", original
+ end
+
def test_remove!
original = "This is a very good day to die"
assert_equal "This is a good day to die", original.remove!(" very")
@@ -275,15 +281,11 @@ class StringInflectionsTest < ActiveSupport::TestCase
end
def test_constantize
- run_constantize_tests_on do |string|
- string.constantize
- end
+ run_constantize_tests_on(&:constantize)
end
def test_safe_constantize
- run_safe_constantize_tests_on do |string|
- string.safe_constantize
- end
+ run_safe_constantize_tests_on(&:safe_constantize)
end
end
@@ -414,11 +416,11 @@ class StringConversionsTest < ActiveSupport::TestCase
end
def test_partial_string_to_time
- with_env_tz "Europe/Moscow" do
+ with_env_tz "Europe/Moscow" do # use timezone which does not observe DST.
now = Time.now
assert_equal Time.local(now.year, now.month, now.day, 23, 50), "23:50".to_time
assert_equal Time.utc(now.year, now.month, now.day, 23, 50), "23:50".to_time(:utc)
- assert_equal Time.local(now.year, now.month, now.day, 18, 50), "13:50 -0100".to_time
+ assert_equal Time.local(now.year, now.month, now.day, 17, 50), "13:50 -0100".to_time
assert_equal Time.utc(now.year, now.month, now.day, 23, 50), "22:50 -0100".to_time(:utc)
end
end
diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb
index f2f60167c4..96e9bd1e65 100644
--- a/activesupport/test/dependencies_test.rb
+++ b/activesupport/test/dependencies_test.rb
@@ -16,11 +16,16 @@ module ModuleWithConstant
end
class DependenciesTest < ActiveSupport::TestCase
- def teardown
- ActiveSupport::Dependencies.clear
+ include DependenciesTestHelpers
+
+ setup do
+ @loaded_features_copy = $LOADED_FEATURES.dup
end
- include DependenciesTestHelpers
+ teardown do
+ ActiveSupport::Dependencies.clear
+ $LOADED_FEATURES.replace(@loaded_features_copy)
+ end
def test_depend_on_path
skip "LoadError#path does not exist" if RUBY_VERSION < '2.0.0'
@@ -53,8 +58,7 @@ class DependenciesTest < ActiveSupport::TestCase
assert_equal 2, ActiveSupport::Dependencies.loaded.size
end
ensure
- Object.send(:remove_const, :ServiceOne) if Object.const_defined?(:ServiceOne)
- Object.send(:remove_const, :ServiceTwo) if Object.const_defined?(:ServiceTwo)
+ remove_constants(:ServiceOne, :ServiceTwo)
end
def test_tracking_identical_loaded_files
@@ -64,7 +68,7 @@ class DependenciesTest < ActiveSupport::TestCase
assert_equal 1, ActiveSupport::Dependencies.loaded.size
end
ensure
- Object.send(:remove_const, :ServiceOne) if Object.const_defined?(:ServiceOne)
+ remove_constants(:ServiceOne)
end
def test_missing_dependency_raises_missing_source_file
@@ -84,8 +88,8 @@ class DependenciesTest < ActiveSupport::TestCase
assert_equal 'Loading me failed, so do not add to loaded or history.', e.message
assert_equal count + 1, $raises_exception_load_count
- assert !ActiveSupport::Dependencies.loaded.include?(filename)
- assert !ActiveSupport::Dependencies.history.include?(filename)
+ assert_not ActiveSupport::Dependencies.loaded.include?(filename)
+ assert_not ActiveSupport::Dependencies.history.include?(filename)
end
end
end
@@ -93,7 +97,6 @@ class DependenciesTest < ActiveSupport::TestCase
def test_dependency_which_raises_doesnt_blindly_call_blame_file!
with_loading do
filename = 'dependencies/raises_exception_without_blame_file'
-
assert_raises(Exception) { require_dependency filename }
end
end
@@ -101,13 +104,12 @@ class DependenciesTest < ActiveSupport::TestCase
def test_warnings_should_be_enabled_on_first_load
with_loading 'dependencies' do
old_warnings, ActiveSupport::Dependencies.warnings_on_first_load = ActiveSupport::Dependencies.warnings_on_first_load, true
-
filename = "check_warnings"
expanded = File.expand_path("#{File.dirname(__FILE__)}/dependencies/#{filename}")
$check_warnings_load_count = 0
- assert !ActiveSupport::Dependencies.loaded.include?(expanded)
- assert !ActiveSupport::Dependencies.history.include?(expanded)
+ assert_not ActiveSupport::Dependencies.loaded.include?(expanded)
+ assert_not ActiveSupport::Dependencies.history.include?(expanded)
silence_warnings { require_dependency filename }
assert_equal 1, $check_warnings_load_count
@@ -115,7 +117,7 @@ class DependenciesTest < ActiveSupport::TestCase
assert ActiveSupport::Dependencies.loaded.include?(expanded)
ActiveSupport::Dependencies.clear
- assert !ActiveSupport::Dependencies.loaded.include?(expanded)
+ assert_not ActiveSupport::Dependencies.loaded.include?(expanded)
assert ActiveSupport::Dependencies.history.include?(expanded)
silence_warnings { require_dependency filename }
@@ -124,7 +126,7 @@ class DependenciesTest < ActiveSupport::TestCase
assert ActiveSupport::Dependencies.loaded.include?(expanded)
ActiveSupport::Dependencies.clear
- assert !ActiveSupport::Dependencies.loaded.include?(expanded)
+ assert_not ActiveSupport::Dependencies.loaded.include?(expanded)
assert ActiveSupport::Dependencies.history.include?(expanded)
enable_warnings { require_dependency filename }
@@ -203,43 +205,49 @@ class DependenciesTest < ActiveSupport::TestCase
def test_directories_manifest_as_modules_unless_const_defined
with_autoloading_fixtures do
assert_kind_of Module, ModuleFolder
- Object.__send__ :remove_const, :ModuleFolder
end
+ ensure
+ remove_constants(:ModuleFolder)
end
def test_module_with_nested_class
with_autoloading_fixtures do
assert_kind_of Class, ModuleFolder::NestedClass
- Object.__send__ :remove_const, :ModuleFolder
end
+ ensure
+ remove_constants(:ModuleFolder)
end
def test_module_with_nested_inline_class
with_autoloading_fixtures do
assert_kind_of Class, ModuleFolder::InlineClass
- Object.__send__ :remove_const, :ModuleFolder
end
+ ensure
+ remove_constants(:ModuleFolder)
end
def test_directories_may_manifest_as_nested_classes
with_autoloading_fixtures do
assert_kind_of Class, ClassFolder
- Object.__send__ :remove_const, :ClassFolder
end
+ ensure
+ remove_constants(:ClassFolder)
end
def test_class_with_nested_class
with_autoloading_fixtures do
assert_kind_of Class, ClassFolder::NestedClass
- Object.__send__ :remove_const, :ClassFolder
end
+ ensure
+ remove_constants(:ClassFolder)
end
def test_class_with_nested_inline_class
with_autoloading_fixtures do
assert_kind_of Class, ClassFolder::InlineClass
- Object.__send__ :remove_const, :ClassFolder
end
+ ensure
+ remove_constants(:ClassFolder)
end
def test_class_with_nested_inline_subclass_of_parent
@@ -247,8 +255,9 @@ class DependenciesTest < ActiveSupport::TestCase
assert_kind_of Class, ClassFolder::ClassFolderSubclass
assert_kind_of Class, ClassFolder
assert_equal 'indeed', ClassFolder::ClassFolderSubclass::ConstantInClassFolder
- Object.__send__ :remove_const, :ClassFolder
end
+ ensure
+ remove_constants(:ClassFolder)
end
def test_nested_class_can_access_sibling
@@ -256,16 +265,15 @@ class DependenciesTest < ActiveSupport::TestCase
sibling = ModuleFolder::NestedClass.class_eval "NestedSibling"
assert defined?(ModuleFolder::NestedSibling)
assert_equal ModuleFolder::NestedSibling, sibling
- Object.__send__ :remove_const, :ModuleFolder
end
+ ensure
+ remove_constants(:ModuleFolder)
end
def test_doesnt_break_normal_require
path = File.expand_path("../autoloading_fixtures/load_path", __FILE__)
original_path = $:.dup
- original_features = $".dup
$:.push(path)
-
with_autoloading_fixtures do
# The _ = assignments are to prevent warnings
_ = RequiresConstant
@@ -277,15 +285,13 @@ class DependenciesTest < ActiveSupport::TestCase
assert defined?(LoadedConstant)
end
ensure
- remove_constants(:RequiresConstant, :LoadedConstant, :LoadsConstant)
- $".replace(original_features)
+ remove_constants(:RequiresConstant, :LoadedConstant)
$:.replace(original_path)
end
def test_doesnt_break_normal_require_nested
path = File.expand_path("../autoloading_fixtures/load_path", __FILE__)
original_path = $:.dup
- original_features = $".dup
$:.push(path)
with_autoloading_fixtures do
@@ -300,14 +306,12 @@ class DependenciesTest < ActiveSupport::TestCase
end
ensure
remove_constants(:RequiresConstant, :LoadedConstant, :LoadsConstant)
- $".replace(original_features)
$:.replace(original_path)
end
def test_require_returns_true_when_file_not_yet_required
path = File.expand_path("../autoloading_fixtures/load_path", __FILE__)
original_path = $:.dup
- original_features = $".dup
$:.push(path)
with_loading do
@@ -315,14 +319,12 @@ class DependenciesTest < ActiveSupport::TestCase
end
ensure
remove_constants(:LoadedConstant)
- $".replace(original_features)
$:.replace(original_path)
end
def test_require_returns_true_when_file_not_yet_required_even_when_no_new_constants_added
path = File.expand_path("../autoloading_fixtures/load_path", __FILE__)
original_path = $:.dup
- original_features = $".dup
$:.push(path)
with_loading do
@@ -331,14 +333,12 @@ class DependenciesTest < ActiveSupport::TestCase
end
ensure
remove_constants(:LoadedConstant)
- $".replace(original_features)
$:.replace(original_path)
end
def test_require_returns_false_when_file_already_required
path = File.expand_path("../autoloading_fixtures/load_path", __FILE__)
original_path = $:.dup
- original_features = $".dup
$:.push(path)
with_loading do
@@ -347,7 +347,6 @@ class DependenciesTest < ActiveSupport::TestCase
end
ensure
remove_constants(:LoadedConstant)
- $".replace(original_features)
$:.replace(original_path)
end
@@ -355,14 +354,11 @@ class DependenciesTest < ActiveSupport::TestCase
with_loading do
assert_raise(LoadError) { require 'this_file_dont_exist_dude' }
end
- ensure
- remove_constants(:LoadedConstant)
end
def test_load_returns_true_when_file_found
path = File.expand_path("../autoloading_fixtures/load_path", __FILE__)
original_path = $:.dup
- original_features = $".dup
$:.push(path)
with_loading do
@@ -371,7 +367,6 @@ class DependenciesTest < ActiveSupport::TestCase
end
ensure
remove_constants(:LoadedConstant)
- $".replace(original_features)
$:.replace(original_path)
end
@@ -379,17 +374,16 @@ class DependenciesTest < ActiveSupport::TestCase
with_loading do
assert_raise(LoadError) { load 'this_file_dont_exist_dude.rb' }
end
- ensure
- remove_constants(:LoadedConstant)
end
def failing_test_access_thru_and_upwards_fails
with_autoloading_fixtures do
- assert ! defined?(ModuleFolder)
+ assert_not defined?(ModuleFolder)
assert_raise(NameError) { ModuleFolder::Object }
assert_raise(NameError) { ModuleFolder::NestedClass::Object }
- Object.__send__ :remove_const, :ModuleFolder
end
+ ensure
+ remove_constants(:ModuleFolder)
end
def test_non_existing_const_raises_name_error_with_fully_qualified_name
@@ -402,6 +396,8 @@ class DependenciesTest < ActiveSupport::TestCase
assert_equal "uninitialized constant A::B::DoesNotExist", e.message
assert_equal :DoesNotExist, e.name
end
+ ensure
+ remove_constants(:A)
end
def test_smart_name_error_strings
@@ -491,9 +487,9 @@ class DependenciesTest < ActiveSupport::TestCase
nil_name = Module.new
def nil_name.name() nil end
assert !ActiveSupport::Dependencies.autoloaded?(nil_name)
-
- Object.class_eval { remove_const :ModuleFolder }
end
+ ensure
+ remove_constants(:ModuleFolder)
end
def test_qualified_name_for
@@ -551,6 +547,8 @@ class DependenciesTest < ActiveSupport::TestCase
assert_kind_of Module, ::ModuleWithCustomConstMissing::A
assert_kind_of String, ::ModuleWithCustomConstMissing::A::B
end
+ ensure
+ remove_constants(:ModuleWithCustomConstMissing)
end
def test_const_missing_in_anonymous_modules_loads_top_level_constants
@@ -559,6 +557,8 @@ class DependenciesTest < ActiveSupport::TestCase
klass = Class.new.class_eval "E"
assert_equal E, klass
end
+ ensure
+ remove_constants(:E)
end
def test_const_missing_in_anonymous_modules_raises_if_the_constant_belongs_to_Object
@@ -570,18 +570,22 @@ class DependenciesTest < ActiveSupport::TestCase
assert_equal 'E cannot be autoloaded from an anonymous class or module', e.message
assert_equal :E, e.name
end
+ ensure
+ remove_constants(:E)
end
def test_removal_from_tree_should_be_detected
with_loading 'dependencies' do
c = ServiceOne
ActiveSupport::Dependencies.clear
- assert ! defined?(ServiceOne)
+ assert_not defined?(ServiceOne)
e = assert_raise ArgumentError do
ActiveSupport::Dependencies.load_missing_constant(c, :FakeMissing)
end
assert_match %r{ServiceOne has been removed from the module tree}i, e.message
end
+ ensure
+ remove_constants(:ServiceOne)
end
def test_references_should_work
@@ -590,18 +594,21 @@ class DependenciesTest < ActiveSupport::TestCase
service_one_first = ServiceOne
assert_equal service_one_first, c.get("ServiceOne")
ActiveSupport::Dependencies.clear
- assert ! defined?(ServiceOne)
-
+ assert_not defined?(ServiceOne)
service_one_second = ServiceOne
assert_not_equal service_one_first, c.get("ServiceOne")
assert_equal service_one_second, c.get("ServiceOne")
end
+ ensure
+ remove_constants(:ServiceOne)
end
def test_constantize_shortcut_for_cached_constant_lookups
with_loading 'dependencies' do
assert_equal ServiceOne, ActiveSupport::Dependencies.constantize("ServiceOne")
end
+ ensure
+ remove_constants(:ServiceOne)
end
def test_nested_load_error_isnt_rescued
@@ -613,19 +620,20 @@ class DependenciesTest < ActiveSupport::TestCase
end
def test_autoload_once_paths_do_not_add_to_autoloaded_constants
+ old_path = ActiveSupport::Dependencies.autoload_once_paths
with_autoloading_fixtures do
ActiveSupport::Dependencies.autoload_once_paths = ActiveSupport::Dependencies.autoload_paths.dup
- assert ! ActiveSupport::Dependencies.autoloaded?("ModuleFolder")
- assert ! ActiveSupport::Dependencies.autoloaded?("ModuleFolder::NestedClass")
- assert ! ActiveSupport::Dependencies.autoloaded?(ModuleFolder)
+ assert_not ActiveSupport::Dependencies.autoloaded?("ModuleFolder")
+ assert_not ActiveSupport::Dependencies.autoloaded?("ModuleFolder::NestedClass")
+ assert_not ActiveSupport::Dependencies.autoloaded?(ModuleFolder)
1 if ModuleFolder::NestedClass # 1 if to avoid warning
- assert ! ActiveSupport::Dependencies.autoloaded?(ModuleFolder::NestedClass)
+ assert_not ActiveSupport::Dependencies.autoloaded?(ModuleFolder::NestedClass)
end
ensure
- Object.class_eval { remove_const :ModuleFolder }
- ActiveSupport::Dependencies.autoload_once_paths = []
+ remove_constants(:ModuleFolder)
+ ActiveSupport::Dependencies.autoload_once_paths = old_path
end
def test_autoload_once_pathnames_do_not_add_to_autoloaded_constants
@@ -634,15 +642,15 @@ class DependenciesTest < ActiveSupport::TestCase
ActiveSupport::Dependencies.autoload_paths = pathnames
ActiveSupport::Dependencies.autoload_once_paths = pathnames
- assert ! ActiveSupport::Dependencies.autoloaded?("ModuleFolder")
- assert ! ActiveSupport::Dependencies.autoloaded?("ModuleFolder::NestedClass")
- assert ! ActiveSupport::Dependencies.autoloaded?(ModuleFolder)
+ assert_not ActiveSupport::Dependencies.autoloaded?("ModuleFolder")
+ assert_not ActiveSupport::Dependencies.autoloaded?("ModuleFolder::NestedClass")
+ assert_not ActiveSupport::Dependencies.autoloaded?(ModuleFolder)
1 if ModuleFolder::NestedClass # 1 if to avoid warning
- assert ! ActiveSupport::Dependencies.autoloaded?(ModuleFolder::NestedClass)
+ assert_not ActiveSupport::Dependencies.autoloaded?(ModuleFolder::NestedClass)
end
ensure
- Object.class_eval { remove_const :ModuleFolder }
+ remove_constants(:ModuleFolder)
ActiveSupport::Dependencies.autoload_once_paths = []
end
@@ -652,6 +660,8 @@ class DependenciesTest < ActiveSupport::TestCase
assert_equal 10, ApplicationController
assert ActiveSupport::Dependencies.autoloaded?(:ApplicationController)
end
+ ensure
+ remove_constants(:ApplicationController)
end
def test_preexisting_constants_are_not_marked_as_autoloaded
@@ -667,9 +677,8 @@ class DependenciesTest < ActiveSupport::TestCase
assert ! ActiveSupport::Dependencies.autoloaded?(:E), "E shouldn't be marked autoloaded!"
ActiveSupport::Dependencies.clear
end
-
ensure
- Object.class_eval { remove_const :E }
+ remove_constants(:E)
end
def test_constants_in_capitalized_nesting_marked_as_autoloaded
@@ -678,6 +687,8 @@ class DependenciesTest < ActiveSupport::TestCase
assert ActiveSupport::Dependencies.autoloaded?("HTML::SomeClass")
end
+ ensure
+ remove_constants(:HTML)
end
def test_unloadable
@@ -708,7 +719,7 @@ class DependenciesTest < ActiveSupport::TestCase
assert_equal false, M.unloadable
end
ensure
- Object.class_eval { remove_const :M }
+ remove_constants(:M)
end
def test_unloadable_constants_should_receive_callback
@@ -719,7 +730,7 @@ class DependenciesTest < ActiveSupport::TestCase
ActiveSupport::Dependencies.clear
assert !defined?(C)
ensure
- Object.class_eval { remove_const :C } if defined?(C)
+ remove_constants(:C)
end
def test_new_contants_in_without_constants
@@ -733,7 +744,7 @@ class DependenciesTest < ActiveSupport::TestCase
}.map(&:to_s)
assert ActiveSupport::Dependencies.constant_watch_stack.all? {|k,v| v.empty? }
ensure
- Object.class_eval { remove_const :Hello }
+ remove_constants(:Hello)
end
def test_new_constants_in_with_nesting
@@ -750,9 +761,7 @@ class DependenciesTest < ActiveSupport::TestCase
assert_equal ["OuterAfter", "OuterBefore"], outer.sort.map(&:to_s)
assert ActiveSupport::Dependencies.constant_watch_stack.all? {|k,v| v.empty? }
ensure
- %w(OuterBefore Inner OuterAfter).each do |name|
- Object.class_eval { remove_const name if const_defined?(name) }
- end
+ remove_constants(:OuterBefore, :Inner, :OuterAfter)
end
def test_new_constants_in_module
@@ -771,7 +780,7 @@ class DependenciesTest < ActiveSupport::TestCase
assert_equal ["M::OuterAfter", "M::OuterBefore"], outer.sort
assert ActiveSupport::Dependencies.constant_watch_stack.all? {|k,v| v.empty? }
ensure
- Object.class_eval { remove_const :M }
+ remove_constants(:M)
end
def test_new_constants_in_module_using_name
@@ -789,7 +798,7 @@ class DependenciesTest < ActiveSupport::TestCase
assert_equal ["M::OuterAfter", "M::OuterBefore"], outer.sort
assert ActiveSupport::Dependencies.constant_watch_stack.all? {|k,v| v.empty? }
ensure
- Object.class_eval { remove_const :M }
+ remove_constants(:M)
end
def test_new_constants_in_with_inherited_constants
@@ -807,26 +816,27 @@ class DependenciesTest < ActiveSupport::TestCase
def test_file_with_multiple_constants_and_require_dependency
with_autoloading_fixtures do
- assert ! defined?(MultipleConstantFile)
- assert ! defined?(SiblingConstant)
+ assert_not defined?(MultipleConstantFile)
+ assert_not defined?(SiblingConstant)
require_dependency 'multiple_constant_file'
assert defined?(MultipleConstantFile)
assert defined?(SiblingConstant)
assert ActiveSupport::Dependencies.autoloaded?(:MultipleConstantFile)
assert ActiveSupport::Dependencies.autoloaded?(:SiblingConstant)
-
ActiveSupport::Dependencies.clear
- assert ! defined?(MultipleConstantFile)
- assert ! defined?(SiblingConstant)
+ assert_not defined?(MultipleConstantFile)
+ assert_not defined?(SiblingConstant)
end
+ ensure
+ remove_constants(:MultipleConstantFile, :SiblingConstant)
end
def test_file_with_multiple_constants_and_auto_loading
with_autoloading_fixtures do
- assert ! defined?(MultipleConstantFile)
- assert ! defined?(SiblingConstant)
+ assert_not defined?(MultipleConstantFile)
+ assert_not defined?(SiblingConstant)
assert_equal 10, MultipleConstantFile
@@ -837,15 +847,17 @@ class DependenciesTest < ActiveSupport::TestCase
ActiveSupport::Dependencies.clear
- assert ! defined?(MultipleConstantFile)
- assert ! defined?(SiblingConstant)
+ assert_not defined?(MultipleConstantFile)
+ assert_not defined?(SiblingConstant)
end
+ ensure
+ remove_constants(:MultipleConstantFile, :SiblingConstant)
end
def test_nested_file_with_multiple_constants_and_require_dependency
with_autoloading_fixtures do
- assert ! defined?(ClassFolder::NestedClass)
- assert ! defined?(ClassFolder::SiblingClass)
+ assert_not defined?(ClassFolder::NestedClass)
+ assert_not defined?(ClassFolder::SiblingClass)
require_dependency 'class_folder/nested_class'
@@ -856,15 +868,17 @@ class DependenciesTest < ActiveSupport::TestCase
ActiveSupport::Dependencies.clear
- assert ! defined?(ClassFolder::NestedClass)
- assert ! defined?(ClassFolder::SiblingClass)
+ assert_not defined?(ClassFolder::NestedClass)
+ assert_not defined?(ClassFolder::SiblingClass)
end
+ ensure
+ remove_constants(:ClassFolder)
end
def test_nested_file_with_multiple_constants_and_auto_loading
with_autoloading_fixtures do
- assert ! defined?(ClassFolder::NestedClass)
- assert ! defined?(ClassFolder::SiblingClass)
+ assert_not defined?(ClassFolder::NestedClass)
+ assert_not defined?(ClassFolder::SiblingClass)
assert_kind_of Class, ClassFolder::NestedClass
@@ -875,9 +889,11 @@ class DependenciesTest < ActiveSupport::TestCase
ActiveSupport::Dependencies.clear
- assert ! defined?(ClassFolder::NestedClass)
- assert ! defined?(ClassFolder::SiblingClass)
+ assert_not defined?(ClassFolder::NestedClass)
+ assert_not defined?(ClassFolder::SiblingClass)
end
+ ensure
+ remove_constants(:ClassFolder)
end
def test_autoload_doesnt_shadow_no_method_error_with_relative_constant
@@ -888,9 +904,8 @@ class DependenciesTest < ActiveSupport::TestCase
assert !defined?(::RaisesNoMethodError), "::RaisesNoMethodError is defined but it should have failed!"
end
end
-
ensure
- Object.class_eval { remove_const :RaisesNoMethodError if const_defined?(:RaisesNoMethodError) }
+ remove_constants(:RaisesNoMethodError)
end
def test_autoload_doesnt_shadow_no_method_error_with_absolute_constant
@@ -901,9 +916,8 @@ class DependenciesTest < ActiveSupport::TestCase
assert !defined?(::RaisesNoMethodError), "::RaisesNoMethodError is defined but it should have failed!"
end
end
-
ensure
- Object.class_eval { remove_const :RaisesNoMethodError if const_defined?(:RaisesNoMethodError) }
+ remove_constants(:RaisesNoMethodError)
end
def test_autoload_doesnt_shadow_error_when_mechanism_not_set_to_load
@@ -919,7 +933,6 @@ class DependenciesTest < ActiveSupport::TestCase
def test_autoload_doesnt_shadow_name_error
with_autoloading_fixtures do
- Object.send(:remove_const, :RaisesNameError) if defined?(::RaisesNameError)
2.times do
e = assert_raise NameError do
::RaisesNameError::FooBarBaz.object_id
@@ -934,19 +947,20 @@ class DependenciesTest < ActiveSupport::TestCase
assert !defined?(::RaisesNameError), "::RaisesNameError is defined but it should have failed!"
end
end
-
ensure
- Object.class_eval { remove_const :RaisesNoMethodError if const_defined?(:RaisesNoMethodError) }
+ remove_constants(:RaisesNameError)
end
def test_remove_constant_handles_double_colon_at_start
Object.const_set 'DeleteMe', Module.new
DeleteMe.const_set 'OrMe', Module.new
ActiveSupport::Dependencies.remove_constant "::DeleteMe::OrMe"
- assert ! defined?(DeleteMe::OrMe)
+ assert_not defined?(DeleteMe::OrMe)
assert defined?(DeleteMe)
ActiveSupport::Dependencies.remove_constant "::DeleteMe"
- assert ! defined?(DeleteMe)
+ assert_not defined?(DeleteMe)
+ ensure
+ remove_constants(:DeleteMe)
end
def test_remove_constant_does_not_trigger_loading_autoloads
@@ -956,7 +970,9 @@ class DependenciesTest < ActiveSupport::TestCase
end
assert_nil ActiveSupport::Dependencies.remove_constant(constant), "Kernel#autoload has been triggered by remove_constant"
- assert !defined?(ShouldNotBeAutoloaded)
+ assert_not defined?(ShouldNotBeAutoloaded)
+ ensure
+ remove_constants(constant)
end
def test_remove_constant_does_not_autoload_already_removed_parents_as_a_side_effect
@@ -965,11 +981,14 @@ class DependenciesTest < ActiveSupport::TestCase
_ = ::A::B # assignment to silence parse-time warning "possibly useless use of :: in void context"
ActiveSupport::Dependencies.remove_constant('A')
ActiveSupport::Dependencies.remove_constant('A::B')
- assert !defined?(A)
+ assert_not defined?(A)
end
+ ensure
+ remove_constants(:A)
end
def test_load_once_constants_should_not_be_unloaded
+ old_path = ActiveSupport::Dependencies.autoload_once_paths
with_autoloading_fixtures do
ActiveSupport::Dependencies.autoload_once_paths = ActiveSupport::Dependencies.autoload_paths
_ = ::A # assignment to silence parse-time warning "possibly useless use of :: in void context"
@@ -978,8 +997,8 @@ class DependenciesTest < ActiveSupport::TestCase
assert defined?(A)
end
ensure
- ActiveSupport::Dependencies.autoload_once_paths = []
- Object.class_eval { remove_const :A if const_defined?(:A) }
+ ActiveSupport::Dependencies.autoload_once_paths = old_path
+ remove_constants(:A)
end
def test_access_unloaded_constants_for_reload
@@ -991,29 +1010,45 @@ class DependenciesTest < ActiveSupport::TestCase
A::B # Make sure no circular dependency error
end
+ ensure
+ remove_constants(:A)
end
def test_autoload_once_paths_should_behave_when_recursively_loading
+ old_path = ActiveSupport::Dependencies.autoload_once_paths
with_loading 'dependencies', 'autoloading_fixtures' do
ActiveSupport::Dependencies.autoload_once_paths = [ActiveSupport::Dependencies.autoload_paths.last]
- assert !defined?(CrossSiteDependency)
+ assert_not defined?(CrossSiteDependency)
assert_nothing_raised { CrossSiteDepender.nil? }
assert defined?(CrossSiteDependency)
- assert !ActiveSupport::Dependencies.autoloaded?(CrossSiteDependency),
+ assert_not ActiveSupport::Dependencies.autoloaded?(CrossSiteDependency),
"CrossSiteDependency shouldn't be marked as autoloaded!"
ActiveSupport::Dependencies.clear
assert defined?(CrossSiteDependency),
"CrossSiteDependency shouldn't have been unloaded!"
end
ensure
- ActiveSupport::Dependencies.autoload_once_paths = []
+ ActiveSupport::Dependencies.autoload_once_paths = old_path
+ remove_constants(:CrossSiteDependency)
end
def test_hook_called_multiple_times
assert_nothing_raised { ActiveSupport::Dependencies.hook! }
end
+ def test_load_and_require_stay_private
+ assert Object.private_methods.include?(:load)
+ assert Object.private_methods.include?(:require)
+
+ ActiveSupport::Dependencies.unhook!
+
+ assert Object.private_methods.include?(:load)
+ assert Object.private_methods.include?(:require)
+ ensure
+ ActiveSupport::Dependencies.hook!
+ end
+
def test_unhook
ActiveSupport::Dependencies.unhook!
assert !Module.new.respond_to?(:const_missing_without_dependencies)
diff --git a/activesupport/test/multibyte_chars_test.rb b/activesupport/test/multibyte_chars_test.rb
index feca013675..94748dd991 100644
--- a/activesupport/test/multibyte_chars_test.rb
+++ b/activesupport/test/multibyte_chars_test.rb
@@ -182,7 +182,7 @@ class MultibyteCharsUTF8BehaviourTest < ActiveSupport::TestCase
end
def test_sortability
- words = %w(builder armor zebra).sort_by { |s| s.mb_chars }
+ words = %w(builder armor zebra).sort_by(&:mb_chars)
assert_equal %w(armor builder zebra), words
end
diff --git a/activesupport/test/multibyte_conformance_test.rb b/activesupport/test/multibyte_conformance_test.rb
index aba81b8248..f7bd21c8ab 100644
--- a/activesupport/test/multibyte_conformance_test.rb
+++ b/activesupport/test/multibyte_conformance_test.rb
@@ -115,7 +115,7 @@ class MultibyteConformanceTest < ActiveSupport::TestCase
next if (line.empty? || line =~ /^\#/)
cols, comment = line.split("#")
- cols = cols.split(";").map{|e| e.strip}.reject{|e| e.empty? }
+ cols = cols.split(";").map(&:strip).reject(&:empty?)
next unless cols.length == 5
# codepoints are in hex in the test suite, pack wants them as integers
diff --git a/activesupport/test/rescuable_test.rb b/activesupport/test/rescuable_test.rb
index ec9d231125..b8af888f7c 100644
--- a/activesupport/test/rescuable_test.rb
+++ b/activesupport/test/rescuable_test.rb
@@ -93,13 +93,13 @@ class RescuableTest < ActiveSupport::TestCase
def test_rescues_defined_later_are_added_at_end_of_the_rescue_handlers_array
expected = ["WraithAttack", "WraithAttack", "NuclearExplosion", "MadRonon"]
- result = @stargate.send(:rescue_handlers).collect {|e| e.first}
+ result = @stargate.send(:rescue_handlers).collect(&:first)
assert_equal expected, result
end
def test_children_should_inherit_rescue_definitions_from_parents_and_child_rescue_should_be_appended
expected = ["WraithAttack", "WraithAttack", "NuclearExplosion", "MadRonon", "CoolError"]
- result = @cool_stargate.send(:rescue_handlers).collect {|e| e.first}
+ result = @cool_stargate.send(:rescue_handlers).collect(&:first)
assert_equal expected, result
end
end
diff --git a/ci/travis.rb b/ci/travis.rb
index a1920a7a1f..b62f90a59e 100755
--- a/ci/travis.rb
+++ b/ci/travis.rb
@@ -140,6 +140,6 @@ if failures.empty?
else
puts
puts "Rails build FAILED"
- puts "Failed components: #{failures.map { |component| component.first }.join(', ')}"
+ puts "Failed components: #{failures.map(&:first).join(', ')}"
exit(false)
end
diff --git a/guides/CHANGELOG.md b/guides/CHANGELOG.md
index 2770fc73e7..afaa404ac1 100644
--- a/guides/CHANGELOG.md
+++ b/guides/CHANGELOG.md
@@ -1,27 +1 @@
-* Change Posts to Articles in Getting Started sample application in order to
-better align with the actual guides.
-
- *John Kelly Ferguson*
-
-* Update all Rails 4.1.0 references to 4.1.1 within the guides and code.
-
- *John Kelly Ferguson*
-
-* Split up rows in the Explain Queries table of the ActiveRecord Querying section
-in order to improve readability.
-
- *John Kelly Ferguson*
-
-* Change all non-HTTP method 'post' references to 'article'.
-
- *John Kelly Ferguson*
-
-* Updates the maintenance policy to match the latest versions of Rails
-
- *Matias Korhonen*
-
-* Switched the order of `Applying a default scope` and `Merging of scopes` subsections so default scopes are introduced first.
-
- *Alex Riabov*
-
-Please check [4-1-stable](https://github.com/rails/rails/blob/4-1-stable/guides/CHANGELOG.md) for previous changes.
+Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/guides/CHANGELOG.md) for previous changes.
diff --git a/guides/Rakefile b/guides/Rakefile
index 94d4be8c0a..824bea0b39 100644
--- a/guides/Rakefile
+++ b/guides/Rakefile
@@ -34,10 +34,12 @@ namespace :guides do
task :help do
puts <<-help
-Guides are taken from the source directory, and the resulting HTML goes into the
+Guides are taken from the source directory, and the result goes into the
output directory. Assets are stored under files, and copied to output/files as
part of the generation process.
+You can generate HTML, Kindle or both formats using the `guides:generate` task.
+
All this process is handled via rake tasks, here's a full list of them:
#{%x[rake -T]}
diff --git a/guides/bug_report_templates/action_controller_gem.rb b/guides/bug_report_templates/action_controller_gem.rb
index 9387e3dc1d..1f0cec1e22 100644
--- a/guides/bug_report_templates/action_controller_gem.rb
+++ b/guides/bug_report_templates/action_controller_gem.rb
@@ -7,8 +7,8 @@ require 'action_controller/railtie'
class TestApp < Rails::Application
config.root = File.dirname(__FILE__)
config.session_store :cookie_store, key: 'cookie_store_key'
- config.secret_token = 'secret_token'
- config.secret_key_base = 'secret_key_base'
+ secrets.secret_token = 'secret_token'
+ secrets.secret_key_base = 'secret_key_base'
config.logger = Logger.new($stdout)
Rails.logger = config.logger
diff --git a/guides/bug_report_templates/action_controller_master.rb b/guides/bug_report_templates/action_controller_master.rb
index 20c64b4a85..0e51eaa0db 100644
--- a/guides/bug_report_templates/action_controller_master.rb
+++ b/guides/bug_report_templates/action_controller_master.rb
@@ -19,8 +19,8 @@ require 'action_controller/railtie'
class TestApp < Rails::Application
config.root = File.dirname(__FILE__)
config.session_store :cookie_store, key: 'cookie_store_key'
- config.secret_token = 'secret_token'
- config.secret_key_base = 'secret_key_base'
+ secrets.secret_token = 'secret_token'
+ secrets.secret_key_base = 'secret_key_base'
config.logger = Logger.new($stdout)
Rails.logger = config.logger
diff --git a/guides/rails_guides/kindle.rb b/guides/rails_guides/kindle.rb
index 09eecd5634..32926622e3 100644
--- a/guides/rails_guides/kindle.rb
+++ b/guides/rails_guides/kindle.rb
@@ -70,7 +70,7 @@ module Kindle
File.open("sections/%03d/_section.txt" % section_idx, 'w') {|f| f.puts title}
doc.xpath("//h3[@id]").each_with_index do |h3,item_idx|
subsection = h3.inner_text
- content = h3.xpath("./following-sibling::*").take_while {|x| x.name != "h3"}.map {|x| x.to_html}
+ content = h3.xpath("./following-sibling::*").take_while {|x| x.name != "h3"}.map(&:to_html)
item = Nokogiri::HTML(h3.to_html + content.join("\n"))
item_path = "sections/%03d/%03d.html" % [section_idx, item_idx]
add_head_section(item, subsection)
diff --git a/guides/source/3_0_release_notes.md b/guides/source/3_0_release_notes.md
index 46be2613ab..e985f1ab4b 100644
--- a/guides/source/3_0_release_notes.md
+++ b/guides/source/3_0_release_notes.md
@@ -138,7 +138,7 @@ More Information: - [Rails Edge Architecture](http://yehudakatz.com/2009/06/11/r
[Arel](http://github.com/brynary/arel) (or Active Relation) has been taken on as the underpinnings of Active Record and is now required for Rails. Arel provides an SQL abstraction that simplifies out Active Record and provides the underpinnings for the relation functionality in Active Record.
-More information: - [Why I wrote Arel](http://magicscalingsprinkles.wordpress.com/2010/01/28/why-i-wrote-arel/.)
+More information: - [Why I wrote Arel](https://web.archive.org/web/20120718093140/http://magicscalingsprinkles.wordpress.com/2010/01/28/why-i-wrote-arel/)
### Mail Extraction
@@ -298,7 +298,7 @@ Deprecations
More Information:
* [The Rails 3 Router: Rack it Up](http://yehudakatz.com/2009/12/26/the-rails-3-router-rack-it-up/)
-* [Revamped Routes in Rails 3](http://rizwanreza.com/2009/12/20/revamped-routes-in-rails-3)
+* [Revamped Routes in Rails 3](https://medium.com/fusion-of-thoughts/revamped-routes-in-rails-3-b6d00654e5b0)
* [Generic Actions in Rails 3](http://yehudakatz.com/2009/12/20/generic-actions-in-rails-3/)
diff --git a/guides/source/4_1_release_notes.md b/guides/source/4_1_release_notes.md
index 52a5acb75e..c7877a9cb5 100644
--- a/guides/source/4_1_release_notes.md
+++ b/guides/source/4_1_release_notes.md
@@ -136,7 +136,7 @@ end
### Action Mailer Previews
-Action Mailer previews provide a way to visually see how emails look by visiting
+Action Mailer previews provide a way to see how emails look by visiting
a special URL that renders them.
You implement a preview class whose methods return the mail object you'd like
diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md
index d9f49aac55..737922c283 100644
--- a/guides/source/4_2_release_notes.md
+++ b/guides/source/4_2_release_notes.md
@@ -3,21 +3,19 @@ Ruby on Rails 4.2 Release Notes
Highlights in Rails 4.2:
-* Active Job, Action Mailer #deliver_later
+* Active Job
+* Asynchronous mails
* Adequate Record
* Web Console
* Foreign key support
-These release notes cover only the major changes. To learn about various bug
-fixes and changes, please refer to the change logs or check out the [list of
-commits](https://github.com/rails/rails/commits/master) in the main Rails
-repository on GitHub.
+These release notes cover only the major changes. To learn about other
+features, bug fixes, and changes, please refer to the changelogs or check out
+the [list of commits](https://github.com/rails/rails/commits/4-2-stable) in
+the main Rails repository on GitHub.
--------------------------------------------------------------------------------
-NOTE: This document is a work in progress, please help to improve this by sending
-a [pull request](https://github.com/rails/rails/edit/master/guides/source/4_2_release_notes.md).
-
Upgrading to Rails 4.2
----------------------
@@ -25,96 +23,112 @@ If you're upgrading an existing application, it's a great idea to have good test
coverage before going in. You should also first upgrade to Rails 4.1 in case you
haven't and make sure your application still runs as expected before attempting
to upgrade to Rails 4.2. A list of things to watch out for when upgrading is
-available in the guide: [Upgrading Ruby on
-Rails](upgrading_ruby_on_rails.html#upgrading-from-rails-4-1-to-rails-4-2)
+available in the guide [Upgrading Ruby on
+Rails](upgrading_ruby_on_rails.html#upgrading-from-rails-4-1-to-rails-4-2).
Major Features
--------------
-### Active Job, Action Mailer #deliver_later
+### Active Job
-Active Job is a new framework in Rails 4.2. It is an adapter layer on top of
+Active Job is a new framework in Rails 4.2. It is a common interface on top of
queuing systems like [Resque](https://github.com/resque/resque), [Delayed
Job](https://github.com/collectiveidea/delayed_job),
[Sidekiq](https://github.com/mperham/sidekiq), and more.
-You can write your jobs with the Active Job API, and it'll run on all these
-queues with no changes (it comes pre-configured with an inline runner).
+Jobs written with the Active Job API run on any of the supported queues thanks
+to their respective adapters. Active Job comes pre-configured with an inline
+runner that executes jobs right away.
+
+Jobs often need to take Active Record objects as arguments. Active Job passes
+object references as URIs (uniform resource identifiers) instead of marshaling
+the object itself. The new [Global ID](https://github.com/rails/globalid)
+library builds URIs and looks up the objects they reference. Passing Active
+Record objects as job arguments just works by using Global ID internally.
-Building on top of Active Job, Action Mailer now comes with a `#deliver_later`
-method, which adds your email to be sent as a job to a queue, so it doesn't
-bog down the controller or model.
+For example, if `trashable` is an Active Record object, then this job runs
+just fine with no serialization involved:
-The new GlobalID library makes it easy to pass Active Record objects to jobs by
-serializing them in a generic form. This means you no longer have to manually
-pack and unpack your Active Records by passing ids. Just give the job the
-straight Active Record object, and it'll serialize it using GlobalID, and
-deserialize it at run time.
+```ruby
+class TrashableCleanupJob < ActiveJob::Base
+ def perform(trashable, depth)
+ trashable.cleanup(depth)
+ end
+end
+```
+
+See the [Active Job Basics](active_job_basics.html) guide for more
+information.
+
+### Asynchronous Mails
+
+Building on top of Active Job, Action Mailer now comes with a `deliver_later`
+method that sends emails via the queue, so it doesn't block the controller or
+model if the queue is asynchronous (the default inline queue blocks).
+
+Sending emails right away is still possible with `deliver_now`.
### Adequate Record
-Adequate Record is a set of refactorings that make Active Record `find` and
-`find_by` methods and some association queries upto 2x faster.
+Adequate Record is a set of performance improvements in Active Record that makes
+common `find` and `find_by` calls and some association queries up to 2x faster.
-It works by caching SQL query patterns while executing the Active Record calls.
-The cache helps skip parts of the computation involved in the transformation of
-the calls into SQL queries. More details in [Aaron Patterson's
+It works by caching common SQL queries as prepared statements and reusing them
+on similar calls, skipping most of the query-generation work on subsequent
+calls. For more details, please refer to [Aaron Patterson's blog
post](http://tenderlovemaking.com/2014/02/19/adequaterecord-pro-like-activerecord.html).
-Nothing special has to be done to activate this feature. Most `find` and
-`find_by` calls and association queries will use it automatically. Examples:
+Active Record will automatically take advantage of this feature on
+supported operations without any user involvement or code changes. Here are
+some examples of supported operations:
```ruby
-Post.find 1 # caches query pattern
-Post.find 2 # uses the cached pattern
+Post.find(1) # First call generates and cache the prepared statement
+Post.find(2) # Subsequent calls reuse the cached prepared statement
-Post.find_by_title 'first post' # caches query pattern
-Post.find_by_title 'second post' # uses the cached pattern
+Post.find_by_title('first post')
+Post.find_by_title('second post')
-post.comments # caches query pattern
-post.comments(true) # uses cached pattern
+post.comments
+post.comments(true)
```
-The caching is not used in the following scenarios:
+It's important to highlight that, as the examples above suggest, the prepared
+statements do not cache the values passed in the method calls; rather, they
+have placeholders for them.
+
+Caching is not used in the following scenarios:
- The model has a default scope
-- The model uses single table inheritance to inherit from another model
-- `find` with a list of ids. eg:
+- The model uses single table inheritance
+- `find` with a list of ids, e.g.:
```ruby
- Post.find(1,2,3)
- OR
- Post.find [1,2]
+ # not cached
+ Post.find(1, 2, 3)
+ Post.find([1,2])
```
-- `find_by` with sql fragments:
+- `find_by` with SQL fragments:
```ruby
- Post.find_by "published_at < ?", 2.weeks.ago
+ Post.find_by('published_at < ?', 2.weeks.ago)
```
### Web Console
-New applications generated from Rails 4.2 now come with the Web Console gem by
-default.
+New applications generated with Rails 4.2 now come with the [Web
+Console](https://github.com/rails/web-console) gem by default. Web Console adds
+an interactive Ruby console on every error page and provides a `console` view
+and controller helpers.
-Web Console is a set of debugging tools for your Rails application. It will add
-an interactive console on every error page, a `console` view helper and a VT100
-compatible terminal.
+The interactive console on error pages lets you execute code in the context of
+the place where the exception originated. The `console` helper, if called
+anywhere in a view or controller, launches an interactive console with the final
+context, once rendering has completed.
-The interactive console on the error pages lets you execute code where the
-exception originated. It's quite handy to introspect the state that led to the
-error.
-
-The `console` view helper launches an interactive console within the context of
-the view where it is invoked.
-
-Finally, you can launch a VT100 terminal that runs `rails console`. If you need
-to create or modify existing test data, you can do that straight from the
-browser.
-
-### Foreign key support
+### Foreign Key Support
The migration DSL now supports adding and removing foreign keys. They are dumped
to `schema.rb` as well. At this time, only the `mysql`, `mysql2` and `postgresql`
@@ -149,18 +163,18 @@ individual components for new deprecations in this release.
The following changes may require immediate action upon upgrade.
-### `render` with a String argument
+### `render` with a String Argument
-Previously, calling `render "foo/bar"` in a controller action is equivalent to
-`render file: "foo/bar"`. In Rails 4.2, this has been changed to mean `render template: "foo/bar"`
-instead. If you need to render a file, please change your code to use the
-explicit form (`render file: "foo/bar"`) instead.
+Previously, calling `render "foo/bar"` in a controller action was equivalent to
+`render file: "foo/bar"`. In Rails 4.2, this has been changed to mean
+`render template: "foo/bar"` instead. If you need to render a file, please
+change your code to use the explicit form (`render file: "foo/bar"`) instead.
-### `respond_with` / class-level `respond_to`
+### `respond_with` / Class-Level `respond_to`
-`respond_with` and the corresponding class-level `respond_to` have been moved to
-the `responders` gem. To use the following, add `gem 'responders', '~> 2.0'` to
-your Gemfile:
+`respond_with` and the corresponding class-level `respond_to` have been moved
+to the [responders](https://github.com/plataformatec/responders) gem. Add
+`gem 'responders', '~> 2.0'` to your Gemfile to use it:
```ruby
# app/controllers/users_controller.rb
@@ -191,61 +205,47 @@ class UsersController < ApplicationController
end
```
-### Default host for `rails server`
+### Default Host for `rails server`
Due to a [change in Rack](https://github.com/rack/rack/commit/28b014484a8ac0bbb388e7eaeeef159598ec64fc),
`rails server` now listens on `localhost` instead of `0.0.0.0` by default. This
-should have minimal impact on the standard development workflow as both http://127.0.0.1:3000
-and http://localhost:3000 would continue to work as before on your own machine.
+should have minimal impact on the standard development workflow as both
+http://127.0.0.1:3000 and http://localhost:3000 will continue to work as before
+on your own machine.
-However, with this change you would no longer be able to access the Rails server
-from a different machine (e.g. your development environment is in a virtual
-machine and you would like to access it from the host machine), you would need
-to start the server with `rails server -b 0.0.0.0` to restore the old behavior.
+However, with this change you will no longer be able to access the Rails
+server from a different machine, for example if your development environment
+is in a virtual machine and you would like to access it from the host machine.
+In such cases, please start the server with `rails server -b 0.0.0.0` to
+restore the old behavior.
If you do this, be sure to configure your firewall properly such that only
trusted machines on your network can access your development server.
-### Production logging
-
-The default log level in the `production` environment is now `:debug`. This
-makes it consistent with the other environments, and ensures plenty of
-information is available to diagnose problems.
-
-It can be returned to the previous level, `:info`, in the environment
-configuration:
-
-```ruby
-# config/environments/production.rb
-
-# Decrease the log volume.
-config.log_level = :info
-```
-
### HTML Sanitizer
The HTML sanitizer has been replaced with a new, more robust, implementation
-built upon Loofah and Nokogiri. The new sanitizer is more secure and its
-sanitization is more powerful and flexible.
+built upon [Loofah](https://github.com/flavorjones/loofah) and
+[Nokogiri](https://github.com/sparklemotion/nokogiri). The new sanitizer is
+more secure and its sanitization is more powerful and flexible.
-With a new sanitization algorithm, the sanitized output will change for certain
+Due to the new algorithm, the sanitized output may be different for certain
pathological inputs.
-If you have particular need for the exact output of the old sanitizer, you can
-add `rails-deprecated_sanitizer` to your Gemfile, and it will automatically
-replace the new implementation. Because it is opt-in, the legacy gem will not
-give deprecation warnings.
+If you have a particular need for the exact output of the old sanitizer, you
+can add the [rails-deprecated_sanitizer](https://github.com/kaspth/rails-deprecated_sanitizer)
+gem to the `Gemfile`, to have the old behavior. The gem does not issue
+deprecation warnings because it is opt-in.
`rails-deprecated_sanitizer` will be supported for Rails 4.2 only; it will not
be maintained for Rails 5.0.
-See [the blog post](http://blog.plataformatec.com.br/2014/07/the-new-html-sanitizer-in-rails-4-2/)
-for more detail on the changes in the new sanitizer.
+See [this blog post](http://blog.plataformatec.com.br/2014/07/the-new-html-sanitizer-in-rails-4-2/)
+for more details on the changes in the new sanitizer.
### `assert_select`
-`assert_select` is now based on Nokogiri, making it (TODO: betterer).
-
+`assert_select` is now based on [Nokogiri](https://github.com/sparklemotion/nokogiri).
As a result, some previously-valid selectors are now unsupported. If your
application is using any of these spellings, you will need to update them:
@@ -253,8 +253,13 @@ application is using any of these spellings, you will need to update them:
non-alphanumeric characters.
```
- a[href=/] => a[href="/"]
- a[href$=/] => a[href$="/"]
+ # before
+ a[href=/]
+ a[href$=/]
+
+ # now
+ a[href="/"]
+ a[href$="/"]
```
* DOMs built from HTML source containing invalid HTML with improperly
@@ -300,11 +305,24 @@ Please refer to the [Changelog][railties] for detailed changes.
### Removals
+* The `--skip-action-view` option has been removed from the
+ app generator. ([Pull Request](https://github.com/rails/rails/pull/17042))
+
* The `rails application` command has been removed without replacement.
([Pull Request](https://github.com/rails/rails/pull/11616))
### Deprecations
+* Deprecated missing `config.log_level` for production environments.
+ ([Pull Request](https://github.com/rails/rails/pull/16622))
+
+* Deprecated `rake test:all` in favor of `rake test` as it now run all tests
+ in the `test` folder.
+ ([Pull Request](https://github.com/rails/rails/pull/17348))
+
+* Deprecated `rake test:all:db` in favor of `rake test:db`.
+ ([Pull Request](https://github.com/rails/rails/pull/17348))
+
* Deprecated `Rails::Rack::LogTailer` without replacement.
([Commit](https://github.com/rails/rails/commit/84a13e019e93efaa8994b3f8303d635a7702dbce))
@@ -316,9 +334,6 @@ Please refer to the [Changelog][railties] for detailed changes.
* Added a `required` option to the model generator for associations.
([Pull Request](https://github.com/rails/rails/pull/16062))
-* Introduced an `after_bundle` callback for use in Rails templates.
- ([Pull Request](https://github.com/rails/rails/pull/16359))
-
* Introduced the `x` namespace for defining custom configuration options:
```ruby
@@ -358,20 +373,23 @@ Please refer to the [Changelog][railties] for detailed changes.
([Pull Request](https://github.com/rails/rails/pull/16129))
-* Introduced a `--skip-gems` option in the app generator to skip gems such as
- `turbolinks` and `coffee-rails` that do not have their own specific flags.
- ([Commit](https://github.com/rails/rails/commit/10565895805887d4faf004a6f71219da177f78b7))
+* Introduced a `--skip-turbolinks` option in the app generator to not generate
+ turbolinks integration.
+ ([Commit](https://github.com/rails/rails/commit/bf17c8a531bc8059d50ad731398002a3e7162a7d))
-* Introduced a `bin/setup` script to enable automated setup code when
+* Introduced a `bin/setup` script as a convention for automated setup code when
bootstrapping an application.
([Pull Request](https://github.com/rails/rails/pull/15189))
-* Changed default value for `config.assets.digest` to `true` in development.
+* Changed the default value for `config.assets.digest` to `true` in development.
([Pull Request](https://github.com/rails/rails/pull/15155))
* Introduced an API to register new extensions for `rake notes`.
([Pull Request](https://github.com/rails/rails/pull/14379))
+* Introduced an `after_bundle` callback for use in Rails templates.
+ ([Pull Request](https://github.com/rails/rails/pull/16359))
+
* Introduced `Rails.gem_version` as a convenience method to return
`Gem::Version.new(Rails.version)`.
([Pull Request](https://github.com/rails/rails/pull/14101))
@@ -384,10 +402,11 @@ Please refer to the [Changelog][action-pack] for detailed changes.
### Removals
-* `respond_with` and the class-level `respond_to` were removed from Rails and
+* `respond_with` and the class-level `respond_to` have been removed from Rails and
moved to the `responders` gem (version 2.0). Add `gem 'responders', '~> 2.0'`
to your `Gemfile` to continue using these features.
- ([Pull Request](https://github.com/rails/rails/pull/16526))
+ ([Pull Request](https://github.com/rails/rails/pull/16526),
+ [More Details](http://guides.rubyonrails.org/upgrading_ruby_on_rails.html#responders))
* Removed deprecated `AbstractController::Helpers::ClassMethods::MissingHelperError`
in favor of `AbstractController::Helpers::MissingHelperError`.
@@ -403,7 +422,7 @@ Please refer to the [Changelog][action-pack] for detailed changes.
([Commit](https://github.com/rails/rails-dom-testing/commit/b12850bc5ff23ba4b599bf2770874dd4f11bf750))
* Deprecated support for setting the `:to` option of a router to a symbol or a
- string that does not contain a `#` character:
+ string that does not contain a "#" character:
```ruby
get '/posts', to: MyRackApp => (No change necessary)
@@ -414,22 +433,22 @@ Please refer to the [Changelog][action-pack] for detailed changes.
([Commit](https://github.com/rails/rails/commit/cc26b6b7bccf0eea2e2c1a9ebdcc9d30ca7390d9))
-### Notable changes
+* Deprecated support for string keys in URL helpers:
-* Rails will now automatically include the template's digest in ETags.
- ([Pull Request](https://github.com/rails/rails/pull/16527))
+ ```ruby
+ # bad
+ root_path('controller' => 'posts', 'action' => 'index')
-* `render nothing: true` or rendering a `nil` body no longer add a single
- space padding to the response body.
- ([Pull Request](https://github.com/rails/rails/pull/14883))
+ # good
+ root_path(controller: 'posts', action: 'index')
+ ```
-* Introduced the `always_permitted_parameters` option to configure which
- parameters are permitted globally. The default value of this configuration
- is `['controller', 'action']`.
- ([Pull Request](https://github.com/rails/rails/pull/15933))
+ ([Pull Request](https://github.com/rails/rails/pull/17743))
+
+### Notable changes
-* The `*_filter` family methods have been removed from the documentation. Their
- usage is discouraged in favor of the `*_action` family methods:
+* The `*_filter` family of methods have been removed from the documentation. Their
+ usage is discouraged in favor of the `*_action` family of methods:
```
after_filter => after_action
@@ -454,16 +473,28 @@ Please refer to the [Changelog][action-pack] for detailed changes.
(Commit [1](https://github.com/rails/rails/commit/6c5f43bab8206747a8591435b2aa0ff7051ad3de),
[2](https://github.com/rails/rails/commit/489a8f2a44dc9cea09154ee1ee2557d1f037c7d4))
-* Added HTTP method `MKCALENDAR` from RFC-4791
+* `render nothing: true` or rendering a `nil` body no longer add a single
+ space padding to the response body.
+ ([Pull Request](https://github.com/rails/rails/pull/14883))
+
+* Rails now automatically includes the template's digest in ETags.
+ ([Pull Request](https://github.com/rails/rails/pull/16527))
+
+* Segments that are passed into URL helpers are now automatically escaped.
+ ([Commit](https://github.com/rails/rails/commit/5460591f0226a9d248b7b4f89186bd5553e7768f))
+
+* Introduced the `always_permitted_parameters` option to configure which
+ parameters are permitted globally. The default value of this configuration
+ is `['controller', 'action']`.
+ ([Pull Request](https://github.com/rails/rails/pull/15933))
+
+* Added the HTTP method `MKCALENDAR` from [RFC 4791](https://tools.ietf.org/html/rfc4791).
([Pull Request](https://github.com/rails/rails/pull/15121))
* `*_fragment.action_controller` notifications now include the controller
and action name in the payload.
([Pull Request](https://github.com/rails/rails/pull/14137))
-* Segments that are passed into URL helpers are now automatically escaped.
- ([Commit](https://github.com/rails/rails/commit/5460591f0226a9d248b7b4f89186bd5553e7768f))
-
* Improved the Routing Error page with fuzzy matching for route search.
([Pull Request](https://github.com/rails/rails/pull/14619))
@@ -471,28 +502,15 @@ Please refer to the [Changelog][action-pack] for detailed changes.
([Pull Request](https://github.com/rails/rails/pull/14280))
* When the Rails server is set to serve static assets, gzip assets will now be
- served if the client supports it and a pre-generated gzip file (.gz) is on disk.
+ served if the client supports it and a pre-generated gzip file (`.gz`) is on disk.
By default the asset pipeline generates `.gz` files for all compressible assets.
Serving gzip files minimizes data transfer and speeds up asset requests. Always
[use a CDN](http://guides.rubyonrails.org/asset_pipeline.html#cdns) if you are
serving assets from your Rails server in production.
([Pull Request](https://github.com/rails/rails/pull/16466))
-* The way `assert_select` works has changed; specifically a different library
- is used to interpret css selectors, build the transient DOM that the
- selectors are applied against, and to extract the data from that DOM. These
- changes should only affect edge cases. Examples:
- * Values in attribute selectors may need to be quoted if they contain
- non-alphanumeric characters.
- * DOMs built from HTML source containing invalid HTML with improperly
- nested elements may differ.
- * If the data selected contains entities, the value selected for comparison
- used to be raw (e.g. `AT&amp;T`), and now is evaluated
- (e.g. `AT&T`).
-
-
Action View
--------------
+-----------
Please refer to the [Changelog][action-view] for detailed changes.
@@ -513,16 +531,16 @@ Please refer to the [Changelog][action-view] for detailed changes.
`render file: "foo/bar"`.
([Pull Request](https://github.com/rails/rails/pull/16888))
-* Introduced a `#{partial_name}_iteration` special local variable for use with
- partials that are rendered with a collection. It provides access to the
- current state of the iteration via the `#index`, `#size`, `#first?` and
- `#last?` methods.
- ([Pull Request](https://github.com/rails/rails/pull/7698))
-
* The form helpers no longer generate a `<div>` element with inline CSS around
the hidden fields.
([Pull Request](https://github.com/rails/rails/pull/14738))
+* Introduced a `#{partial_name}_iteration` special local variable for use with
+ partials that are rendered with a collection. It provides access to the
+ current state of the iteration via the `index`, `size`, `first?` and
+ `last?` methods.
+ ([Pull Request](https://github.com/rails/rails/pull/7698))
+
* Placeholder I18n follows the same convention as `label` I18n.
([Pull Request](https://github.com/rails/rails/pull/16438))
@@ -537,11 +555,15 @@ Please refer to the [Changelog][action-mailer] for detailed changes.
* Deprecated `*_path` helpers in mailers. Always use `*_url` helpers instead.
([Pull Request](https://github.com/rails/rails/pull/15840))
-* Deprecated `deliver` / `deliver!` in favour of `deliver_now` / `deliver_now!`.
+* Deprecated `deliver` / `deliver!` in favor of `deliver_now` / `deliver_now!`.
([Pull Request](https://github.com/rails/rails/pull/16582))
### Notable changes
+* `link_to` and `url_for` generate absolute URLs by default in templates,
+ it is no longer needed to pass `only_path: false`.
+ ([Commit](https://github.com/rails/rails/commit/9685080a7677abfa5d288a81c3e078368c6bb67c))
+
* Introduced `deliver_later` which enqueues a job on the application's queue
to deliver emails asynchronously.
([Pull Request](https://github.com/rails/rails/pull/16485))
@@ -570,7 +592,7 @@ Please refer to the [Changelog][active-record] for detailed changes.
* Removed unused `:timestamp` type. Transparently alias it to `:datetime`
in all cases. Fixes inconsistencies when column types are sent outside of
- `ActiveRecord`, such as for XML serialization.
+ Active Record, such as for XML serialization.
([Pull Request](https://github.com/rails/rails/pull/15184))
### Deprecations
@@ -578,112 +600,116 @@ Please refer to the [Changelog][active-record] for detailed changes.
* Deprecated swallowing of errors inside `after_commit` and `after_rollback`.
([Pull Request](https://github.com/rails/rails/pull/16537))
-* Deprecated calling `DatabaseTasks.load_schema` without a connection. Use
- `DatabaseTasks.load_schema_current` instead.
- ([Commit](https://github.com/rails/rails/commit/f15cef67f75e4b52fd45655d7c6ab6b35623c608))
-
-* Deprecated `Reflection#source_macro` without replacement as it is no longer
- needed in Active Record.
- ([Pull Request](https://github.com/rails/rails/pull/16373))
-
* Deprecated broken support for automatic detection of counter caches on
`has_many :through` associations. You should instead manually specify the
counter cache on the `has_many` and `belongs_to` associations for the
through records.
([Pull Request](https://github.com/rails/rails/pull/15754))
-* Deprecated `serialized_attributes` without replacement.
- ([Pull Request](https://github.com/rails/rails/pull/15704))
-
-* Deprecated returning `nil` from `column_for_attribute` when no column
- exists. It will return a null object in Rails 5.0
- ([Pull Request](https://github.com/rails/rails/pull/15878))
-
-* Deprecated using `.joins`, `.preload` and `.eager_load` with associations
- that depends on the instance state (i.e. those defined with a scope that
- takes an argument) without replacement.
- ([Commit](https://github.com/rails/rails/commit/ed56e596a0467390011bc9d56d462539776adac1))
-
* Deprecated passing Active Record objects to `.find` or `.exists?`. Call
- `#id` on the objects first.
+ `id` on the objects first.
(Commit [1](https://github.com/rails/rails/commit/d92ae6ccca3bcfd73546d612efaea011270bd270),
[2](https://github.com/rails/rails/commit/d35f0033c7dec2b8d8b52058fb8db495d49596f7))
* Deprecated half-baked support for PostgreSQL range values with excluding
beginnings. We currently map PostgreSQL ranges to Ruby ranges. This conversion
- is not fully possible because the Ruby range does not support excluded
- beginnings.
+ is not fully possible because Ruby ranges do not support excluded beginnings.
The current solution of incrementing the beginning is not correct
and is now deprecated. For subtypes where we don't know how to increment
- (e.g. `#succ` is not defined) it will raise an `ArgumentError` for ranges
+ (e.g. `succ` is not defined) it will raise an `ArgumentError` for ranges
with excluding beginnings.
-
([Commit](https://github.com/rails/rails/commit/91949e48cf41af9f3e4ffba3e5eecf9b0a08bfc3))
-### Notable changes
+* Deprecated calling `DatabaseTasks.load_schema` without a connection. Use
+ `DatabaseTasks.load_schema_current` instead.
+ ([Commit](https://github.com/rails/rails/commit/f15cef67f75e4b52fd45655d7c6ab6b35623c608))
-* The PostgreSQL adapter now supports the `JSONB` datatype in PostgreSQL 9.4+.
- ([Pull Request](https://github.com/rails/rails/pull/16220))
+* Deprecated `sanitize_sql_hash_for_conditions` without replacement. Using a
+ `Relation` for performing queries and updates is the preferred API.
+ ([Commit](https://github.com/rails/rails/commit/d5902c9e))
-* The `#references` method in migrations now supports a `type` option for
- specifying the type of the foreign key (e.g. `:uuid`).
- ([Pull Request](https://github.com/rails/rails/pull/16231))
+* Deprecated `Reflection#source_macro` without replacement as it is no longer
+ needed in Active Record.
+ ([Pull Request](https://github.com/rails/rails/pull/16373))
-* Added a `:required` option to singular associations, which defines a
- presence validation on the association.
- ([Pull Request](https://github.com/rails/rails/pull/16056))
+* Deprecated `serialized_attributes` without replacement.
+ ([Pull Request](https://github.com/rails/rails/pull/15704))
-* Introduced `ActiveRecord::Base#validate!` that raises `RecordInvalid` if the
- record is invalid.
- ([Pull Request](https://github.com/rails/rails/pull/8639))
+* Deprecated returning `nil` from `column_for_attribute` when no column
+ exists. It will return a null object in Rails 5.0.
+ ([Pull Request](https://github.com/rails/rails/pull/15878))
-* `ActiveRecord::Base#reload` now behaves the same as `m = Model.find(m.id)`,
- meaning that it no longer retains the extra attributes from custom
- `select`s.
- ([Pull Request](https://github.com/rails/rails/pull/15866))
+* Deprecated using `.joins`, `.preload` and `.eager_load` with associations
+ that depend on the instance state (i.e. those defined with a scope that
+ takes an argument) without replacement.
+ ([Commit](https://github.com/rails/rails/commit/ed56e596a0467390011bc9d56d462539776adac1))
-* Introduced the `bin/rake db:purge` task to empty the database for the
- current environment.
- ([Commit](https://github.com/rails/rails/commit/e2f232aba15937a4b9d14bd91e0392c6d55be58d))
+### Notable changes
+
+* Added a `:required` option to singular associations, which defines a
+ presence validation on the association.
+ ([Pull Request](https://github.com/rails/rails/pull/16056))
* `ActiveRecord::Dirty` now detects in-place changes to mutable values.
- Serialized attributes on ActiveRecord models will no longer save when
+ Serialized attributes on Active Record models are no longer saved when
unchanged. This also works with other types such as string columns and json
columns on PostgreSQL.
(Pull Requests [1](https://github.com/rails/rails/pull/15674),
[2](https://github.com/rails/rails/pull/15786),
[3](https://github.com/rails/rails/pull/15788))
-* Added support for `#pretty_print` in `ActiveRecord::Base` objects.
- ([Pull Request](https://github.com/rails/rails/pull/15172))
+* Introduced the `db:purge` Rake task to empty the database for the
+ current environment.
+ ([Commit](https://github.com/rails/rails/commit/e2f232aba15937a4b9d14bd91e0392c6d55be58d))
+
+* Introduced `ActiveRecord::Base#validate!` that raises
+ `ActiveRecord::RecordInvalid` if the record is invalid.
+ ([Pull Request](https://github.com/rails/rails/pull/8639))
+
+* Introduced `validate` as an alias for `valid?`.
+ ([Pull Request](https://github.com/rails/rails/pull/14456))
+
+* `touch` now accepts multiple attributes to be touched at once.
+ ([Pull Request](https://github.com/rails/rails/pull/14423))
-* PostgreSQL and SQLite adapters no longer add a default limit of 255
+* The PostgreSQL adapter now supports the `jsonb` datatype in PostgreSQL 9.4+.
+ ([Pull Request](https://github.com/rails/rails/pull/16220))
+
+* The PostgreSQL and SQLite adapters no longer add a default limit of 255
characters on string columns.
([Pull Request](https://github.com/rails/rails/pull/14579))
+* Added support for the `citext` column type in the PostgreSQL adapter.
+ ([Pull Request](https://github.com/rails/rails/pull/12523))
+
+* Added support for user-created range types in the PostgreSQL adapter.
+ ([Commit](https://github.com/rails/rails/commit/4cb47167e747e8f9dc12b0ddaf82bdb68c03e032))
+
* `sqlite3:///some/path` now resolves to the absolute system path
`/some/path`. For relative paths, use `sqlite3:some/path` instead.
(Previously, `sqlite3:///some/path` resolved to the relative path
- `some/path`. This behaviour was deprecated on Rails 4.1).
+ `some/path`. This behavior was deprecated on Rails 4.1).
([Pull Request](https://github.com/rails/rails/pull/14569))
-* Introduced `#validate` as an alias for `#valid?`.
- ([Pull Request](https://github.com/rails/rails/pull/14456))
-
-* `#touch` now accepts multiple attributes to be touched at once.
- ([Pull Request](https://github.com/rails/rails/pull/14423))
-
* Added support for fractional seconds for MySQL 5.6 and above.
(Pull Request [1](https://github.com/rails/rails/pull/8240),
[2](https://github.com/rails/rails/pull/14359))
-* Added support for the `citext` column type in PostgreSQL adapter.
- ([Pull Request](https://github.com/rails/rails/pull/12523))
+* Added `ActiveRecord::Base#pretty_print` to pretty print models.
+ ([Pull Request](https://github.com/rails/rails/pull/15172))
-* Added support for user-created range types in PostgreSQL adapter.
- ([Commit](https://github.com/rails/rails/commit/4cb47167e747e8f9dc12b0ddaf82bdb68c03e032))
+* `ActiveRecord::Base#reload` now behaves the same as `m = Model.find(m.id)`,
+ meaning that it no longer retains the extra attributes from custom
+ `SELECT`s.
+ ([Pull Request](https://github.com/rails/rails/pull/15866))
+* `ActiveRecord::Base#reflections` now returns a hash with string keys instead
+ of symbol keys. ([Pull Request](https://github.com/rails/rails/pull/17718))
+
+* The `references` method in migrations now supports a `type` option for
+ specifying the type of the foreign key (e.g. `:uuid`).
+ ([Pull Request](https://github.com/rails/rails/pull/16231))
Active Model
------------
@@ -701,11 +727,14 @@ Please refer to the [Changelog][active-model] for detailed changes.
([Pull Request](https://github.com/rails/rails/pull/16180))
* Deprecated `ActiveModel::Dirty#reset_changes` in favor of
- `#clear_changes_information`.
+ `clear_changes_information`.
([Pull Request](https://github.com/rails/rails/pull/16180))
### Notable changes
+* Introduced `validate` as an alias for `valid?`.
+ ([Pull Request](https://github.com/rails/rails/pull/14456))
+
* Introduced the `restore_attributes` method in `ActiveModel::Dirty` to restore
the changed (dirty) attributes to their previous values.
(Pull Request [1](https://github.com/rails/rails/pull/14861),
@@ -719,10 +748,6 @@ Please refer to the [Changelog][active-model] for detailed changes.
characters if validations are enabled.
([Pull Request](https://github.com/rails/rails/pull/15708))
-* Introduced `#validate` as an alias for `#valid?`.
- ([Pull Request](https://github.com/rails/rails/pull/14456))
-
-
Active Support
--------------
@@ -753,15 +778,15 @@ Please refer to the [Changelog][active-support] for detailed changes.
### Notable changes
-* `Object#try` and `Object#try!` can now be used without an explicit receiver.
- ([Commit](https://github.com/rails/rails/commit/5e51bdda59c9ba8e5faf86294e3e431bd45f1830),
- [Pull Request](https://github.com/rails/rails/pull/17361))
-
-* Introduced new configuration option `active_support.test_order` for
+* Introduced a new configuration option `active_support.test_order` for
specifying the order test cases are executed. This option currently defaults
to `:sorted` but will be changed to `:random` in Rails 5.0.
([Commit](https://github.com/rails/rails/commit/53e877f7d9291b2bf0b8c425f9e32ef35829f35b))
+* `Object#try` and `Object#try!` can now be used without an explicit receiver in the block.
+ ([Commit](https://github.com/rails/rails/commit/5e51bdda59c9ba8e5faf86294e3e431bd45f1830),
+ [Pull Request](https://github.com/rails/rails/pull/17361))
+
* The `travel_to` test helper now truncates the `usec` component to 0.
([Commit](https://github.com/rails/rails/commit/9f6e82ee4783e491c20f5244a613fdeb4024beb5))
@@ -769,7 +794,7 @@ Please refer to the [Changelog][active-support] for detailed changes.
(Commit [1](https://github.com/rails/rails/commit/702ad710b57bef45b081ebf42e6fa70820fdd810),
[2](https://github.com/rails/rails/commit/64d91122222c11ad3918cc8e2e3ebc4b0a03448a))
-* `Object#with_options` can now be used without an explicit receiver.
+* `Object#with_options` can now be used without an explicit receiver in the block.
([Pull Request](https://github.com/rails/rails/pull/16339))
* Introduced `String#truncate_words` to truncate a string by a number of words.
diff --git a/guides/source/_welcome.html.erb b/guides/source/_welcome.html.erb
index f2315bfe22..614d69ecdd 100644
--- a/guides/source/_welcome.html.erb
+++ b/guides/source/_welcome.html.erb
@@ -15,5 +15,5 @@
</p>
<% end %>
<p>
- The guides for earlier releases: <a href="http://guides.rubyonrails.org/v4.1.6/">Rails 4.1.6</a>, <a href="http://guides.rubyonrails.org/v4.0.10/">Rails 4.0.10</a>, <a href="http://guides.rubyonrails.org/v3.2.19/">Rails 3.2.19</a> and <a href="http://guides.rubyonrails.org/v2.3.11/">Rails 2.3.11</a>.
+ The guides for earlier releases: <a href="http://guides.rubyonrails.org/v4.1.8/">Rails 4.1.8</a>, <a href="http://guides.rubyonrails.org/v4.0.12/">Rails 4.0.12</a>, <a href="http://guides.rubyonrails.org/v3.2.21/">Rails 3.2.21</a> and <a href="http://guides.rubyonrails.org/v2.3.11/">Rails 2.3.11</a>.
</p>
diff --git a/guides/source/action_mailer_basics.md b/guides/source/action_mailer_basics.md
index f6c974c87a..ba7c16aa1d 100644
--- a/guides/source/action_mailer_basics.md
+++ b/guides/source/action_mailer_basics.md
@@ -35,10 +35,26 @@ views.
```bash
$ bin/rails generate mailer UserMailer
create app/mailers/user_mailer.rb
+create app/mailers/application_mailer.rb
invoke erb
create app/views/user_mailer
+create app/views/layouts/mailer.text.erb
+create app/views/layouts/mailer.html.erb
invoke test_unit
create test/mailers/user_mailer_test.rb
+create test/mailers/previews/user_mailer_preview.rb
+```
+
+```ruby
+# app/mailers/application_mailer.rb
+class ApplicationMailer < ActionMailer::Base
+ default "from@example.com"
+ layout 'mailer'
+end
+
+# app/mailers/user_mailer.rb
+class UserMailer < ApplicationMailer
+end
```
As you can see, you can generate mailers just like you use other generators with
@@ -63,8 +79,7 @@ delivered via email.
`app/mailers/user_mailer.rb` contains an empty mailer:
```ruby
-class UserMailer < ActionMailer::Base
- default from: 'from@example.com'
+class UserMailer < ApplicationMailer
end
```
@@ -72,7 +87,7 @@ Let's add a method called `welcome_email`, that will send an email to the user's
registered email address:
```ruby
-class UserMailer < ActionMailer::Base
+class UserMailer < ApplicationMailer
default from: 'notifications@example.com'
def welcome_email(user)
@@ -348,7 +363,7 @@ for the HTML version and `welcome_email.text.erb` for the plain text version.
To change the default mailer view for your action you do something like:
```ruby
-class UserMailer < ActionMailer::Base
+class UserMailer < ApplicationMailer
default from: 'notifications@example.com'
def welcome_email(user)
@@ -370,7 +385,7 @@ If you want more flexibility you can also pass a block and render specific
templates or even render inline or text without using a template file:
```ruby
-class UserMailer < ActionMailer::Base
+class UserMailer < ApplicationMailer
default from: 'notifications@example.com'
def welcome_email(user)
@@ -400,7 +415,7 @@ layout.
In order to use a different file, call `layout` in your mailer:
```ruby
-class UserMailer < ActionMailer::Base
+class UserMailer < ApplicationMailer
layout 'awesome' # use awesome.(html|text).erb as the layout
end
```
@@ -412,7 +427,7 @@ You can also pass in a `layout: 'layout_name'` option to the render call inside
the format block to specify different layouts for different formats:
```ruby
-class UserMailer < ActionMailer::Base
+class UserMailer < ApplicationMailer
def welcome_email(user)
mail(to: user.email) do |format|
format.html { render layout: 'my_layout' }
@@ -455,16 +470,7 @@ By using the full URL, your links will now work in your emails.
#### generating URLs with `url_for`
-You need to pass the `only_path: false` option when using `url_for`. This will
-ensure that absolute URLs are generated because the `url_for` view helper will,
-by default, generate relative URLs when a `:host` option isn't explicitly
-provided.
-
-```erb
-<%= url_for(controller: 'welcome',
- action: 'greeting',
- only_path: false) %>
-```
+`url_for` generate full URL by default in templates.
If you did not configure the `:host` option globally make sure to pass it to
`url_for`.
@@ -476,9 +482,6 @@ If you did not configure the `:host` option globally make sure to pass it to
action: 'greeting') %>
```
-NOTE: When you explicitly pass the `:host` Rails will always generate absolute
-URLs, so there is no need to pass `only_path: false`.
-
#### generating URLs with named routes
Email clients have no web context and so paths have no base URL to form complete
@@ -510,7 +513,7 @@ while delivering emails, you can do this using `delivery_method_options` in the
mailer action.
```ruby
-class UserMailer < ActionMailer::Base
+class UserMailer < ApplicationMailer
def welcome_email(user, company)
@user = user
@url = user_url(@user)
@@ -532,7 +535,7 @@ option. In such cases don't forget to add the `:content_type` option. Rails
will default to `text/plain` otherwise.
```ruby
-class UserMailer < ActionMailer::Base
+class UserMailer < ApplicationMailer
def welcome_email(user, email_body)
mail(to: user.email,
body: email_body,
@@ -562,7 +565,7 @@ mailer, and pass the email object to the mailer `receive` instance
method. Here's an example:
```ruby
-class UserMailer < ActionMailer::Base
+class UserMailer < ApplicationMailer
def receive(email)
page = Page.find_by(address: email.to.first)
page.emails.create(
@@ -598,7 +601,7 @@ Action Mailer allows for you to specify a `before_action`, `after_action` and
using instance variables set in your mailer action.
```ruby
-class UserMailer < ActionMailer::Base
+class UserMailer < ApplicationMailer
after_action :set_delivery_options,
:prevent_delivery_to_guests,
:set_business_headers
diff --git a/guides/source/action_view_overview.md b/guides/source/action_view_overview.md
index 683e633668..f4d5bb8272 100644
--- a/guides/source/action_view_overview.md
+++ b/guides/source/action_view_overview.md
@@ -7,7 +7,6 @@ After reading this guide, you will know:
* How best to use templates, partials, and layouts.
* What helpers are provided by Action View and how to make your own.
* How to use localized views.
-* How to use Action View outside of Rails.
--------------------------------------------------------------------------------
diff --git a/guides/source/active_job_basics.md b/guides/source/active_job_basics.md
index ca851371a9..748467866d 100644
--- a/guides/source/active_job_basics.md
+++ b/guides/source/active_job_basics.md
@@ -23,7 +23,7 @@ clean-ups, to billing charges, to mailings. Anything that can be chopped up
into small units of work and run in parallel, really.
-The Purpose of the Active Job
+The Purpose of Active Job
-----------------------------
The main point is to ensure that all Rails apps will have a job infrastructure
in place, even if it's in the form of an "immediate runner". We can then have
@@ -56,9 +56,6 @@ You can also create a job that will run on a specific queue:
$ bin/rails generate job guests_cleanup --queue urgent
```
-As you can see, you can generate jobs just like you use other generators with
-Rails.
-
If you don't want to use a generator, you could create your own file inside of
`app/jobs`, just make sure that it inherits from `ActiveJob::Base`.
@@ -107,14 +104,19 @@ Active Job has built-in adapters for multiple queueing backends (Sidekiq,
Resque, Delayed Job and others). To get an up-to-date list of the adapters
see the API Documentation for [ActiveJob::QueueAdapters](http://api.rubyonrails.org/classes/ActiveJob/QueueAdapters.html).
-### Changing the Backend
+### Setting the Backend
-You can easily change your queueing backend:
+You can easily set your queueing backend:
```ruby
-# be sure to have the adapter gem in your Gemfile and follow
-# the adapter specific installation and deployment instructions
-config.active_job.queue_adapter = :sidekiq
+# config/application.rb
+module YourApp
+ class Application < Rails::Application
+ # Be sure to have the adapter's gem in your Gemfile and follow
+ # the adapter's specific installation and deployment instructions.
+ config.active_job.queue_adapter = :sidekiq
+ end
+end
```
@@ -149,7 +151,7 @@ class GuestsCleanupJob < ActiveJob::Base
end
# Now your job will run on queue production_low_priority on your
-# production environment and on beta_low_priority on your beta
+# production environment and on staging_low_priority on your staging
# environment
```
@@ -248,7 +250,7 @@ end
```
-ActionMailer
+Action Mailer
------------
One of the most common jobs in a modern web application is sending emails outside
diff --git a/guides/source/active_record_postgresql.md b/guides/source/active_record_postgresql.md
index 6c94218ef6..a2681a80e9 100644
--- a/guides/source/active_record_postgresql.md
+++ b/guides/source/active_record_postgresql.md
@@ -103,11 +103,6 @@ profile.settings # => {"color"=>"blue", "resolution"=>"800x600"}
profile.settings = {"color" => "yellow", "resolution" => "1280x1024"}
profile.save!
-
-## you need to call _will_change! if you are editing the store in place
-profile.settings["color"] = "green"
-profile.settings_will_change!
-profile.save!
```
### JSON
@@ -219,7 +214,7 @@ Currently there is no special support for enumerated types. They are mapped as
normal text columns:
```ruby
-# db/migrate/20131220144913_create_events.rb
+# db/migrate/20131220144913_create_articles.rb
execute <<-SQL
CREATE TYPE article_status AS ENUM ('draft', 'published');
SQL
@@ -281,7 +276,7 @@ end
# Usage
User.create settings: "01010011"
user = User.first
-user.settings # => "(Paris,Champs-Élysées)"
+user.settings # => "01010011"
user.settings = "0xAF"
user.settings # => 10101111
user.save!
diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md
index f6f96b79c6..7b11092f3d 100644
--- a/guides/source/active_support_core_extensions.md
+++ b/guides/source/active_support_core_extensions.md
@@ -1011,7 +1011,7 @@ self.default_params = {
}.freeze
```
-They can be also accessed and overridden at the instance level.
+They can also be accessed and overridden at the instance level.
```ruby
A.x = 1
@@ -1447,7 +1447,7 @@ Returns the substring of the string starting at position `position`:
"hello".from(0) # => "hello"
"hello".from(2) # => "llo"
"hello".from(-2) # => "lo"
-"hello".from(10) # => "" if < 1.9, nil in 1.9
+"hello".from(10) # => nil
```
NOTE: Defined in `active_support/core_ext/string/access.rb`.
diff --git a/guides/source/association_basics.md b/guides/source/association_basics.md
index 61490ceb54..a12f5638e3 100644
--- a/guides/source/association_basics.md
+++ b/guides/source/association_basics.md
@@ -1532,8 +1532,6 @@ Controls what happens to the associated objects when their owner is destroyed:
* `: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
-NOTE: This option is ignored when you use the `:through` option on the association.
-
##### `:foreign_key`
By convention, Rails assumes that the column used to hold the foreign key on the other model is the name of this model with the suffix `_id` added. The `:foreign_key` option lets you set the name of the foreign key directly:
diff --git a/guides/source/command_line.md b/guides/source/command_line.md
index b9014724bd..e72bc81766 100644
--- a/guides/source/command_line.md
+++ b/guides/source/command_line.md
@@ -61,7 +61,7 @@ With no further work, `rails server` will run our new shiny Rails app:
$ cd commandsapp
$ bin/rails server
=> Booting WEBrick
-=> Rails 4.2.0 application starting in development on http://0.0.0.0:3000
+=> Rails 4.2.0 application starting in development on http://localhost:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2013-08-07 02:00:01] INFO WEBrick 1.3.1
@@ -79,7 +79,7 @@ The server can be run on a different port using the `-p` option. The default dev
$ bin/rails server -e production -p 4000
```
-The `-b` option binds Rails to the specified IP, by default it is 0.0.0.0. You can run a server as a daemon by passing a `-d` option.
+The `-b` option binds Rails to the specified IP, by default it is localhost. You can run a server as a daemon by passing a `-d` option.
### `rails generate`
@@ -368,8 +368,7 @@ Rake is Ruby Make, a standalone Ruby utility that replaces the Unix utility 'mak
You can get a list of Rake tasks available to you, which will often depend on your current directory, by typing `rake --tasks`. Each task has a description, and should help you find the thing you need.
-To get the full backtrace for running rake task you can pass the option
-```--trace``` to command line, for example ```rake db:create --trace```.
+To get the full backtrace for running rake task you can pass the option ```--trace``` to command line, for example ```rake db:create --trace```.
```bash
$ bin/rake --tasks
@@ -394,16 +393,11 @@ INFO: You can also use ```rake -T``` to get the list of tasks.
```bash
$ bin/rake about
About your application's environment
+Rails version 4.2.0
Ruby version 1.9.3 (x86_64-linux)
RubyGems version 1.3.6
Rack version 1.3
-Rails version 4.2.0
JavaScript Runtime Node.js (V8)
-Active Record version 4.2.0
-Action Pack version 4.2.0
-Action View version 4.2.0
-Action Mailer version 4.2.0
-Active Support version 4.2.0
Middleware Rack::Sendfile, ActionDispatch::Static, Rack::Lock, #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x007ffd131a7c88>, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::DebugExceptions, ActionDispatch::RemoteIp, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::Migration::CheckPending, ActiveRecord::ConnectionAdapters::ConnectionManagement, ActiveRecord::QueryCache, ActionDispatch::Cookies, ActionDispatch::Session::CookieStore, ActionDispatch::Flash, ActionDispatch::ParamsParser, Rack::Head, Rack::ConditionalGet, Rack::ETag
Application root /home/foobar/commandsapp
Environment development
@@ -413,10 +407,7 @@ Database schema version 20110805173523
### `assets`
-You can precompile the assets in `app/assets` using `rake assets:precompile`,
-and remove older compiled assets using `rake assets:clean`. The `assets:clean`
-task allows for rolling deploys that may still be linking to an old asset while
-the new assets are being built.
+You can precompile the assets in `app/assets` using `rake assets:precompile`, and remove older compiled assets using `rake assets:clean`. The `assets:clean` task allows for rolling deploys that may still be linking to an old asset while the new assets are being built.
If you want to clear `public/assets` completely, you can use `rake assets:clobber`.
@@ -503,7 +494,7 @@ Rails comes with a test suite called Minitest. Rails owes its stability to the u
### `tmp`
-The `Rails.root/tmp` directory is, like the *nix /tmp directory, the holding place for temporary files like sessions (if you're using a file store for files), process id files, and cached actions.
+The `Rails.root/tmp` directory is, like the *nix /tmp directory, the holding place for temporary files like sessions (if you're using a file store for sessions), process id files, and cached actions.
The `tmp:` namespaced tasks will help you clear and create the `Rails.root/tmp` directory:
diff --git a/guides/source/configuring.md b/guides/source/configuring.md
index 58c3f217eb..7688962c01 100644
--- a/guides/source/configuring.md
+++ b/guides/source/configuring.md
@@ -153,7 +153,7 @@ pipeline is enabled. It is set to true by default.
* `config.assets.manifest` defines the full path to be used for the asset precompiler's manifest file. Defaults to a file named `manifest-<random>.json` in the `config.assets.prefix` directory within the public folder.
-* `config.assets.digest` enables the use of MD5 fingerprints in asset names. Set to `true` by default in `production.rb`.
+* `config.assets.digest` enables the use of MD5 fingerprints in asset names. Set to `true` by default in `production.rb` and `development.rb`.
* `config.assets.debug` disables the concatenation and compression of assets. Set to `true` by default in `development.rb`.
@@ -214,7 +214,7 @@ Every Rails application comes with a standard set of middleware which it uses in
* `ActionDispatch::Flash` sets up the `flash` keys. Only available if `config.action_controller.session_store` is set to a value.
* `ActionDispatch::ParamsParser` parses out parameters from the request into `params`.
* `Rack::MethodOverride` allows the method to be overridden if `params[:_method]` is set. This is the middleware which supports the PATCH, PUT, and DELETE HTTP method types.
-* `ActionDispatch::Head` converts HEAD requests to GET requests and serves them as so.
+* `Rack::Head` converts HEAD requests to GET requests and serves them as so.
Besides these usual middleware, you can add your own by using the `config.middleware.use` method:
@@ -225,13 +225,13 @@ config.middleware.use Magical::Unicorns
This will put the `Magical::Unicorns` middleware on the end of the stack. You can use `insert_before` if you wish to add a middleware before another.
```ruby
-config.middleware.insert_before ActionDispatch::Head, Magical::Unicorns
+config.middleware.insert_before Rack::Head, Magical::Unicorns
```
There's also `insert_after` which will insert a middleware after another:
```ruby
-config.middleware.insert_after ActionDispatch::Head, Magical::Unicorns
+config.middleware.insert_after Rack::Head, Magical::Unicorns
```
Middlewares can also be completely swapped out and replaced with others:
diff --git a/guides/source/documents.yaml b/guides/source/documents.yaml
index 4c98d3e1d5..1b838201cc 100644
--- a/guides/source/documents.yaml
+++ b/guides/source/documents.yaml
@@ -171,7 +171,6 @@
name: Ruby on Rails 4.2 Release Notes
url: 4_2_release_notes.html
description: Release notes for Rails 4.2.
- work_in_progress: true
-
name: Ruby on Rails 4.1 Release Notes
url: 4_1_release_notes.html
diff --git a/guides/source/engines.md b/guides/source/engines.md
index 21ac941ac0..a1f2da18ed 100644
--- a/guides/source/engines.md
+++ b/guides/source/engines.md
@@ -32,7 +32,7 @@ directory structure, and are both generated using the `rails plugin new`
generator. The difference is that an engine is considered a "full plugin" by
Rails (as indicated by the `--full` option that's passed to the generator
command). We'll actually be using the `--mountable` option here, which includes
-all the features of `--full`, and then some. This guide will refer to these
+all the features of `--full`, and then some. This guide will refer to these
"full plugins" simply as "engines" throughout. An engine **can** be a plugin,
and a plugin **can** be an engine.
@@ -1036,31 +1036,42 @@ functionality, especially controllers. This means that if you were to make a
typical `GET` to a controller in a controller's functional test like this:
```ruby
-get :index
+module Blorgh
+ class FooControllerTest < ActionController::TestCase
+ def test_index
+ get :index
+ ...
+ end
+ end
+end
```
It may not function correctly. This is because the application doesn't know how
to route these requests to the engine unless you explicitly tell it **how**. To
-do this, you must also pass the `:use_route` option as a parameter on these
-requests:
+do this, you must set the `@routes` instance variable to the engine's route set
+in your setup code:
```ruby
-get :index, use_route: :blorgh
+module Blorgh
+ class FooControllerTest < ActionController::TestCase
+ setup do
+ @routes = Engine.routes
+ end
+
+ def test_index
+ get :index
+ ...
+ end
+ end
+end
```
This tells the application that you still want to perform a `GET` request to the
`index` action of this controller, but you want to use the engine's route to get
there, rather than the application's one.
-Another way to do this is to assign the `@routes` instance variable to `Engine.routes` in your test setup:
-
-```ruby
-setup do
- @routes = Engine.routes
-end
-```
-
-This will also ensure url helpers for the engine will work as expected in your tests.
+This also ensures that the engine's URL helpers will work as expected in your
+tests.
Improving engine functionality
------------------------------
@@ -1155,7 +1166,7 @@ end
Using `Class#class_eval` is great for simple adjustments, but for more complex
class modifications, you might want to consider using [`ActiveSupport::Concern`]
-(http://edgeapi.rubyonrails.org/classes/ActiveSupport/Concern.html).
+(http://api.rubyonrails.org/classes/ActiveSupport/Concern.html).
ActiveSupport::Concern manages load order of interlinked dependent modules and
classes at run time allowing you to significantly modularize your code.
diff --git a/guides/source/form_helpers.md b/guides/source/form_helpers.md
index cb45e38614..f3f7415b3c 100644
--- a/guides/source/form_helpers.md
+++ b/guides/source/form_helpers.md
@@ -96,7 +96,15 @@ form_tag({controller: "people", action: "search"}, method: "get", class: "nifty_
### Helpers for Generating Form Elements
-Rails provides a series of helpers for generating form elements such as checkboxes, text fields, and radio buttons. These basic helpers, with names ending in "_tag" (such as `text_field_tag` and `check_box_tag`), generate just a single `<input>` element. The first parameter to these is always the name of the input. When the form is submitted, the name will be passed along with the form data, and will make its way to the `params` hash in the controller with the value entered by the user for that field. For example, if the form contains `<%= text_field_tag(:query) %>`, then you would be able to get the value of this field in the controller with `params[:query]`.
+Rails provides a series of helpers for generating form elements such as
+checkboxes, text fields, and radio buttons. These basic helpers, with names
+ending in `_tag` (such as `text_field_tag` and `check_box_tag`), generate just a
+single `<input>` element. The first parameter to these is always the name of the
+input. When the form is submitted, the name will be passed along with the form
+data, and will make its way to the `params` hash in the controller with the
+value entered by the user for that field. For example, if the form contains `<%=
+text_field_tag(:query) %>`, then you would be able to get the value of this
+field in the controller with `params[:query]`.
When naming inputs, Rails uses certain conventions that make it possible to submit parameters with non-scalar values such as arrays or hashes, which will also be accessible in `params`. You can read more about them in [chapter 7 of this guide](#understanding-parameter-naming-conventions). For details on the precise usage of these helpers, please refer to the [API documentation](http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html).
diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md
index 1769448531..dc63ae62b1 100644
--- a/guides/source/getting_started.md
+++ b/guides/source/getting_started.md
@@ -101,7 +101,7 @@ If you don't have Ruby installed have a look at
install Ruby on your platform.
Many popular UNIX-like OSes ship with an acceptable version of SQLite3. Windows
-users and others can find installation instructions at [the SQLite3 website](https://www.sqlite.org).
+users and others can find installation instructions at the [SQLite3 website](https://www.sqlite.org).
Verify that it is correctly installed and in your PATH:
```bash
@@ -165,7 +165,7 @@ of the files and folders that Rails created by default:
|config/|Configure your application's routes, database, and more. This is covered in more detail in [Configuring Rails Applications](configuring.html).|
|config.ru|Rack configuration for Rack based servers used to start the application.|
|db/|Contains your current database schema, as well as the database migrations.|
-|Gemfile<br>Gemfile.lock|These files allow you to specify what gem dependencies are needed for your Rails application. These files are used by the Bundler gem. For more information about Bundler, see [the Bundler website](http://bundler.io).|
+|Gemfile<br>Gemfile.lock|These files allow you to specify what gem dependencies are needed for your Rails application. These files are used by the Bundler gem. For more information about Bundler, see the [Bundler website](http://bundler.io).|
|lib/|Extended modules for your application.|
|log/|Application log files.|
|public/|The only folder seen by the world as-is. Contains static files and compiled assets.|
@@ -195,8 +195,8 @@ TIP: Compiling CoffeeScript and JavaScript asset compression requires you
have a JavaScript runtime available on your system, in the absence
of a runtime you will see an `execjs` error during asset compilation.
Usually Mac OS X and Windows come with a JavaScript runtime installed.
-Rails adds the `therubyracer` gem to the generated `Gemfile` in a
-commented line for new apps and you can uncomment if you need it.
+Rails adds the `therubyracer` gem to the generated `Gemfile` in a
+commented line for new apps and you can uncomment if you need it.
`therubyrhino` is the recommended runtime for JRuby users and is added by
default to the `Gemfile` in apps generated under JRuby. You can investigate
all the supported runtimes at [ExecJS](https://github.com/sstephenson/execjs#readme).
@@ -338,8 +338,8 @@ You can create, read, update and destroy items for a resource and these
operations are referred to as _CRUD_ operations.
Rails provides a `resources` method which can be used to declare a standard REST
-resource. Here's what `config/routes.rb` should look like after the
-_article resource_ is declared.
+resource. You need to add the _article resource_ to the
+`config/routes.rb` as follows:
```ruby
Rails.application.routes.draw do
@@ -833,7 +833,7 @@ class ArticlesController < ApplicationController
A couple of things to note. We use `Article.find` to find the article we're
interested in, passing in `params[:id]` to get the `:id` parameter from the
-request. We also use an instance variable (prefixed by `@`) to hold a
+request. We also use an instance variable (prefixed with `@`) to hold a
reference to the article object. We do this because Rails will pass all instance
variables to the view.
@@ -1279,7 +1279,7 @@ And here's how our app looks so far:
Our `edit` page looks very similar to the `new` page; in fact, they
both share the same code for displaying the form. Let's remove this
duplication by using a view partial. By convention, partial files are
-prefixed by an underscore.
+prefixed with an underscore.
TIP: You can read more about partials in the
[Layouts and Rendering in Rails](layouts_and_rendering.html) guide.
@@ -2049,7 +2049,7 @@ command-line utility:
in your web browser to explore the API documentation.
TIP: To be able to generate the Rails Guides locally with the `doc:guides` rake
-task you need to install the RedCloth gem. Add it to your `Gemfile` and run
+task you need to install the RedCloth and Nokogiri gems. Add it to your `Gemfile` and run
`bundle install` and you're ready to go.
Configuration Gotchas
diff --git a/guides/source/i18n.md b/guides/source/i18n.md
index f6cbc1823a..75b5275245 100644
--- a/guides/source/i18n.md
+++ b/guides/source/i18n.md
@@ -626,7 +626,7 @@ entry[count == 1 ? 0 : 1]
I.e. the translation denoted as `:one` is regarded as singular, the other is used as plural (including the count being zero).
-If the lookup for the key does not return a Hash suitable for pluralization, an `18n::InvalidPluralizationData` exception is raised.
+If the lookup for the key does not return a Hash suitable for pluralization, an `I18n::InvalidPluralizationData` exception is raised.
### Setting and Passing a Locale
diff --git a/guides/source/rails_on_rack.md b/guides/source/rails_on_rack.md
index 8bc2678d8f..0dec0e139b 100644
--- a/guides/source/rails_on_rack.md
+++ b/guides/source/rails_on_rack.md
@@ -277,7 +277,7 @@ Much of Action Controller's functionality is implemented as Middlewares. The fol
**`ActionDispatch::Callbacks`**
-* Runs the prepare callbacks before serving the request.
+* Provides callbacks to be executed before and after dispatching the request.
**`ActiveRecord::Migration::CheckPending`**
@@ -307,7 +307,7 @@ Much of Action Controller's functionality is implemented as Middlewares. The fol
* Parses out parameters from the request into `params`.
-**`ActionDispatch::Head`**
+**`Rack::Head`**
* Converts HEAD requests to `GET` requests and serves them as so.
diff --git a/guides/source/security.md b/guides/source/security.md
index 125dd82666..b1c5b22338 100644
--- a/guides/source/security.md
+++ b/guides/source/security.md
@@ -362,7 +362,7 @@ Refer to the Injection section for countermeasures against XSS. It is _recommend
**CSRF** Cross-Site Request Forgery (CSRF), also known as Cross-Site Reference Forgery (XSRF), is a gigantic attack method, it allows the attacker to do everything the administrator or Intranet user may do. As you have already seen above how CSRF works, here are a few examples of what attackers can do in the Intranet or admin interface.
-A real-world example is a [router reconfiguration by CSRF](http://www.h-online.com/security/Symantec-reports-first-active-attack-on-a-DSL-router--/news/102352). The attackers sent a malicious e-mail, with CSRF in it, to Mexican users. The e-mail claimed there was an e-card waiting for them, but it also contained an image tag that resulted in a HTTP-GET request to reconfigure the user's router (which is a popular model in Mexico). The request changed the DNS-settings so that requests to a Mexico-based banking site would be mapped to the attacker's site. Everyone who accessed the banking site through that router saw the attacker's fake web site and had their credentials stolen.
+A real-world example is a [router reconfiguration by CSRF](http://www.h-online.com/security/news/item/Symantec-reports-first-active-attack-on-a-DSL-router-735883.html). The attackers sent a malicious e-mail, with CSRF in it, to Mexican users. The e-mail claimed there was an e-card waiting for them, but it also contained an image tag that resulted in a HTTP-GET request to reconfigure the user's router (which is a popular model in Mexico). The request changed the DNS-settings so that requests to a Mexico-based banking site would be mapped to the attacker's site. Everyone who accessed the banking site through that router saw the attacker's fake web site and had their credentials stolen.
Another example changed Google Adsense's e-mail address and password by. If the victim was logged into Google Adsense, the administration interface for Google advertisements campaigns, an attacker could change their credentials.

diff --git a/guides/source/testing.md b/guides/source/testing.md
index 6678db21f8..d54f431d54 100644
--- a/guides/source/testing.md
+++ b/guides/source/testing.md
@@ -82,7 +82,7 @@ Each fixture is given a name followed by an indented list of colon-separated key
If you are working with [associations](/association_basics.html), you can simply
define a reference node between two different fixtures. Here's an example with
-a belongs_to/has_many association:
+a `belongs_to`/`has_many` association:
```yaml
# In fixtures/categories.yml
@@ -728,7 +728,7 @@ class UserFlowsTest < ActionDispatch::IntegrationTest
https!(false)
get "/articles/all"
assert_response :success
- assert assigns(:products)
+ assert assigns(:articles)
end
end
```
@@ -785,14 +785,13 @@ end
Rake Tasks for Running your Tests
---------------------------------
-You don't need to set up and run your tests by hand on a test-by-test basis.
-Rails comes with a number of commands to help in testing.
-The table below lists all commands that come along in the default Rakefile
-when you initiate a Rails project.
+Rails comes with a number of built-in rake tasks to help with testing. The
+table below lists the commands included in the default Rakefile when a Rails
+project is created.
| Tasks | Description |
| ----------------------- | ----------- |
-| `rake test` | Runs all unit, functional and integration tests. You can also simply run `rake` as Rails will run all the tests by default |
+| `rake test` | Runs all tests in the `test` folder. You can also simply run `rake` as Rails will run all the tests by default |
| `rake test:controllers` | Runs all the controller tests from `test/controllers` |
| `rake test:functionals` | Runs all the functional tests from `test/controllers`, `test/mailers`, and `test/functional` |
| `rake test:helpers` | Runs all the helper tests from `test/helpers` |
@@ -801,11 +800,10 @@ when you initiate a Rails project.
| `rake test:mailers` | Runs all the mailer tests from `test/mailers` |
| `rake test:models` | Runs all the model tests from `test/models` |
| `rake test:units` | Runs all the unit tests from `test/models`, `test/helpers`, and `test/unit` |
-| `rake test:all` | Runs all tests quickly by merging all types and not resetting db |
-| `rake test:all:db` | Runs all tests quickly by merging all types and resetting db |
+| `rake test:db` | Runs all tests in the `test` folder and resets the db |
-Brief Note About `Minitest`
+A Brief Note About Minitest
-----------------------------
Ruby ships with a vast Standard Library for all common use-cases including testing. Since version 1.9, Ruby provides `Minitest`, a framework for testing. All the basic assertions such as `assert_equal` discussed above are actually defined in `Minitest::Assertions`. The classes `ActiveSupport::TestCase`, `ActionController::TestCase`, `ActionMailer::TestCase`, `ActionView::TestCase` and `ActionDispatch::IntegrationTest` - which we have been inheriting in our test classes - include `Minitest::Assertions`, allowing us to use all of the basic assertions in our tests.
@@ -902,13 +900,17 @@ end
Testing Routes
--------------
-Like everything else in your Rails application, it is recommended that you test your routes. An example test for a route in the default `show` action of `Articles` controller above should look like:
+Like everything else in your Rails application, it is recommended that you test your routes. Below are example tests for the routes of default `show` and `create` action of `Articles` controller above and it should look like:
```ruby
class ArticleRoutesTest < ActionController::TestCase
test "should route to article" do
assert_routing '/articles/1', { controller: "articles", action: "show", id: "1" }
end
+
+ test "should route to create article" do
+ assert_routing({ method: 'post', path: '/articles' }, { controller: "articles", action: "create" })
+ end
end
```
@@ -1045,6 +1047,68 @@ end
Moreover, since the test class extends from `ActionView::TestCase`, you have
access to Rails' helper methods such as `link_to` or `pluralize`.
+Testing Jobs
+------------
+
+Since your custom jobs can be queued at different levels inside your application,
+you'll need to test both jobs themselves (their behavior when they get enqueued)
+and that other entities correctly enqueue them.
+
+### A Basic Test Case
+
+By default, when you generate a job, an associated test will be generated as well
+under the `test/jobs` directory. Here's an example test with a billing job:
+
+```ruby
+require 'test_helper'
+
+class BillingJobTest < ActiveJob::TestCase
+ test 'that account is charged' do
+ BillingJob.perform_now(account, product)
+ assert account.reload.charged_for?(product)
+ end
+end
+```
+
+This test is pretty simple and only asserts that the job get the work done
+as expected.
+
+By default, `ActiveJob::TestCase` will set the queue adapter to `:test` so that
+your jobs are performed inline. It will also ensure that all previously performed
+and enqueued jobs are cleared before any test run so you can safely assume that
+no jobs have already been executed in the scope of each test.
+
+### Custom Assertions And Testing Jobs Inside Other Components
+
+Active Job ships with a bunch of custom assertions that can be used to lessen
+the verbosity of tests:
+
+| Assertion | Purpose |
+| -------------------------------------- | ------- |
+| `assert_enqueued_jobs(number)` | Asserts that the number of enqueued jobs matches the given number. |
+| `assert_performed_jobs(number)` | Asserts that the number of performed jobs matches the given number. |
+| `assert_no_enqueued_jobs { ... }` | Asserts that no jobs have been enqueued. |
+| `assert_no_performed_jobs { ... }` | Asserts that no jobs have been performed. |
+| `assert_enqueued_with([args]) { ... }` | Asserts that the job passed in the block has been enqueued with the given arguments. |
+| `assert_performed_with([args]) { ... }`| Asserts that the job passed in the block has been performed with the given arguments. |
+
+It's a good practice to ensure that your jobs correctly get enqueued or performed
+wherever you invoke them (e.g. inside your controllers). This is precisely where
+the custom assertions provided by Active Job are pretty useful. For instance,
+within a model:
+
+```ruby
+require 'test_helper'
+
+class ProductTest < ActiveSupport::TestCase
+ test 'billing job scheduling' do
+ assert_enqueued_with(job: BillingJob) do
+ product.charge(account)
+ end
+ end
+end
+```
+
Other Testing Approaches
------------------------
@@ -1056,3 +1120,4 @@ The built-in `minitest` based testing is not the only way to test Rails applicat
* [MiniTest::Spec Rails](https://github.com/metaskills/minitest-spec-rails), use the MiniTest::Spec DSL within your rails tests.
* [Shoulda](http://www.thoughtbot.com/projects/shoulda), an extension to `test/unit` with additional helpers, macros, and assertions.
* [RSpec](http://relishapp.com/rspec), a behavior-driven development framework
+* [Capybara](http://jnicklas.github.com/capybara/), Acceptance test framework for web applications
diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md
index aac2aef615..4ce61c282d 100644
--- a/guides/source/upgrading_ruby_on_rails.md
+++ b/guides/source/upgrading_ruby_on_rails.md
@@ -50,22 +50,10 @@ Don't forget to review the difference, to see if there were any unexpected chang
Upgrading from Rails 4.1 to Rails 4.2
-------------------------------------
-NOTE: This section is a work in progress, please help to improve this by sending
-a [pull request](https://github.com/rails/rails/edit/master/guides/source/upgrading_ruby_on_rails.md).
-
### Web Console
First, add `gem 'web-console', '~> 2.0'` to the `:development` group in your Gemfile and run `bundle install` (it won't have been included when you upgraded Rails). Once it's been installed, you can simply drop a reference to the console helper (i.e., `<%= console %>`) into any view you want to enable it for. A console will also be provided on any error page you view in your development environment.
-Additionally, you can tell Rails to automatically mount a VT100-compatible console on a predetermined path by setting the appropriate configuration flags in your development config:
-
-```ruby
-# config/environments/development.rb
-
-config.web_console.automount = true
-config.web_console.default_mount_path = '/terminal' # Optional, defaults to /console
-```
-
### Responders
`respond_with` and the class-level `respond_to` methods have been extracted to the `responders` gem. To use them, simply add `gem 'responders', '~> 2.0'` to your Gemfile. Calls to `respond_with` and `respond_to` (again, at the class level) will no longer work without having included the `responders` gem in your dependencies:
@@ -145,6 +133,18 @@ assigning `nil` to a serialized attribute will save it to the database
as `NULL` instead of passing the `nil` value through the coder (e.g. `"null"`
when using the `JSON` coder).
+### Production log level
+
+In Rails 5, the default log level for the production environment will be changed
+to `:debug` (from `:info`). To preserve the current default, add the following
+line to your `production.rb`:
+
+```ruby
+# Set to `:info` to match the current default, or set to `:debug` to opt-into
+# the future default.
+config.log_level = :info
+```
+
### `after_bundle` in Rails templates
If you have a Rails template that adds all the files in version control, it
@@ -181,7 +181,7 @@ end
There's a new choice for sanitizing HTML fragments in your applications. The
venerable html-scanner approach is now officially being deprecated in favor of
-[`Rails Html Sanitizer`](https://github.com/rails/rails-html-sanitizer).
+[`Rails HTML Sanitizer`](https://github.com/rails/rails-html-sanitizer).
This means the methods `sanitize`, `sanitize_css`, `strip_tags` and
`strip_links` are backed by a new implementation.
@@ -207,7 +207,7 @@ gem 'rails-deprecated_sanitizer'
```
### Rails DOM Testing
-The [`TagAssertions` module](http://api.rubyonrails.org/classes/ActionDispatch/Assertions/TagAssertions.html) (containing methods such as `assert_tag`), [has been deprecated](https://github.com/rails/rails/blob/6061472b8c310158a2a2e8e9a6b81a1aef6b60fe/actionpack/lib/action_dispatch/testing/assertions/dom.rb) in favor of the `assert_select` methods from the `SelectorAssertions` module, which has been extracted into the [rails-dom-testing gem](https://github.com/rails/rails-dom-testing).
+The [`TagAssertions` module](http://api.rubyonrails.org/classes/ActionDispatch/Assertions/TagAssertions.html) (containing methods such as `assert_tag`), [has been deprecated](https://github.com/rails/rails/blob/6061472b8c310158a2a2e8e9a6b81a1aef6b60fe/actionpack/lib/action_dispatch/testing/assertions/dom.rb) in favor of the `assert_select` methods from the `SelectorAssertions` module, which has been extracted into the [rails-dom-testing gem](https://github.com/rails/rails-dom-testing).
### Masked Authenticity Tokens
@@ -421,7 +421,7 @@ class ReadOnlyModel < ActiveRecord::Base
end
```
-This behaviour was never intentionally supported. Due to a change in the internals
+This behavior was never intentionally supported. Due to a change in the internals
of `ActiveSupport::Callbacks`, this is no longer allowed in Rails 4.1. Using a
`return` statement in an inline callback block causes a `LocalJumpError` to
be raised when the callback is executed.
@@ -795,7 +795,7 @@ Rails 4.0 extracted Active Resource to its own gem. If you still need the featur
* Rails 4.0 has changed how errors attach with the `ActiveModel::Validations::ConfirmationValidator`. Now when confirmation validations fail, the error will be attached to `:#{attribute}_confirmation` instead of `attribute`.
-* Rails 4.0 has changed `ActiveModel::Serializers::JSON.include_root_in_json` default value to `false`. Now, Active Model Serializers and Active Record objects have the same default behaviour. This means that you can comment or remove the following option in the `config/initializers/wrap_parameters.rb` file:
+* Rails 4.0 has changed `ActiveModel::Serializers::JSON.include_root_in_json` default value to `false`. Now, Active Model Serializers and Active Record objects have the same default behavior. This means that you can comment or remove the following option in the `config/initializers/wrap_parameters.rb` file:
```ruby
# Disable root element in JSON by default.
diff --git a/rails.gemspec b/rails.gemspec
index 99685252e0..be83304e2b 100644
--- a/rails.gemspec
+++ b/rails.gemspec
@@ -7,7 +7,7 @@ Gem::Specification.new do |s|
s.summary = 'Full-stack web application framework.'
s.description = 'Ruby on Rails is a full-stack web framework optimized for programmer happiness and sustainable productivity. It encourages beautiful code by favoring convention over configuration.'
- s.required_ruby_version = '>= 1.9.3'
+ s.required_ruby_version = '>= 2.1.0'
s.required_rubygems_version = '>= 1.8.11'
s.license = 'MIT'
@@ -28,5 +28,5 @@ Gem::Specification.new do |s|
s.add_dependency 'railties', version
s.add_dependency 'bundler', '>= 1.3.0', '< 2.0'
- s.add_dependency 'sprockets-rails', '~> 3.0.0.beta1'
+ s.add_dependency 'sprockets-rails'
end
diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md
index 2960eccb3f..cd7f3b1e2f 100644
--- a/railties/CHANGELOG.md
+++ b/railties/CHANGELOG.md
@@ -1,178 +1 @@
-* Remove `--skip-action-view` option from `Rails::Generators::AppBase`.
-
- Fixes #17023.
-
- *Dan Olson*
-
-* Specify dummy app's db migrate path in plugin's test_helper.rb.
-
- Fixes #16877.
-
- *Yukio Mizuta*
-
-* Inject `Rack::Lock` if `config.eager_load` is false.
-
- Fixes #15089.
-
- *Xavier Noria*
-
-* Change the path of dummy app location in plugin's test_helper.rb for cases
- you specify dummy_path option.
-
- *Yukio Mizuta*
-
-* Fix a bug in the `gem` method for Rails templates when non-String options
- are used.
-
- Fixes #16709.
-
- *Yves Senn*
-
-* The [web-console](https://github.com/rails/web-console) gem is now
- installed by default for new applications. It can help you debug
- development exceptions by spawning an interactive console in its cause
- binding.
-
- *Ryan Dao*, *Genadi Samokovarov*, *Guillermo Iguaran*
-
-* Add a `required` option to the model generator for associations
-
- *Sean Griffin*
-
-* Add `after_bundle` callbacks in Rails templates. Useful for allowing the
- generated binstubs to be added to version control.
-
- Fixes #16292.
-
- *Stefan Kanev*
-
-* Pull in the custom configuration concept from dhh/custom_configuration, which allows you to
- configure your own code through the Rails configuration object with custom configuration:
-
- # config/environments/production.rb
- config.x.payment_processing.schedule = :daily
- config.x.payment_processing.retries = 3
- config.x.super_debugger = true
-
- These configuration points are then available through the configuration object:
-
- Rails.configuration.x.payment_processing.schedule # => :daily
- Rails.configuration.x.payment_processing.retries # => 3
- Rails.configuration.x.super_debugger # => true
-
- *DHH*
-
-* Scaffold generator `_form` partial adds `class="field"` for password
- confirmation fields.
-
- *noinkling*
-
-* Add `Rails::Application.config_for` to load a configuration for the current
- environment.
-
- # config/exception_notification.yml:
- production:
- url: http://127.0.0.1:8080
- namespace: my_app_production
- development:
- url: http://localhost:3001
- namespace: my_app_development
-
- # config/production.rb
- Rails.application.configure do
- config.middleware.use ExceptionNotifier, config_for(:exception_notification)
- end
-
- *Rafael Mendonça França*, *DHH*
-
-* Deprecate `Rails::Rack::LogTailer` without replacement.
-
- *Rafael Mendonça França*
-
-* Add a generic --skip-turbolinks options to generator.
-
- *Rafael Mendonça França*
-
-* Invalid `bin/rails generate` commands will now show spelling suggestions.
-
- *Richard Schneeman*
-
-* Add `bin/setup` script to bootstrap an application.
-
- *Yves Senn*
-
-* Replace double quotes with single quotes while adding an entry into Gemfile.
-
- *Alexander Belaev*
-
-* Default `config.assets.digest` to `true` in development.
-
- *Dan Kang*
-
-* Load database configuration from the first `database.yml` available in paths.
-
- *Pier-Olivier Thibault*
-
-* Reading name and email from git for plugin gemspec.
-
- Fixes #9589.
-
- *Arun Agrawal*, *Abd ar-Rahman Hamidi*, *Roman Shmatov*
-
-* Fix `console` and `generators` blocks defined at different environments.
-
- Fixes #14748.
-
- *Rafael Mendonça França*
-
-* Move configuration of asset precompile list and version to an initializer.
-
- *Matthew Draper*
-
-* Remove sqlite3 lines from `.gitignore` if the application is not using sqlite3.
-
- *Dmitrii Golub*
-
-* Add public API to register new extensions for `rake notes`.
-
- Example:
-
- config.annotations.register_extensions("scss", "sass") { |tag| /\/\/\s*(#{tag}):?\s*(.*)$/ }
-
- *Roberto Miranda*
-
-* Removed unnecessary `rails application` command.
-
- *Arun Agrawal*
-
-* Make the `rails:template` rake task load the application's initializers.
-
- Fixes #12133.
-
- *Robin Dupret*
-
-* Introduce `Rails.gem_version` as a convenience method to return
- `Gem::Version.new(Rails.version)`, suggesting a more reliable way to perform
- version comparison.
-
- Example:
-
- Rails.version #=> "4.1.2"
- Rails.gem_version #=> #<Gem::Version "4.1.2">
-
- Rails.version > "4.1.10" #=> false
- Rails.gem_version > Gem::Version.new("4.1.10") #=> true
- Gem::Requirement.new("~> 4.1.2") =~ Rails.gem_version #=> true
-
- *Prem Sichanugrist*
-
-* Avoid namespacing routes inside engines.
-
- Mountable engines are namespaced by default so the generated routes
- were too while they should not.
-
- Fixes #14079.
-
- *Yves Senn*, *Carlos Antonio da Silva*, *Robin Dupret*
-
-Please check [4-1-stable](https://github.com/rails/rails/blob/4-1-stable/railties/CHANGELOG.md) for previous changes.
+Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/railties/CHANGELOG.md) for previous changes.
diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb
index bc966e87c6..f8bd6096f2 100644
--- a/railties/lib/rails/application.rb
+++ b/railties/lib/rails/application.rb
@@ -88,6 +88,7 @@ module Rails
def inherited(base)
super
Rails.app_class = base
+ add_lib_to_load_path!(find_root(base.called_from))
end
def instance
@@ -98,6 +99,10 @@ module Rails
new(initial_variable_values, &block).run_load_hooks!
end
+ def find_root(from)
+ find_root_with_flag "config.ru", from, Dir.pwd
+ end
+
# Makes the +new+ method public.
#
# Note that Rails::Application inherits from Rails::Engine, which
@@ -129,8 +134,6 @@ module Rails
# are these actually used?
@initial_variable_values = initial_variable_values
@block = block
-
- add_lib_to_load_path!
end
# Returns true if the application is initialized.
@@ -175,7 +178,7 @@ module Rails
key_generator = ActiveSupport::KeyGenerator.new(secrets.secret_key_base, iterations: 1000)
ActiveSupport::CachingKeyGenerator.new(key_generator)
else
- ActiveSupport::LegacyKeyGenerator.new(config.secret_token)
+ ActiveSupport::LegacyKeyGenerator.new(secrets.secret_token)
end
end
@@ -245,7 +248,7 @@ module Rails
super.merge({
"action_dispatch.parameter_filter" => config.filter_parameters,
"action_dispatch.redirect_filter" => config.filter_redirect,
- "action_dispatch.secret_token" => config.secret_token,
+ "action_dispatch.secret_token" => secrets.secret_token,
"action_dispatch.secret_key_base" => secrets.secret_key_base,
"action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions,
"action_dispatch.show_detailed_exceptions" => config.consider_all_requests_local,
@@ -313,8 +316,8 @@ module Rails
# are changing config.root inside your application definition or having a custom
# Rails application, you will need to add lib to $LOAD_PATH on your own in case
# you need to load files in lib/ during the application configuration as well.
- def add_lib_to_load_path! #:nodoc:
- path = File.join config.root, 'lib'
+ def self.add_lib_to_load_path!(root) #:nodoc:
+ path = File.join root, 'lib'
if File.exist?(path) && !$LOAD_PATH.include?(path)
$LOAD_PATH.unshift(path)
end
@@ -358,7 +361,7 @@ module Rails
end
def config #:nodoc:
- @config ||= Application::Configuration.new(find_root_with_flag("config.ru", Dir.pwd))
+ @config ||= Application::Configuration.new(self.class.find_root(self.class.called_from))
end
def config=(configuration) #:nodoc:
@@ -378,6 +381,8 @@ module Rails
# Fallback to config.secret_key_base if secrets.secret_key_base isn't set
secrets.secret_key_base ||= config.secret_key_base
+ # Fallback to config.secret_token if secrets.secret_token isn't set
+ secrets.secret_token ||= config.secret_token
secrets
end
@@ -507,8 +512,13 @@ module Rails
end
def validate_secret_key_config! #:nodoc:
- if secrets.secret_key_base.blank? && config.secret_token.blank?
- raise "Missing `secret_key_base` for '#{Rails.env}' environment, set this value in `config/secrets.yml`"
+ if secrets.secret_key_base.blank?
+ ActiveSupport::Deprecation.warn "You didn't set `secret_key_base`. " +
+ "Read the upgrade documentation to learn more about this new config option."
+
+ if secrets.secret_token.blank?
+ raise "Missing `secret_token` and `secret_key_base` for '#{Rails.env}' environment, set these values in `config/secrets.yml`"
+ end
end
end
end
diff --git a/railties/lib/rails/application/bootstrap.rb b/railties/lib/rails/application/bootstrap.rb
index 0f4d932749..71d3febde4 100644
--- a/railties/lib/rails/application/bootstrap.rb
+++ b/railties/lib/rails/application/bootstrap.rb
@@ -1,5 +1,6 @@
require "active_support/notifications"
require "active_support/dependencies"
+require "active_support/deprecation"
require "active_support/descendants_tracker"
module Rails
@@ -54,6 +55,18 @@ INFO
logger
end
+ if Rails.env.production? && !config.has_explicit_log_level?
+ ActiveSupport::Deprecation.warn \
+ "You did not specify a `log_level` in `production.rb`. Currently, " \
+ "the default value for `log_level` is `:info` for the production " \
+ "environment and `:debug` in all other environments. In Rails 5 " \
+ "the default value will be unified to `:debug` across all " \
+ "environments. To preserve the current setting, add the following " \
+ "line to your `production.rb`:\n" \
+ "\n" \
+ " config.log_level = :info\n\n"
+ end
+
Rails.logger.level = ActiveSupport::Logger.const_get(config.log_level.to_s.upcase)
end
diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb
index 786dcee007..268ef2c7aa 100644
--- a/railties/lib/rails/application/configuration.rb
+++ b/railties/lib/rails/application/configuration.rb
@@ -15,7 +15,6 @@ module Rails
:time_zone, :reload_classes_only_on_change,
:beginning_of_week, :filter_redirect, :x
- attr_writer :log_level
attr_reader :encoding
def initialize(*)
@@ -34,6 +33,7 @@ module Rails
@session_options = {}
@time_zone = "UTC"
@beginning_of_week = :monday
+ @has_explicit_log_level = false
@log_level = nil
@middleware = app_middleware
@generators = app_generators
@@ -117,8 +117,17 @@ module Rails
raise e, "Cannot load `Rails.application.database_configuration`:\n#{e.message}", e.backtrace
end
+ def has_explicit_log_level? # :nodoc:
+ @has_explicit_log_level
+ end
+
+ def log_level=(level)
+ @has_explicit_log_level = !!(level)
+ @log_level = level
+ end
+
def log_level
- @log_level ||= :debug
+ @log_level ||= (Rails.env.production? ? :info : :debug)
end
def colorize_logging
diff --git a/railties/lib/rails/application/routes_reloader.rb b/railties/lib/rails/application/routes_reloader.rb
index 737977adf9..cf0a4e128f 100644
--- a/railties/lib/rails/application/routes_reloader.rb
+++ b/railties/lib/rails/application/routes_reloader.rb
@@ -41,9 +41,7 @@ module Rails
end
def finalize!
- route_sets.each do |routes|
- routes.finalize!
- end
+ route_sets.each(&:finalize!)
end
def revert
diff --git a/railties/lib/rails/code_statistics.rb b/railties/lib/rails/code_statistics.rb
index 0ae6d2a455..27779857b7 100644
--- a/railties/lib/rails/code_statistics.rb
+++ b/railties/lib/rails/code_statistics.rb
@@ -6,6 +6,7 @@ class CodeStatistics #:nodoc:
'Helper tests',
'Model tests',
'Mailer tests',
+ 'Job tests',
'Integration tests',
'Functional tests (old)',
'Unit tests (old)']
diff --git a/railties/lib/rails/commands/dbconsole.rb b/railties/lib/rails/commands/dbconsole.rb
index 1a2613a8d0..9014560611 100644
--- a/railties/lib/rails/commands/dbconsole.rb
+++ b/railties/lib/rails/commands/dbconsole.rb
@@ -44,7 +44,7 @@ module Rails
find_cmd_and_exec(['mysql', 'mysql5'], *args)
- when "postgresql", "postgres", "postgis"
+ when /^postgres|^postgis/
ENV['PGUSER'] = config["username"] if config["username"]
ENV['PGHOST'] = config["host"] if config["host"]
ENV['PGPORT'] = config["port"].to_s if config["port"]
@@ -74,6 +74,21 @@ module Rails
find_cmd_and_exec('sqlplus', logon)
+ when "sqlserver"
+ args = []
+
+ args += ["-D", "#{config['database']}"] if config['database']
+ args += ["-U", "#{config['username']}"] if config['username']
+ args += ["-P", "#{config['password']}"] if config['password']
+
+ if config['host']
+ host_arg = "#{config['host']}"
+ host_arg << ":#{config['port']}" if config['port']
+ args += ["-S", host_arg]
+ end
+
+ find_cmd_and_exec("sqsh", *args)
+
else
abort "Unknown command-line client for #{config['database']}. Submit a Rails patch to add support!"
end
diff --git a/railties/lib/rails/commands/destroy.rb b/railties/lib/rails/commands/destroy.rb
index 5479da86a0..ce26cc3fde 100644
--- a/railties/lib/rails/commands/destroy.rb
+++ b/railties/lib/rails/commands/destroy.rb
@@ -1,5 +1,7 @@
require 'rails/generators'
+#if no argument/-h/--help is passed to rails destroy command, then
+#it generates the help associated.
if [nil, "-h", "--help"].include?(ARGV.first)
Rails::Generators.help 'destroy'
exit
diff --git a/railties/lib/rails/commands/generate.rb b/railties/lib/rails/commands/generate.rb
index 351c59c645..926c36b967 100644
--- a/railties/lib/rails/commands/generate.rb
+++ b/railties/lib/rails/commands/generate.rb
@@ -1,5 +1,7 @@
require 'rails/generators'
+#if no argument/-h/--help is passed to rails generate command, then
+#it generates the help associated.
if [nil, "-h", "--help"].include?(ARGV.first)
Rails::Generators.help 'generate'
exit
diff --git a/railties/lib/rails/commands/plugin.rb b/railties/lib/rails/commands/plugin.rb
index 95bbdd4cdf..52d8966ead 100644
--- a/railties/lib/rails/commands/plugin.rb
+++ b/railties/lib/rails/commands/plugin.rb
@@ -11,7 +11,7 @@ else
end
if File.exist?(railsrc)
extra_args_string = File.read(railsrc)
- extra_args = extra_args_string.split(/\n+/).flat_map {|l| l.split}
+ extra_args = extra_args_string.split(/\n+/).flat_map(&:split)
puts "Using #{extra_args.join(" ")} from #{railsrc}"
ARGV.insert(1, *extra_args)
end
diff --git a/railties/lib/rails/configuration.rb b/railties/lib/rails/configuration.rb
index f5d7dede66..f99cec04c5 100644
--- a/railties/lib/rails/configuration.rb
+++ b/railties/lib/rails/configuration.rb
@@ -18,11 +18,11 @@ module Rails
# This will put the <tt>Magical::Unicorns</tt> middleware on the end of the stack.
# You can use +insert_before+ if you wish to add a middleware before another:
#
- # config.middleware.insert_before ActionDispatch::Head, Magical::Unicorns
+ # config.middleware.insert_before Rack::Head, Magical::Unicorns
#
# There's also +insert_after+ which will insert a middleware after another:
#
- # config.middleware.insert_after ActionDispatch::Head, Magical::Unicorns
+ # config.middleware.insert_after Rack::Head, Magical::Unicorns
#
# Middlewares can also be completely swapped out and replaced with others:
#
diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb
index dc3da1eb41..4b7da32208 100644
--- a/railties/lib/rails/engine.rb
+++ b/railties/lib/rails/engine.rb
@@ -110,8 +110,8 @@ module Rails
#
# == Endpoint
#
- # An engine can be also a rack application. It can be useful if you have a rack application that
- # you would like to wrap with +Engine+ and provide some of the +Engine+'s features.
+ # An engine can also be a rack application. It can be useful if you have a rack application that
+ # you would like to wrap with +Engine+ and provide with some of the +Engine+'s features.
#
# To do that, use the +endpoint+ method:
#
@@ -351,7 +351,7 @@ module Rails
base.called_from = begin
call_stack = if Kernel.respond_to?(:caller_locations)
- caller_locations.map(&:path)
+ caller_locations.map(&:absolute_path)
else
# Remove the line number from backtraces making sure we don't leave anything behind
caller.map { |p| p.sub(/:\d+.*/, '') }
@@ -364,6 +364,10 @@ module Rails
super
end
+ def find_root(from)
+ find_root_with_flag "lib", from
+ end
+
def endpoint(endpoint = nil)
@endpoint ||= nil
@endpoint = endpoint if endpoint
@@ -531,7 +535,7 @@ module Rails
# Define the configuration object for the engine.
def config
- @config ||= Engine::Configuration.new(find_root_with_flag("lib"))
+ @config ||= Engine::Configuration.new(self.class.find_root(self.class.called_from))
end
# Load data from db/seeds.rb file. It can be used in to load engines'
@@ -658,8 +662,7 @@ module Rails
paths["db/migrate"].existent.any?
end
- def find_root_with_flag(flag, default=nil) #:nodoc:
- root_path = self.class.called_from
+ 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)
diff --git a/railties/lib/rails/gem_version.rb b/railties/lib/rails/gem_version.rb
index 8abed99f2c..7d74b1bfe5 100644
--- a/railties/lib/rails/gem_version.rb
+++ b/railties/lib/rails/gem_version.rb
@@ -5,10 +5,10 @@ module Rails
end
module VERSION
- MAJOR = 4
- MINOR = 2
+ MAJOR = 5
+ MINOR = 0
TINY = 0
- PRE = "beta4"
+ PRE = "alpha"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb
index bf2390cb7e..e25c364178 100644
--- a/railties/lib/rails/generators.rb
+++ b/railties/lib/rails/generators.rb
@@ -153,7 +153,7 @@ module Rails
def self.invoke(namespace, args=ARGV, config={})
names = namespace.to_s.split(':')
if klass = find_by_namespace(names.pop, names.any? && names.join(':'))
- args << "--help" if args.empty? && klass.arguments.any? { |a| a.required? }
+ args << "--help" if args.empty? && klass.arguments.any?(&:required?)
klass.start(args, config)
else
options = sorted_groups.map(&:last).flatten
@@ -226,7 +226,7 @@ module Rails
def self.public_namespaces
lookup!
- subclasses.map { |k| k.namespace }
+ subclasses.map(&:namespace)
end
def self.print_generators
diff --git a/railties/lib/rails/generators/actions.rb b/railties/lib/rails/generators/actions.rb
index ffdb314612..5373121835 100644
--- a/railties/lib/rails/generators/actions.rb
+++ b/railties/lib/rails/generators/actions.rb
@@ -189,7 +189,7 @@ module Rails
# generate(:authenticated, "user session")
def generate(what, *args)
log :generate, what
- argument = args.flat_map {|arg| arg.to_s }.join(" ")
+ argument = args.flat_map(&:to_s).join(" ")
in_root { run_ruby_script("bin/rails generate #{what} #{argument}", verbose: false) }
end
diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb
index 92ed9136a0..f5ae600bd8 100644
--- a/railties/lib/rails/generators/app_base.rb
+++ b/railties/lib/rails/generators/app_base.rb
@@ -237,13 +237,10 @@ module Rails
gems = []
if options.dev? || options.edge?
- gems << GemfileEntry.github('sprockets-rails', 'rails/sprockets-rails',
- 'Use edge version of sprockets-rails')
gems << GemfileEntry.github('sass-rails', 'rails/sass-rails',
'Use SCSS for stylesheets')
else
- gems << GemfileEntry.version('sass-rails',
- '~> 5.0.0.beta1',
+ gems << GemfileEntry.version('sass-rails', '~> 4.0',
'Use SCSS for stylesheets')
end
@@ -278,14 +275,8 @@ module Rails
[]
else
gems = [coffee_gemfile_entry, javascript_runtime_gemfile_entry]
-
- if options[:javascript] == 'jquery'
- gems << GemfileEntry.version('jquery-rails', '~> 4.0.0.beta2',
- 'Use jQuery as the JavaScript library')
- else
- gems << GemfileEntry.version("#{options[:javascript]}-rails", nil,
- "Use #{options[:javascript]} as the JavaScript library")
- end
+ gems << GemfileEntry.version("#{options[:javascript]}-rails", nil,
+ "Use #{options[:javascript]} as the JavaScript library")
unless options[:skip_turbolinks]
gems << GemfileEntry.version("turbolinks", nil,
@@ -342,7 +333,7 @@ module Rails
end
def spring_install?
- !options[:skip_spring] && Process.respond_to?(:fork)
+ !options[:skip_spring] && Process.respond_to?(:fork) && !RUBY_PLATFORM.include?("cygwin")
end
def run_bundle
diff --git a/railties/lib/rails/generators/base.rb b/railties/lib/rails/generators/base.rb
index 9af6435f23..813b8b629e 100644
--- a/railties/lib/rails/generators/base.rb
+++ b/railties/lib/rails/generators/base.rb
@@ -273,7 +273,7 @@ module Rails
# Use Rails default banner.
def self.banner
- "rails generate #{namespace.sub(/^rails:/,'')} #{self.arguments.map{ |a| a.usage }.join(' ')} [options]".gsub(/\s+/, ' ')
+ "rails generate #{namespace.sub(/^rails:/,'')} #{self.arguments.map(&:usage).join(' ')} [options]".gsub(/\s+/, ' ')
end
# Sets the base_name taking into account the current class namespace.
diff --git a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb
index 66b17bd10e..f9b3658ae7 100644
--- a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb
+++ b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb
@@ -1,8 +1,29 @@
-require 'rails/generators/erb/controller/controller_generator'
+require 'rails/generators/erb'
module Erb # :nodoc:
module Generators # :nodoc:
- class MailerGenerator < ControllerGenerator # :nodoc:
+ class MailerGenerator < Base # :nodoc:
+ argument :actions, type: :array, default: [], banner: "method method"
+
+ def copy_view_files
+ view_base_path = File.join("app/views", class_path, file_name)
+ empty_directory view_base_path
+
+ formats.each do |format|
+ layout_path = File.join("app/views/layouts", filename_with_extensions("mailer", format))
+ template filename_with_extensions(:layout, format), layout_path
+ end
+
+ actions.each do |action|
+ @action = action
+
+ formats.each do |format|
+ @path = File.join(view_base_path, filename_with_extensions(action, format))
+ template filename_with_extensions(:view, format), @path
+ end
+ end
+ end
+
protected
def formats
diff --git a/railties/lib/rails/generators/erb/mailer/templates/layout.html.erb b/railties/lib/rails/generators/erb/mailer/templates/layout.html.erb
new file mode 100644
index 0000000000..93110e74ad
--- /dev/null
+++ b/railties/lib/rails/generators/erb/mailer/templates/layout.html.erb
@@ -0,0 +1,5 @@
+<html>
+ <body>
+ <%%= yield %>
+ </body>
+</html>
diff --git a/railties/lib/rails/generators/erb/mailer/templates/layout.text.erb b/railties/lib/rails/generators/erb/mailer/templates/layout.text.erb
new file mode 100644
index 0000000000..6363733e6e
--- /dev/null
+++ b/railties/lib/rails/generators/erb/mailer/templates/layout.text.erb
@@ -0,0 +1 @@
+<%%= yield %>
diff --git a/railties/lib/rails/generators/named_base.rb b/railties/lib/rails/generators/named_base.rb
index b7da44ca2d..397e1e73f1 100644
--- a/railties/lib/rails/generators/named_base.rb
+++ b/railties/lib/rails/generators/named_base.rb
@@ -99,7 +99,7 @@ module Rails
end
def class_name
- (class_path + [file_name]).map!{ |m| m.camelize }.join('::')
+ (class_path + [file_name]).map!(&:camelize).join('::')
end
def human_name
@@ -156,7 +156,7 @@ module Rails
def assign_names!(name) #:nodoc:
@class_path = name.include?('/') ? name.split('/') : name.split('::')
- @class_path.map! { |m| m.underscore }
+ @class_path.map!(&:underscore)
@file_name = @class_path.pop
end
diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb
index 9110c129d1..f8a8ae90d9 100644
--- a/railties/lib/rails/generators/rails/app/app_generator.rb
+++ b/railties/lib/rails/generators/rails/app/app_generator.rb
@@ -260,9 +260,7 @@ module Rails
public_task :generate_spring_binstubs
def run_after_bundle_callbacks
- @after_bundle_callbacks.each do |callback|
- callback.call
- end
+ @after_bundle_callbacks.each(&:call)
end
protected
diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile
index 5961f7515c..7027312aa9 100644
--- a/railties/lib/rails/generators/rails/app/templates/Gemfile
+++ b/railties/lib/rails/generators/rails/app/templates/Gemfile
@@ -32,7 +32,7 @@ group :development, :test do
<%- end -%>
# Access an IRB console on exception pages or by using <%%= console %> in views
- gem 'web-console', '~> 2.0.0.beta4'
+ gem 'web-console', '~> 2.0'
<%- if spring_install? %>
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
diff --git a/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt b/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt
index 07ea09cdbd..c1a77944e8 100644
--- a/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt
+++ b/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt
@@ -2,7 +2,7 @@
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
-// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
+// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
diff --git a/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css b/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css
index a443db3401..f9cd5b3483 100644
--- a/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css
+++ b/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css
@@ -3,7 +3,7 @@
* listed below.
*
* Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
- * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
+ * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
*
* You're free to add application-wide styles to this file and they'll appear at the bottom of the
* compiled file so the styles you add here take precedence over styles defined in any styles
diff --git a/railties/lib/rails/generators/rails/app/templates/bin/rails b/railties/lib/rails/generators/rails/app/templates/bin/rails
index 6a128b95e5..80ec8080ab 100644
--- a/railties/lib/rails/generators/rails/app/templates/bin/rails
+++ b/railties/lib/rails/generators/rails/app/templates/bin/rails
@@ -1,3 +1,3 @@
-APP_PATH = File.expand_path('../../config/application', __FILE__)
+APP_PATH = File.expand_path('../../config/application', __FILE__)
require_relative '../config/boot'
require 'rails/commands'
diff --git a/railties/lib/rails/generators/rails/app/templates/config.ru b/railties/lib/rails/generators/rails/app/templates/config.ru
index 5bc2a619e8..bd83b25412 100644
--- a/railties/lib/rails/generators/rails/app/templates/config.ru
+++ b/railties/lib/rails/generators/rails/app/templates/config.ru
@@ -1,4 +1,4 @@
# This file is used by Rack-based servers to start the application.
-require ::File.expand_path('../config/environment', __FILE__)
+require ::File.expand_path('../config/environment', __FILE__)
run Rails.application
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt
index 92ff0de030..ddc04d446c 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt
@@ -45,8 +45,9 @@ Rails.application.configure do
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
- # Decrease the log volume.
- # config.log_level = :info
+ # Use the lowest log level to ensure availability of diagnostic information
+ # when problems arise.
+ config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt
index 32756eb88b..03a3568fbe 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt
@@ -31,7 +31,7 @@ Rails.application.configure do
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
- # Randomize the order test cases are executed
+ # Randomize the order test cases are executed.
config.active_support.test_order = :random
# Print deprecation notices to the stderr.
diff --git a/railties/lib/rails/generators/rails/app/templates/gitignore b/railties/lib/rails/generators/rails/app/templates/gitignore
index 8775e5e235..7c6f2098b8 100644
--- a/railties/lib/rails/generators/rails/app/templates/gitignore
+++ b/railties/lib/rails/generators/rails/app/templates/gitignore
@@ -14,5 +14,6 @@
<% end -%>
# Ignore all logfiles and tempfiles.
-/log/*.log
+/log/*
+!/log/.keep
/tmp
diff --git a/railties/lib/rails/generators/rails/plugin/templates/rails/javascripts.js b/railties/lib/rails/generators/rails/plugin/templates/rails/javascripts.js
index 5bc2e1c8b5..c28e5badc6 100644
--- a/railties/lib/rails/generators/rails/plugin/templates/rails/javascripts.js
+++ b/railties/lib/rails/generators/rails/plugin/templates/rails/javascripts.js
@@ -2,7 +2,7 @@
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
-// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
+// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
diff --git a/railties/lib/rails/generators/rails/plugin/templates/rails/stylesheets.css b/railties/lib/rails/generators/rails/plugin/templates/rails/stylesheets.css
index a443db3401..f9cd5b3483 100644
--- a/railties/lib/rails/generators/rails/plugin/templates/rails/stylesheets.css
+++ b/railties/lib/rails/generators/rails/plugin/templates/rails/stylesheets.css
@@ -3,7 +3,7 @@
* listed below.
*
* Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
- * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
+ * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
*
* You're free to add application-wide styles to this file and they'll appear at the bottom of the
* compiled file so the styles you add here take precedence over styles defined in any styles
diff --git a/railties/lib/rails/generators/resource_helpers.rb b/railties/lib/rails/generators/resource_helpers.rb
index 4669935156..3f84d76ae0 100644
--- a/railties/lib/rails/generators/resource_helpers.rb
+++ b/railties/lib/rails/generators/resource_helpers.rb
@@ -39,7 +39,7 @@ module Rails
def assign_controller_names!(name)
@controller_name = name
@controller_class_path = name.include?('/') ? name.split('/') : name.split('::')
- @controller_class_path.map! { |m| m.underscore }
+ @controller_class_path.map!(&:underscore)
@controller_file_name = @controller_class_path.pop
end
@@ -48,7 +48,7 @@ module Rails
end
def controller_class_name
- (controller_class_path + [controller_file_name]).map!{ |m| m.camelize }.join('::')
+ (controller_class_path + [controller_file_name]).map!(&:camelize).join('::')
end
def controller_i18n_scope
diff --git a/railties/lib/rails/info.rb b/railties/lib/rails/info.rb
index 357aebf584..5909446b66 100644
--- a/railties/lib/rails/info.rb
+++ b/railties/lib/rails/info.rb
@@ -1,11 +1,14 @@
require "cgi"
module Rails
+ # This module helps build the runtime properties used to display in the
+ # Rails::InfoController responses. Including the active Rails version, Ruby
+ # version, Rack version, and so on.
module Info
mattr_accessor :properties
class << (@@properties = [])
def names
- map {|val| val.first }
+ map(&:first)
end
def value_for(property_name)
@@ -23,7 +26,7 @@ module Rails
end
def to_s
- column_width = properties.names.map {|name| name.length}.max
+ column_width = properties.names.map(&:length).max
info = properties.map do |name, value|
value = value.join(", ") if value.is_a?(Array)
"%-#{column_width}s %s" % [name, value]
diff --git a/railties/lib/rails/paths.rb b/railties/lib/rails/paths.rb
index 3eb66c07af..5458036219 100644
--- a/railties/lib/rails/paths.rb
+++ b/railties/lib/rails/paths.rb
@@ -77,23 +77,23 @@ module Rails
end
def all_paths
- values.tap { |v| v.uniq! }
+ values.tap(&:uniq!)
end
def autoload_once
- filter_by { |p| p.autoload_once? }
+ filter_by(&:autoload_once?)
end
def eager_load
- filter_by { |p| p.eager_load? }
+ filter_by(&:eager_load?)
end
def autoload_paths
- filter_by { |p| p.autoload? }
+ filter_by(&:autoload?)
end
def load_paths
- filter_by { |p| p.load_path? }
+ filter_by(&:load_path?)
end
private
@@ -167,8 +167,8 @@ module Rails
@paths.concat paths
end
- def unshift(path)
- @paths.unshift path
+ def unshift(*paths)
+ @paths.unshift(*paths)
end
def to_ary
diff --git a/railties/lib/rails/ruby_version_check.rb b/railties/lib/rails/ruby_version_check.rb
index df74643a59..edfe5cb786 100644
--- a/railties/lib/rails/ruby_version_check.rb
+++ b/railties/lib/rails/ruby_version_check.rb
@@ -1,13 +1,13 @@
-if RUBY_VERSION < '1.9.3'
+if RUBY_VERSION < '2.1.0'
desc = defined?(RUBY_DESCRIPTION) ? RUBY_DESCRIPTION : "ruby #{RUBY_VERSION} (#{RUBY_RELEASE_DATE})"
abort <<-end_message
- Rails 4 prefers to run on Ruby 2.1 or newer.
+ Rails 5 requires to run on Ruby 2.1 or newer.
You're running
#{desc}
- Please upgrade to Ruby 1.9.3 or newer to continue.
+ Please upgrade to Ruby 2.1.0 or newer to continue.
end_message
end
diff --git a/railties/lib/rails/source_annotation_extractor.rb b/railties/lib/rails/source_annotation_extractor.rb
index 201532d299..9b058a1848 100644
--- a/railties/lib/rails/source_annotation_extractor.rb
+++ b/railties/lib/rails/source_annotation_extractor.rb
@@ -80,9 +80,8 @@ class SourceAnnotationExtractor
# Returns a hash that maps filenames under +dir+ (recursively) to arrays
# with their annotations. Only files with annotations are included. Files
- # with extension +.builder+, +.rb+, +.erb+, +.haml+, +.slim+, +.css+,
- # +.scss+, +.js+, +.coffee+, +.rake+, +.sass+ and +.less+
- # are taken into account.
+ # with extension +.builder+, +.rb+, +.rake+, +.yml+, +.yaml+, +.ruby+,
+ # +.css+, +.js+ and +.erb+ are taken into account.
def find_in(dir)
results = {}
diff --git a/railties/lib/rails/tasks/statistics.rake b/railties/lib/rails/tasks/statistics.rake
index b94cd244be..4f09ded31d 100644
--- a/railties/lib/rails/tasks/statistics.rake
+++ b/railties/lib/rails/tasks/statistics.rake
@@ -14,10 +14,11 @@ STATS_DIRECTORIES = [
%w(Helper\ tests test/helpers),
%w(Model\ tests test/models),
%w(Mailer\ tests test/mailers),
+ %w(Job\ tests test/jobs),
%w(Integration\ tests test/integration),
%w(Functional\ tests\ (old) test/functional),
%w(Unit\ tests \ (old) test/unit)
-].collect do |name, dir|
+].collect do |name, dir|
[ name, "#{File.dirname(Rake.application.rakefile_location)}/#{dir}" ]
end.select { |name, dir| File.directory?(dir) }
diff --git a/railties/lib/rails/templates/rails/welcome/index.html.erb b/railties/lib/rails/templates/rails/welcome/index.html.erb
index 89792066d5..6726c23fc9 100644
--- a/railties/lib/rails/templates/rails/welcome/index.html.erb
+++ b/railties/lib/rails/templates/rails/welcome/index.html.erb
@@ -237,7 +237,7 @@
<ol>
<li>
- <h2>Use <code>rails generate</code> to create your models and controllers</h2>
+ <h2>Use <code>bin/rails generate</code> to create your models and controllers</h2>
<p>To see all available options, run it without parameters.</p>
</li>
diff --git a/railties/lib/rails/test_unit/testing.rake b/railties/lib/rails/test_unit/testing.rake
index 957deb8a60..254ea9ecf6 100644
--- a/railties/lib/rails/test_unit/testing.rake
+++ b/railties/lib/rails/test_unit/testing.rake
@@ -3,27 +3,45 @@ require 'rails/test_unit/sub_test_task'
task default: :test
-desc 'Runs test:units, test:functionals, test:generators, test:integration, test:jobs together'
+desc "Runs all tests in test folder"
task :test do
Rails::TestTask.test_creator(Rake.application.top_level_tasks).invoke_rake_task
end
namespace :test do
task :prepare do
- # Placeholder task for other Railtie and plugins to enhance. See Active Record for an example.
+ # Placeholder task for other Railtie and plugins to enhance.
+ # If used with Active Record, this task runs before the database schema is synchronized.
end
- task :run => ['test:units', 'test:functionals', 'test:generators', 'test:integration', 'test:jobs']
+ Rails::TestTask.new(:run) do |t|
+ t.pattern = "test/**/*_test.rb"
+ end
+
+ desc "Run tests quickly, but also reset db"
+ task :db => %w[db:test:prepare test]
- # Inspired by: http://ngauthier.com/2012/02/quick-tests-with-bash.html
desc "Run tests quickly by merging all types and not resetting db"
Rails::TestTask.new(:all) do |t|
t.pattern = "test/**/*_test.rb"
end
+ Rake::Task["test:all"].enhance do
+ Rake::Task["test:deprecate_all"].invoke
+ end
+
+ task :deprecate_all do
+ ActiveSupport::Deprecation.warn "rake test:all is deprecated and will be removed in Rails 5. " \
+ "Use rake test to run all tests in test directory."
+ end
+
namespace :all do
desc "Run tests quickly, but also reset db"
task :db => %w[db:test:prepare test:all]
+
+ Rake::Task["test:all:db"].enhance do
+ Rake::Task["test:deprecate_all"].invoke
+ end
end
Rails::TestTask.new(single: "test:prepare")
diff --git a/railties/railties.gemspec b/railties/railties.gemspec
index 56b8736800..09afcdec04 100644
--- a/railties/railties.gemspec
+++ b/railties/railties.gemspec
@@ -7,7 +7,7 @@ Gem::Specification.new do |s|
s.summary = 'Tools for creating, working with, and running Rails applications.'
s.description = 'Rails internals: application bootup, plugins, generators, and rake tasks.'
- s.required_ruby_version = '>= 1.9.3'
+ s.required_ruby_version = '>= 2.1.0'
s.license = 'MIT'
diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb
index 0eddf644d9..1f97807f8c 100644
--- a/railties/test/application/configuration_test.rb
+++ b/railties/test/application/configuration_test.rb
@@ -59,6 +59,20 @@ module ApplicationTests
end
end
+ test "lib dir is on LOAD_PATH during config" do
+ app_file 'lib/my_logger.rb', <<-RUBY
+ require "logger"
+ class MyLogger < ::Logger
+ end
+ RUBY
+ add_to_top_of_config <<-RUBY
+ require 'my_logger'
+ config.logger = MyLogger.new STDOUT
+ RUBY
+ require "#{app_path}/config/environment"
+ assert_equal 'MyLogger', Rails.application.config.logger.class.name
+ end
+
test "a renders exception on pending migration" do
add_to_config <<-RUBY
config.active_record.migration_error = :page_load
@@ -301,6 +315,51 @@ module ApplicationTests
assert_equal 'some_value', verifier.verify(message)
end
+ test "application message verifier can be used when the key_generator is ActiveSupport::LegacyKeyGenerator" do
+ app_file 'config/initializers/secret_token.rb', <<-RUBY
+ Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33"
+ RUBY
+ app_file 'config/secrets.yml', <<-YAML
+ development:
+ secret_key_base:
+ YAML
+ require "#{app_path}/config/environment"
+
+
+ assert_equal app.env_config['action_dispatch.key_generator'], Rails.application.key_generator
+ assert_equal app.env_config['action_dispatch.key_generator'].class, ActiveSupport::LegacyKeyGenerator
+ message = app.message_verifier(:sensitive_value).generate("some_value")
+ assert_equal 'some_value', Rails.application.message_verifier(:sensitive_value).verify(message)
+ end
+
+ test "warns when secrets.secret_key_base is blank and config.secret_token is set" do
+ app_file 'config/initializers/secret_token.rb', <<-RUBY
+ Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33"
+ RUBY
+ app_file 'config/secrets.yml', <<-YAML
+ development:
+ secret_key_base:
+ YAML
+ require "#{app_path}/config/environment"
+
+ assert_deprecated(/You didn't set `secret_key_base`./) do
+ app.env_config
+ end
+ end
+
+ test "prefer secrets.secret_token over config.secret_token" do
+ app_file 'config/initializers/secret_token.rb', <<-RUBY
+ Rails.application.config.secret_token = ""
+ RUBY
+ app_file 'config/secrets.yml', <<-YAML
+ development:
+ secret_token: 3b7cd727ee24e8444053437c36cc66c3
+ YAML
+ require "#{app_path}/config/environment"
+
+ assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.secrets.secret_token
+ end
+
test "application verifier can build different verifiers" do
make_basic_app do |app|
app.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33'
@@ -341,6 +400,21 @@ module ApplicationTests
assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.secrets.secret_key_base
end
+ test "config.secret_token over-writes a blank secrets.secret_token" do
+ app_file 'config/initializers/secret_token.rb', <<-RUBY
+ Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33"
+ RUBY
+ app_file 'config/secrets.yml', <<-YAML
+ development:
+ secret_key_base:
+ secret_token:
+ YAML
+ require "#{app_path}/config/environment"
+
+ assert_equal 'b3c631c314c0bbca50c1b2843150fe33', app.secrets.secret_token
+ assert_equal 'b3c631c314c0bbca50c1b2843150fe33', app.config.secret_token
+ end
+
test "custom secrets saved in config/secrets.yml are loaded in app secrets" do
app_file 'config/secrets.yml', <<-YAML
development:
@@ -362,6 +436,51 @@ module ApplicationTests
assert_nil app.secrets.not_defined
end
+ test "config.secret_key_base over-writes a blank secrets.secret_key_base" do
+ app_file 'config/initializers/secret_token.rb', <<-RUBY
+ Rails.application.config.secret_key_base = "iaminallyoursecretkeybase"
+ RUBY
+ app_file 'config/secrets.yml', <<-YAML
+ development:
+ secret_key_base:
+ YAML
+ require "#{app_path}/config/environment"
+
+ assert_equal "iaminallyoursecretkeybase", app.secrets.secret_key_base
+ end
+
+ test "uses ActiveSupport::LegacyKeyGenerator as app.key_generator when secrets.secret_key_base is blank" do
+ app_file 'config/initializers/secret_token.rb', <<-RUBY
+ Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33"
+ RUBY
+ app_file 'config/secrets.yml', <<-YAML
+ development:
+ secret_key_base:
+ YAML
+ require "#{app_path}/config/environment"
+
+ assert_equal 'b3c631c314c0bbca50c1b2843150fe33', app.config.secret_token
+ assert_equal nil, app.secrets.secret_key_base
+ assert_equal app.key_generator.class, ActiveSupport::LegacyKeyGenerator
+ end
+
+ test "uses ActiveSupport::LegacyKeyGenerator with config.secret_token as app.key_generator when secrets.secret_key_base is blank" do
+ app_file 'config/initializers/secret_token.rb', <<-RUBY
+ Rails.application.config.secret_token = ""
+ RUBY
+ app_file 'config/secrets.yml', <<-YAML
+ development:
+ secret_key_base:
+ YAML
+ require "#{app_path}/config/environment"
+
+ assert_equal '', app.config.secret_token
+ assert_equal nil, app.secrets.secret_key_base
+ assert_raise ArgumentError, /\AA secret is required/ do
+ app.key_generator
+ end
+ end
+
test "protect from forgery is the default in a new app" do
make_basic_app
@@ -848,6 +967,36 @@ module ApplicationTests
end
end
+ test "Blank config.log_level is not deprecated for non-production environment" do
+ with_rails_env "development" do
+ assert_not_deprecated do
+ make_basic_app do |app|
+ app.config.log_level = nil
+ end
+ end
+ end
+ end
+
+ test "Blank config.log_level is deprecated for the production environment" do
+ with_rails_env "production" do
+ assert_deprecated(/log_level/) do
+ make_basic_app do |app|
+ app.config.log_level = nil
+ end
+ end
+ end
+ end
+
+ test "Not blank config.log_level is not deprecated for the production environment" do
+ with_rails_env "production" do
+ assert_not_deprecated do
+ make_basic_app do |app|
+ app.config.log_level = :info
+ end
+ end
+ end
+ end
+
test "config.log_level with custom logger" do
make_basic_app do |app|
app.config.logger = Logger.new(STDOUT)
diff --git a/railties/test/application/middleware/session_test.rb b/railties/test/application/middleware/session_test.rb
index 31a64c2f5a..eb7885e5b1 100644
--- a/railties/test/application/middleware/session_test.rb
+++ b/railties/test/application/middleware/session_test.rb
@@ -203,7 +203,7 @@ module ApplicationTests
RUBY
add_to_config <<-RUBY
- config.secret_token = "3b7cd727ee24e8444053437c36cc66c4"
+ secrets.secret_token = "3b7cd727ee24e8444053437c36cc66c4"
RUBY
require "#{app_path}/config/environment"
@@ -258,7 +258,7 @@ module ApplicationTests
RUBY
add_to_config <<-RUBY
- config.secret_token = "3b7cd727ee24e8444053437c36cc66c4"
+ secrets.secret_token = "3b7cd727ee24e8444053437c36cc66c4"
RUBY
require "#{app_path}/config/environment"
@@ -317,7 +317,7 @@ module ApplicationTests
RUBY
add_to_config <<-RUBY
- config.secret_token = "3b7cd727ee24e8444053437c36cc66c4"
+ secrets.secret_token = "3b7cd727ee24e8444053437c36cc66c4"
secrets.secret_key_base = nil
RUBY
@@ -334,7 +334,7 @@ module ApplicationTests
get '/foo/read_signed_cookie'
assert_equal '2', last_response.body
- verifier = ActiveSupport::MessageVerifier.new(app.config.secret_token)
+ verifier = ActiveSupport::MessageVerifier.new(app.secrets.secret_token)
get '/foo/read_raw_cookie'
assert_equal 2, verifier.verify(last_response.body)['foo']
diff --git a/railties/test/application/multiple_applications_test.rb b/railties/test/application/multiple_applications_test.rb
index 9ebf163671..cddc79cc85 100644
--- a/railties/test/application/multiple_applications_test.rb
+++ b/railties/test/application/multiple_applications_test.rb
@@ -8,6 +8,7 @@ module ApplicationTests
build_app(initializers: true)
boot_rails
require "#{rails_root}/config/environment"
+ Rails.application.config.some_setting = 'something_or_other'
end
def teardown
@@ -18,7 +19,7 @@ module ApplicationTests
clone = Rails.application.clone
assert_equal Rails.application.config, clone.config, "The cloned application should get a copy of the config"
- assert_equal Rails.application.config.secret_key_base, clone.config.secret_key_base, "The base secret key on the config should be the same"
+ assert_equal Rails.application.config.some_setting, clone.config.some_setting, "The some_setting on the config should be the same"
end
def test_inheriting_multiple_times_from_application
@@ -160,13 +161,14 @@ module ApplicationTests
def test_inserting_configuration_into_application
app = AppTemplate::Application.new(config: Rails.application.config)
- new_config = Rails::Application::Configuration.new("root_of_application")
- new_config.secret_key_base = "some_secret_key_dude"
- app.config.secret_key_base = "a_different_secret_key"
+ app.config.some_setting = "a_different_setting"
+ assert_equal "a_different_setting", app.config.some_setting, "The configuration's some_setting should be set."
- assert_equal "a_different_secret_key", app.config.secret_key_base, "The configuration's secret key should be set."
+ new_config = Rails::Application::Configuration.new("root_of_application")
+ new_config.some_setting = "some_setting_dude"
app.config = new_config
- assert_equal "some_secret_key_dude", app.config.secret_key_base, "The configuration's secret key should have changed."
+
+ assert_equal "some_setting_dude", app.config.some_setting, "The configuration's some_setting should have changed."
assert_equal "root_of_application", app.config.root, "The root should have changed to the new config's root."
assert_equal new_config, app.config, "The application's config should have changed to the new config."
end
diff --git a/railties/test/application/rake/dbs_test.rb b/railties/test/application/rake/dbs_test.rb
index 524c70aad2..0a5873bcbf 100644
--- a/railties/test/application/rake/dbs_test.rb
+++ b/railties/test/application/rake/dbs_test.rb
@@ -175,15 +175,6 @@ module ApplicationTests
db_test_load_structure
end
- test 'db:test deprecation' do
- require "#{app_path}/config/environment"
- Dir.chdir(app_path) do
- output = `bundle exec rake db:migrate db:test:prepare 2>&1`
- assert_equal "WARNING: db:test:prepare is deprecated. The Rails test helper now maintains " \
- "your test schema automatically, see the release notes for details.\n", output
- end
- end
-
test 'db:setup loads schema and seeds database' do
begin
@old_rails_env = ENV["RAILS_ENV"]
diff --git a/railties/test/application/routing_test.rb b/railties/test/application/routing_test.rb
index 8576a2b738..cbada6be97 100644
--- a/railties/test/application/routing_test.rb
+++ b/railties/test/application/routing_test.rb
@@ -123,6 +123,26 @@ module ApplicationTests
assert_equal '/archives', last_response.body
end
+ test "mount named rack app" do
+ controller :foo, <<-RUBY
+ class FooController < ApplicationController
+ def index
+ render text: my_blog_path
+ end
+ end
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ Rails.application.routes.draw do
+ mount lambda { |env| [200, {}, [env["PATH_INFO"]]] }, at: "/blog", as: "my_blog"
+ get '/foo' => 'foo#index'
+ end
+ RUBY
+
+ get '/foo'
+ assert_equal '/blog', last_response.body
+ end
+
test "multiple controllers" do
controller :foo, <<-RUBY
class FooController < ApplicationController
diff --git a/railties/test/application/test_test.rb b/railties/test/application/test_test.rb
index c724c867ec..c7132837b1 100644
--- a/railties/test/application/test_test.rb
+++ b/railties/test/application/test_test.rb
@@ -193,6 +193,98 @@ module ApplicationTests
assert_successful_test_run('models/user_test.rb')
end
+ # TODO: would be nice if we could detect the schema change automatically.
+ # For now, the user has to synchronize the schema manually.
+ # This test-case serves as a reminder for this use-case.
+ test "manually synchronize test schema after rollback" do
+ output = script('generate model user name:string')
+ version = output.match(/(\d+)_create_users\.rb/)[1]
+
+ app_file 'test/models/user_test.rb', <<-RUBY
+ require 'test_helper'
+
+ class UserTest < ActiveSupport::TestCase
+ test "user" do
+ assert_equal ["id", "name"], User.columns_hash.keys
+ end
+ end
+ RUBY
+ app_file 'db/schema.rb', <<-RUBY
+ ActiveRecord::Schema.define(version: #{version}) do
+ create_table :users do |t|
+ t.string :name
+ end
+ end
+ RUBY
+
+ assert_successful_test_run "models/user_test.rb"
+
+ # Simulate `db:rollback` + edit of the migration file + `db:migrate`
+ app_file 'db/schema.rb', <<-RUBY
+ ActiveRecord::Schema.define(version: #{version}) do
+ create_table :users do |t|
+ t.string :name
+ t.integer :age
+ end
+ end
+ RUBY
+
+ assert_successful_test_run "models/user_test.rb"
+
+ Dir.chdir(app_path) { `bin/rake db:test:prepare` }
+
+ assert_unsuccessful_run "models/user_test.rb", <<-ASSERTION
+Expected: ["id", "name"]
+ Actual: ["id", "name", "age"]
+ ASSERTION
+ end
+
+ test "hooks for plugins" do
+ output = script('generate model user name:string')
+ version = output.match(/(\d+)_create_users\.rb/)[1]
+
+ app_file 'lib/tasks/hooks.rake', <<-RUBY
+ task :before_hook do
+ has_user_table = ActiveRecord::Base.connection.table_exists?('users')
+ puts "before: " + has_user_table.to_s
+ end
+
+ task :after_hook do
+ has_user_table = ActiveRecord::Base.connection.table_exists?('users')
+ puts "after: " + has_user_table.to_s
+ end
+
+ Rake::Task["db:test:prepare"].enhance [:before_hook] do
+ Rake::Task[:after_hook].invoke
+ end
+ RUBY
+ app_file 'test/models/user_test.rb', <<-RUBY
+ require 'test_helper'
+ class UserTest < ActiveSupport::TestCase
+ test "user" do
+ User.create! name: "Jon"
+ end
+ end
+ RUBY
+
+ # Simulate `db:migrate`
+ app_file 'db/schema.rb', <<-RUBY
+ ActiveRecord::Schema.define(version: #{version}) do
+ create_table :users do |t|
+ t.string :name
+ end
+ end
+ RUBY
+
+ output = assert_successful_test_run "models/user_test.rb"
+ assert_includes output, "before: false\nafter: true"
+
+ # running tests again won't trigger a schema update
+ output = assert_successful_test_run "models/user_test.rb"
+ assert_not_includes output, "before:"
+ assert_not_includes output, "after:"
+ end
+
private
def assert_unsuccessful_run(name, message)
result = run_test_file(name)
@@ -208,7 +300,7 @@ module ApplicationTests
end
def run_test_file(name, options = {})
- ruby '-Itest', "#{app_path}/test/#{name}", options
+ ruby '-Itest', "#{app_path}/test/#{name}", options.deep_merge(env: {"RAILS_ENV" => "test"})
end
def ruby(*args)
diff --git a/railties/test/application/url_generation_test.rb b/railties/test/application/url_generation_test.rb
index efbc853d7b..ef16ab56ed 100644
--- a/railties/test/application/url_generation_test.rb
+++ b/railties/test/application/url_generation_test.rb
@@ -15,7 +15,7 @@ module ApplicationTests
require "action_view/railtie"
class MyApp < Rails::Application
- config.secret_key_base = "3b7cd727ee24e8444053437c36cc66c4"
+ secrets.secret_key_base = "3b7cd727ee24e8444053437c36cc66c4"
config.session_store :cookie_store, key: "_myapp_session"
config.active_support.deprecation = :log
config.eager_load = false
diff --git a/railties/test/generators/mailer_generator_test.rb b/railties/test/generators/mailer_generator_test.rb
index 25649881eb..bab15ce172 100644
--- a/railties/test/generators/mailer_generator_test.rb
+++ b/railties/test/generators/mailer_generator_test.rb
@@ -8,8 +8,18 @@ class MailerGeneratorTest < Rails::Generators::TestCase
def test_mailer_skeleton_is_created
run_generator
assert_file "app/mailers/notifier.rb" do |mailer|
- assert_match(/class Notifier < ActionMailer::Base/, mailer)
+ assert_match(/class Notifier < ApplicationMailer/, mailer)
+ assert_no_match(/default from: "from@example.com"/, mailer)
+ assert_no_match(/layout :mailer_notifier/, mailer)
+ end
+ end
+
+ def test_application_mailer_skeleton_is_created
+ run_generator
+ assert_file "app/mailers/application_mailer.rb" do |mailer|
+ assert_match(/class ApplicationMailer < ActionMailer::Base/, mailer)
assert_match(/default from: "from@example.com"/, mailer)
+ assert_match(/layout 'mailer'/, mailer)
end
end
@@ -77,6 +87,10 @@ class MailerGeneratorTest < Rails::Generators::TestCase
assert_match(%r(\sapp/views/notifier/bar\.text\.erb), view)
assert_match(/<%= @greeting %>/, view)
end
+
+ assert_file "app/views/layouts/mailer.text.erb" do |view|
+ assert_match(/<%= yield %>/, view)
+ end
end
def test_invokes_default_html_template_engine
@@ -90,11 +104,17 @@ class MailerGeneratorTest < Rails::Generators::TestCase
assert_match(%r(\sapp/views/notifier/bar\.html\.erb), view)
assert_match(/<%= @greeting %>/, view)
end
+
+ assert_file "app/views/layouts/mailer.html.erb" do |view|
+ assert_match(%r{<html>\n <body>\n <%= yield %>\n </body>\n</html>}, view)
+ end
end
def test_invokes_default_template_engine_even_with_no_action
run_generator ["notifier"]
assert_file "app/views/notifier"
+ assert_file "app/views/layouts/mailer.text.erb"
+ assert_file "app/views/layouts/mailer.html.erb"
end
def test_logs_if_the_template_engine_cannot_be_found
@@ -105,7 +125,7 @@ class MailerGeneratorTest < Rails::Generators::TestCase
def test_mailer_with_namedspaced_mailer
run_generator ["Farm::Animal", "moos"]
assert_file "app/mailers/farm/animal.rb" do |mailer|
- assert_match(/class Farm::Animal < ActionMailer::Base/, mailer)
+ assert_match(/class Farm::Animal < ApplicationMailer/, mailer)
assert_match(/en\.farm\.animal\.moos\.subject/, mailer)
end
assert_file "test/mailers/previews/farm/animal_preview.rb" do |preview|
diff --git a/railties/test/generators/migration_generator_test.rb b/railties/test/generators/migration_generator_test.rb
index 72f5fe29ca..c2c8e2abad 100644
--- a/railties/test/generators/migration_generator_test.rb
+++ b/railties/test/generators/migration_generator_test.rb
@@ -85,6 +85,18 @@ class MigrationGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_remove_migration_with_references_removes_foreign_keys
+ migration = "remove_references_from_books"
+ run_generator [migration, "author:belongs_to", "distributor:references{polymorphic}"]
+
+ assert_migration "db/migrate/#{migration}.rb" do |content|
+ assert_method :change, content do |change|
+ assert_match(/remove_foreign_key :books, :authors/, change)
+ assert_no_match(/remove_foreign_key :books, :distributors/, change)
+ end
+ end
+ end
+
def test_add_migration_with_attributes_and_indices
migration = "add_title_with_index_and_body_to_posts"
run_generator [migration, "title:string:index", "body:text", "user_id:integer:uniq"]
@@ -171,6 +183,18 @@ class MigrationGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_add_migration_with_references_adds_foreign_keys
+ migration = "add_references_to_books"
+ run_generator [migration, "author:belongs_to", "distributor:references{polymorphic}"]
+
+ assert_migration "db/migrate/#{migration}.rb" do |content|
+ assert_method :change, content do |change|
+ assert_match(/add_foreign_key :books, :authors/, change)
+ assert_no_match(/add_foreign_key :books, :distributors/, change)
+ end
+ end
+ end
+
def test_create_join_table_migration
migration = "add_media_join_table"
run_generator [migration, "artist_id", "musics:uniq"]
@@ -205,7 +229,7 @@ class MigrationGeneratorTest < Rails::Generators::TestCase
end
end
end
-
+
def test_properly_identifies_usage_file
assert generator_class.send(:usage_path)
end
diff --git a/railties/test/generators/model_generator_test.rb b/railties/test/generators/model_generator_test.rb
index c78597c81b..ac7a0acf6b 100644
--- a/railties/test/generators/model_generator_test.rb
+++ b/railties/test/generators/model_generator_test.rb
@@ -407,6 +407,27 @@ class ModelGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_foreign_key_is_added_for_references
+ run_generator ["account", "supplier:belongs_to", "user:references"]
+
+ assert_migration "db/migrate/create_accounts.rb" do |m|
+ assert_method :change, m do |up|
+ assert_match(/add_foreign_key :accounts, :suppliers/, up)
+ assert_match(/add_foreign_key :accounts, :users/, up)
+ end
+ end
+ end
+
+ def test_foreign_key_is_skipped_for_polymorphic_references
+ run_generator ["account", "supplier:belongs_to{polymorphic}"]
+
+ assert_migration "db/migrate/create_accounts.rb" do |m|
+ assert_method :change, m do |up|
+ assert_no_match(/add_foreign_key :accounts, :suppliers/, up)
+ end
+ end
+ end
+
private
def assert_generated_fixture(path, parsed_contents)
fixture_file = File.new File.expand_path(path, destination_root)
diff --git a/railties/test/generators/namespaced_generators_test.rb b/railties/test/generators/namespaced_generators_test.rb
index 7eeb084eab..6075805152 100644
--- a/railties/test/generators/namespaced_generators_test.rb
+++ b/railties/test/generators/namespaced_generators_test.rb
@@ -148,8 +148,8 @@ class NamespacedMailerGeneratorTest < NamespacedGeneratorTestCase
run_generator
assert_file "app/mailers/test_app/notifier.rb" do |mailer|
assert_match(/module TestApp/, mailer)
- assert_match(/class Notifier < ActionMailer::Base/, mailer)
- assert_match(/default from: "from@example.com"/, mailer)
+ assert_match(/class Notifier < ApplicationMailer/, mailer)
+ assert_no_match(/default from: "from@example.com"/, mailer)
end
end
diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb
index 40469e31d7..9ad0ec0d34 100644
--- a/railties/test/isolation/abstract_unit.rb
+++ b/railties/test/isolation/abstract_unit.rb
@@ -143,6 +143,7 @@ module TestHelpers
config.active_support.deprecation = :log
config.active_support.test_order = :random
config.action_controller.allow_forgery_protection = false
+ config.log_level = :info
RUBY
end
@@ -162,6 +163,8 @@ module TestHelpers
app.secrets.secret_key_base = "3b7cd727ee24e8444053437c36cc66c4"
app.config.session_store :cookie_store, key: "_myapp_session"
app.config.active_support.deprecation = :log
+ app.config.active_support.test_order = :random
+ app.config.log_level = :info
yield app if block_given?
app.initialize!
@@ -231,6 +234,15 @@ module TestHelpers
end
end
+ def add_to_top_of_config(str)
+ environment = File.read("#{app_path}/config/application.rb")
+ if environment =~ /(Rails::Application\s*)/
+ File.open("#{app_path}/config/application.rb", 'w') do |f|
+ f.puts $` + $1 + "\n#{str}\n" + $'
+ end
+ end
+ end
+
def add_to_config(str)
environment = File.read("#{app_path}/config/application.rb")
if environment =~ /(\n\s*end\s*end\s*)\Z/
diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb
index 6239af2066..260ee0eda9 100644
--- a/railties/test/railties/engine_test.rb
+++ b/railties/test/railties/engine_test.rb
@@ -518,7 +518,7 @@ YAML
def call(env)
response = @app.call(env)
- response[2].each { |b| b.upcase! }
+ response[2].each(&:upcase!)
response
end
end
diff --git a/tasks/release.rb b/tasks/release.rb
index de05dfad99..729e0761ad 100644
--- a/tasks/release.rb
+++ b/tasks/release.rb
@@ -102,7 +102,7 @@ namespace :all do
abort "[ABORTING] `git status` reports a dirty tree. Make sure all changes are committed"
end
- unless ENV['SKIP_TAG'] || `git tag | grep '^#{tag}$`.strip.empty?
+ unless ENV['SKIP_TAG'] || `git tag | grep '^#{tag}$'`.strip.empty?
abort "[ABORTING] `git tag` shows that #{tag} already exists. Has this version already\n"\
" been released? Git tagging can be skipped by setting SKIP_TAG=1"
end
diff --git a/version.rb b/version.rb
index 8abed99f2c..7d74b1bfe5 100644
--- a/version.rb
+++ b/version.rb
@@ -5,10 +5,10 @@ module Rails
end
module VERSION
- MAJOR = 4
- MINOR = 2
+ MAJOR = 5
+ MINOR = 0
TINY = 0
- PRE = "beta4"
+ PRE = "alpha"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end