aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.travis.yml5
-rw-r--r--CONTRIBUTING.md40
-rw-r--r--Gemfile34
-rw-r--r--Gemfile.lock265
-rw-r--r--RAILS_VERSION2
-rw-r--r--README.md12
-rw-r--r--Rakefile9
-rw-r--r--actioncable/CHANGELOG.md8
-rw-r--r--actioncable/MIT-LICENSE20
-rw-r--r--actioncable/README.md457
-rw-r--r--actioncable/Rakefile13
-rw-r--r--actioncable/actioncable.gemspec32
-rw-r--r--actioncable/lib/action_cable.rb50
-rw-r--r--actioncable/lib/action_cable/channel.rb14
-rw-r--r--actioncable/lib/action_cable/channel/base.rb277
-rw-r--r--actioncable/lib/action_cable/channel/broadcasting.rb29
-rw-r--r--actioncable/lib/action_cable/channel/callbacks.rb35
-rw-r--r--actioncable/lib/action_cable/channel/naming.rb22
-rw-r--r--actioncable/lib/action_cable/channel/periodic_timers.rb41
-rw-r--r--actioncable/lib/action_cable/channel/streams.rb114
-rw-r--r--actioncable/lib/action_cable/connection.rb16
-rw-r--r--actioncable/lib/action_cable/connection/authorization.rb13
-rw-r--r--actioncable/lib/action_cable/connection/base.rb221
-rw-r--r--actioncable/lib/action_cable/connection/identification.rb46
-rw-r--r--actioncable/lib/action_cable/connection/internal_channel.rb45
-rw-r--r--actioncable/lib/action_cable/connection/message_buffer.rb54
-rw-r--r--actioncable/lib/action_cable/connection/subscriptions.rb76
-rw-r--r--actioncable/lib/action_cable/connection/tagged_logger_proxy.rb40
-rw-r--r--actioncable/lib/action_cable/connection/web_socket.rb29
-rw-r--r--actioncable/lib/action_cable/engine.rb38
-rw-r--r--actioncable/lib/action_cable/gem_version.rb15
-rw-r--r--actioncable/lib/action_cable/helpers/action_cable_helper.rb29
-rw-r--r--actioncable/lib/action_cable/process/logging.rb10
-rw-r--r--actioncable/lib/action_cable/remote_connections.rb64
-rw-r--r--actioncable/lib/action_cable/server.rb19
-rw-r--r--actioncable/lib/action_cable/server/base.rb77
-rw-r--r--actioncable/lib/action_cable/server/broadcasting.rb54
-rw-r--r--actioncable/lib/action_cable/server/configuration.rb35
-rw-r--r--actioncable/lib/action_cable/server/connections.rb37
-rw-r--r--actioncable/lib/action_cable/server/worker.rb42
-rw-r--r--actioncable/lib/action_cable/server/worker/active_record_connection_management.rb22
-rw-r--r--actioncable/lib/action_cable/version.rb8
-rw-r--r--actioncable/lib/assets/javascripts/action_cable.coffee.erb23
-rw-r--r--actioncable/lib/assets/javascripts/action_cable/connection.coffee84
-rw-r--r--actioncable/lib/assets/javascripts/action_cable/connection_monitor.coffee84
-rw-r--r--actioncable/lib/assets/javascripts/action_cable/consumer.coffee31
-rw-r--r--actioncable/lib/assets/javascripts/action_cable/subscription.coffee68
-rw-r--r--actioncable/lib/assets/javascripts/action_cable/subscriptions.coffee78
-rw-r--r--actioncable/lib/rails/generators/channel/USAGE14
-rw-r--r--actioncable/lib/rails/generators/channel/channel_generator.rb21
-rw-r--r--actioncable/lib/rails/generators/channel/templates/assets/channel.coffee14
-rw-r--r--actioncable/lib/rails/generators/channel/templates/channel.rb17
-rw-r--r--actioncable/test/channel/base_test.rb184
-rw-r--r--actioncable/test/channel/broadcasting_test.rb29
-rw-r--r--actioncable/test/channel/naming_test.rb10
-rw-r--r--actioncable/test/channel/periodic_timers_test.rb40
-rw-r--r--actioncable/test/channel/rejection_test.rb25
-rw-r--r--actioncable/test/channel/stream_test.rb80
-rw-r--r--actioncable/test/connection/authorization_test.rb32
-rw-r--r--actioncable/test/connection/base_test.rb118
-rw-r--r--actioncable/test/connection/cross_site_forgery_test.rb82
-rw-r--r--actioncable/test/connection/identifier_test.rb77
-rw-r--r--actioncable/test/connection/multiple_identifiers_test.rb41
-rw-r--r--actioncable/test/connection/string_identifier_test.rb44
-rw-r--r--actioncable/test/connection/subscriptions_test.rb116
-rw-r--r--actioncable/test/stubs/global_id.rb8
-rw-r--r--actioncable/test/stubs/room.rb16
-rw-r--r--actioncable/test/stubs/test_connection.rb21
-rw-r--r--actioncable/test/stubs/test_server.rb15
-rw-r--r--actioncable/test/stubs/user.rb15
-rw-r--r--actioncable/test/test_helper.rb42
-rw-r--r--actioncable/test/worker_test.rb49
-rw-r--r--actionmailer/CHANGELOG.md5
-rw-r--r--actionmailer/README.rdoc3
-rw-r--r--actionmailer/actionmailer.gemspec2
-rw-r--r--actionmailer/lib/action_mailer/base.rb156
-rw-r--r--actionmailer/lib/action_mailer/gem_version.rb2
-rw-r--r--actionmailer/lib/action_mailer/log_subscriber.rb6
-rw-r--r--actionmailer/lib/rails/generators/mailer/mailer_generator.rb3
-rw-r--r--actionpack/CHANGELOG.md68
-rw-r--r--actionpack/README.rdoc3
-rw-r--r--actionpack/lib/abstract_controller/callbacks.rb3
-rw-r--r--actionpack/lib/action_controller/caching/fragments.rb51
-rw-r--r--actionpack/lib/action_controller/metal/http_authentication.rb2
-rw-r--r--actionpack/lib/action_controller/metal/live.rb13
-rw-r--r--actionpack/lib/action_controller/metal/redirecting.rb40
-rw-r--r--actionpack/lib/action_controller/metal/request_forgery_protection.rb44
-rw-r--r--actionpack/lib/action_controller/metal/strong_parameters.rb29
-rw-r--r--actionpack/lib/action_controller/test_case.rb4
-rw-r--r--actionpack/lib/action_dispatch/http/mime_negotiation.rb9
-rw-r--r--actionpack/lib/action_dispatch/http/mime_type.rb26
-rw-r--r--actionpack/lib/action_dispatch/http/request.rb23
-rw-r--r--actionpack/lib/action_dispatch/http/response.rb2
-rw-r--r--actionpack/lib/action_dispatch/http/url.rb3
-rw-r--r--actionpack/lib/action_dispatch/middleware/cookies.rb13
-rw-r--r--actionpack/lib/action_dispatch/middleware/debug_exceptions.rb105
-rw-r--r--actionpack/lib/action_dispatch/middleware/remote_ip.rb22
-rw-r--r--actionpack/lib/action_dispatch/middleware/session/cookie_store.rb2
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (renamed from actionpack/lib/action_dispatch/middleware/templates/rescues/_source.erb)0
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/rescues/_source.text.erb8
-rw-r--r--actionpack/lib/action_dispatch/routing.rb2
-rw-r--r--actionpack/lib/action_dispatch/routing/mapper.rb17
-rw-r--r--actionpack/lib/action_dispatch/routing/route_set.rb10
-rw-r--r--actionpack/lib/action_dispatch/routing/url_for.rb5
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/response.rb15
-rw-r--r--actionpack/lib/action_dispatch/testing/integration.rb1
-rw-r--r--actionpack/lib/action_dispatch/testing/test_process.rb2
-rw-r--r--actionpack/lib/action_pack/gem_version.rb2
-rw-r--r--actionpack/test/assertions/response_assertions_test.rb43
-rw-r--r--actionpack/test/controller/base_test.rb2
-rw-r--r--actionpack/test/controller/caching_test.rb25
-rw-r--r--actionpack/test/controller/helper_test.rb10
-rw-r--r--actionpack/test/controller/http_token_authentication_test.rb8
-rw-r--r--actionpack/test/controller/live_stream_test.rb39
-rw-r--r--actionpack/test/controller/mime/respond_to_test.rb10
-rw-r--r--actionpack/test/controller/new_base/bare_metal_test.rb2
-rw-r--r--actionpack/test/controller/parameters/parameters_permit_test.rb36
-rw-r--r--actionpack/test/controller/redirect_test.rb42
-rw-r--r--actionpack/test/controller/request_forgery_protection_test.rb49
-rw-r--r--actionpack/test/controller/routing_test.rb6
-rw-r--r--actionpack/test/controller/test_case_test.rb2
-rw-r--r--actionpack/test/controller/url_for_test.rb7
-rw-r--r--actionpack/test/dispatch/cookies_test.rb2
-rw-r--r--actionpack/test/dispatch/debug_exceptions_test.rb77
-rw-r--r--actionpack/test/dispatch/live_response_test.rb2
-rw-r--r--actionpack/test/dispatch/mapper_test.rb14
-rw-r--r--actionpack/test/dispatch/request/session_test.rb2
-rw-r--r--actionpack/test/dispatch/request_test.rb76
-rw-r--r--actionpack/test/dispatch/response_test.rb5
-rw-r--r--actionpack/test/dispatch/routing_test.rb41
-rw-r--r--actionpack/test/dispatch/show_exceptions_test.rb16
-rw-r--r--actionpack/test/dispatch/url_generation_test.rb7
-rw-r--r--actionview/CHANGELOG.md30
-rw-r--r--actionview/README.rdoc3
-rw-r--r--actionview/lib/action_view/gem_version.rb2
-rw-r--r--actionview/lib/action_view/helpers/asset_tag_helper.rb2
-rw-r--r--actionview/lib/action_view/helpers/cache_helper.rb8
-rw-r--r--actionview/lib/action_view/helpers/translation_helper.rb10
-rw-r--r--actionview/lib/action_view/railtie.rb1
-rw-r--r--actionview/lib/action_view/testing/resolvers.rb3
-rw-r--r--actionview/test/abstract_unit.rb1
-rw-r--r--actionview/test/template/asset_tag_helper_test.rb5
-rw-r--r--actionview/test/template/date_helper_i18n_test.rb76
-rw-r--r--actionview/test/template/date_helper_test.rb22
-rw-r--r--actionview/test/template/form_options_helper_test.rb49
-rw-r--r--actionview/test/template/log_subscriber_test.rb87
-rw-r--r--actionview/test/template/render_test.rb4
-rw-r--r--actionview/test/template/test_test.rb4
-rw-r--r--actionview/test/template/translation_helper_test.rb10
-rw-r--r--actionview/test/template/url_helper_test.rb13
-rw-r--r--activejob/CHANGELOG.md5
-rw-r--r--activejob/README.md2
-rw-r--r--activejob/activejob.gemspec2
-rw-r--r--activejob/lib/active_job/gem_version.rb2
-rw-r--r--activejob/test/integration/queuing_test.rb2
-rw-r--r--activejob/test/support/integration/dummy_app_template.rb7
-rw-r--r--activejob/test/support/integration/test_case_helpers.rb16
-rw-r--r--activemodel/CHANGELOG.md5
-rw-r--r--activemodel/README.rdoc3
-rw-r--r--activemodel/lib/active_model/attribute_assignment.rb2
-rw-r--r--activemodel/lib/active_model/dirty.rb6
-rw-r--r--activemodel/lib/active_model/errors.rb12
-rw-r--r--activemodel/lib/active_model/gem_version.rb2
-rw-r--r--activemodel/lib/active_model/type/time.rb6
-rw-r--r--activemodel/lib/active_model/type/value.rb5
-rw-r--r--activemodel/test/cases/attribute_assignment_test.rb26
-rw-r--r--activemodel/test/cases/callbacks_test.rb2
-rw-r--r--activemodel/test/cases/errors_test.rb10
-rw-r--r--activemodel/test/cases/forbidden_attributes_protection_test.rb10
-rw-r--r--activemodel/test/cases/translation_test.rb5
-rw-r--r--activemodel/test/cases/validations/with_validation_test.rb1
-rw-r--r--activerecord/CHANGELOG.md129
-rw-r--r--activerecord/README.rdoc5
-rw-r--r--activerecord/RUNNING_UNIT_TESTS.rdoc1
-rw-r--r--activerecord/Rakefile14
-rw-r--r--activerecord/activerecord.gemspec2
-rwxr-xr-xactiverecord/bin/test2
-rw-r--r--activerecord/lib/active_record/associations.rb5
-rw-r--r--activerecord/lib/active_record/associations/association.rb9
-rw-r--r--activerecord/lib/active_record/associations/builder/belongs_to.rb3
-rw-r--r--activerecord/lib/active_record/associations/collection_association.rb12
-rw-r--r--activerecord/lib/active_record/associations/preloader/through_association.rb9
-rw-r--r--activerecord/lib/active_record/attribute_methods.rb12
-rw-r--r--activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb4
-rw-r--r--activerecord/lib/active_record/base.rb2
-rw-r--r--activerecord/lib/active_record/callbacks.rb23
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb2
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb17
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb4
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb45
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract_adapter.rb9
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb24
-rw-r--r--activerecord/lib/active_record/connection_adapters/connection_specification.rb2
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb11
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql_adapter.rb475
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb40
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb45
-rw-r--r--activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb7
-rw-r--r--activerecord/lib/active_record/fixtures.rb2
-rw-r--r--activerecord/lib/active_record/gem_version.rb2
-rw-r--r--activerecord/lib/active_record/inheritance.rb21
-rw-r--r--activerecord/lib/active_record/migration.rb82
-rw-r--r--activerecord/lib/active_record/migration/compatibility.rb90
-rw-r--r--activerecord/lib/active_record/model_schema.rb4
-rw-r--r--activerecord/lib/active_record/persistence.rb15
-rw-r--r--activerecord/lib/active_record/railtie.rb4
-rw-r--r--activerecord/lib/active_record/railties/databases.rake2
-rw-r--r--activerecord/lib/active_record/reflection.rb2
-rw-r--r--activerecord/lib/active_record/relation.rb5
-rw-r--r--activerecord/lib/active_record/relation/delegation.rb16
-rw-r--r--activerecord/lib/active_record/relation/finder_methods.rb17
-rw-r--r--activerecord/lib/active_record/relation/query_methods.rb67
-rw-r--r--activerecord/lib/active_record/relation/spawn_methods.rb10
-rw-r--r--activerecord/lib/active_record/sanitization.rb9
-rw-r--r--activerecord/lib/active_record/schema.rb2
-rw-r--r--activerecord/lib/active_record/tasks/database_tasks.rb2
-rw-r--r--activerecord/lib/active_record/tasks/mysql_database_tasks.rb2
-rw-r--r--activerecord/lib/active_record/tasks/postgresql_database_tasks.rb4
-rw-r--r--activerecord/lib/active_record/touch_later.rb16
-rw-r--r--activerecord/lib/active_record/transactions.rb26
-rw-r--r--activerecord/lib/active_record/validations/uniqueness.rb1
-rw-r--r--activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb2
-rw-r--r--activerecord/lib/rails/generators/active_record/migration/templates/migration.rb2
-rw-r--r--activerecord/lib/rails/generators/active_record/model/model_generator.rb25
-rw-r--r--activerecord/test/cases/adapter_test.rb4
-rw-r--r--activerecord/test/cases/adapters/mysql/active_schema_test.rb190
-rw-r--r--activerecord/test/cases/adapters/mysql/case_sensitivity_test.rb54
-rw-r--r--activerecord/test/cases/adapters/mysql/charset_collation_test.rb54
-rw-r--r--activerecord/test/cases/adapters/mysql/connection_test.rb210
-rw-r--r--activerecord/test/cases/adapters/mysql/consistency_test.rb49
-rw-r--r--activerecord/test/cases/adapters/mysql/enum_test.rb10
-rw-r--r--activerecord/test/cases/adapters/mysql/explain_test.rb21
-rw-r--r--activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb119
-rw-r--r--activerecord/test/cases/adapters/mysql/quoting_test.rb29
-rw-r--r--activerecord/test/cases/adapters/mysql/reserved_word_test.rb153
-rw-r--r--activerecord/test/cases/adapters/mysql/schema_test.rb94
-rw-r--r--activerecord/test/cases/adapters/mysql/sp_test.rb30
-rw-r--r--activerecord/test/cases/adapters/mysql/sql_types_test.rb14
-rw-r--r--activerecord/test/cases/adapters/mysql/statement_pool_test.rb19
-rw-r--r--activerecord/test/cases/adapters/mysql/table_options_test.rb42
-rw-r--r--activerecord/test/cases/adapters/mysql/unsigned_type_test.rb65
-rw-r--r--activerecord/test/cases/adapters/mysql2/active_schema_test.rb2
-rw-r--r--activerecord/test/cases/adapters/mysql2/charset_collation_test.rb2
-rw-r--r--activerecord/test/cases/adapters/mysql2/connection_test.rb25
-rw-r--r--activerecord/test/cases/adapters/mysql2/unsigned_type_test.rb2
-rw-r--r--activerecord/test/cases/adapters/postgresql/active_schema_test.rb8
-rw-r--r--activerecord/test/cases/adapters/postgresql/connection_test.rb20
-rw-r--r--activerecord/test/cases/adapters/postgresql/extension_migration_test.rb4
-rw-r--r--activerecord/test/cases/adapters/postgresql/geometric_test.rb160
-rw-r--r--activerecord/test/cases/adapters/postgresql/hstore_test.rb2
-rw-r--r--activerecord/test/cases/adapters/postgresql/schema_test.rb21
-rw-r--r--activerecord/test/cases/adapters/postgresql/uuid_test.rb2
-rw-r--r--activerecord/test/cases/adapters/sqlite3/sqlite3_create_folder_test.rb16
-rw-r--r--activerecord/test/cases/associations/belongs_to_associations_test.rb2
-rw-r--r--activerecord/test/cases/associations/eager_test.rb6
-rw-r--r--activerecord/test/cases/associations/has_many_associations_test.rb21
-rw-r--r--activerecord/test/cases/attribute_methods_test.rb2
-rw-r--r--activerecord/test/cases/base_test.rb50
-rw-r--r--activerecord/test/cases/binary_test.rb4
-rw-r--r--activerecord/test/cases/calculations_test.rb2
-rw-r--r--activerecord/test/cases/callbacks_test.rb2
-rw-r--r--activerecord/test/cases/column_definition_test.rb2
-rw-r--r--activerecord/test/cases/connection_adapters/mysql_type_lookup_test.rb2
-rw-r--r--activerecord/test/cases/custom_locking_test.rb2
-rw-r--r--activerecord/test/cases/date_time_precision_test.rb37
-rw-r--r--activerecord/test/cases/defaults_test.rb13
-rw-r--r--activerecord/test/cases/finder_test.rb172
-rw-r--r--activerecord/test/cases/fixtures_test.rb1
-rw-r--r--activerecord/test/cases/forbidden_attributes_protection_test.rb72
-rw-r--r--activerecord/test/cases/helper.rb4
-rw-r--r--activerecord/test/cases/inheritance_test.rb45
-rw-r--r--activerecord/test/cases/invalid_connection_test.rb2
-rw-r--r--activerecord/test/cases/invertible_migration_test.rb6
-rw-r--r--activerecord/test/cases/locking_test.rb2
-rw-r--r--activerecord/test/cases/migration/change_schema_test.rb8
-rw-r--r--activerecord/test/cases/migration/column_attributes_test.rb6
-rw-r--r--activerecord/test/cases/migration/column_positioning_test.rb2
-rw-r--r--activerecord/test/cases/migration/columns_test.rb2
-rw-r--r--activerecord/test/cases/migration/compatibility_test.rb42
-rw-r--r--activerecord/test/cases/migration/foreign_key_test.rb6
-rw-r--r--activerecord/test/cases/migration/index_test.rb12
-rw-r--r--activerecord/test/cases/migration/postgresql_geometric_types_test.rb93
-rw-r--r--activerecord/test/cases/migration_test.rb59
-rw-r--r--activerecord/test/cases/migrator_test.rb2
-rw-r--r--activerecord/test/cases/nested_attributes_test.rb35
-rw-r--r--activerecord/test/cases/persistence_test.rb21
-rw-r--r--activerecord/test/cases/primary_keys_test.rb6
-rw-r--r--activerecord/test/cases/relation/delegation_test.rb8
-rw-r--r--activerecord/test/cases/relation_test.rb7
-rw-r--r--activerecord/test/cases/relations_test.rb7
-rw-r--r--activerecord/test/cases/sanitize_test.rb104
-rw-r--r--activerecord/test/cases/schema_dumper_test.rb44
-rw-r--r--activerecord/test/cases/tasks/mysql_rake_test.rb24
-rw-r--r--activerecord/test/cases/tasks/postgresql_rake_test.rb4
-rw-r--r--activerecord/test/cases/test_case.rb6
-rw-r--r--activerecord/test/cases/time_precision_test.rb34
-rw-r--r--activerecord/test/cases/touch_later_test.rb8
-rw-r--r--activerecord/test/cases/transaction_callbacks_test.rb6
-rw-r--r--activerecord/test/cases/view_test.rb4
-rw-r--r--activerecord/test/config.example.yml9
-rw-r--r--activerecord/test/migrations/10_urban/9_add_expressions.rb2
-rw-r--r--activerecord/test/migrations/decimal/1_give_me_big_numbers.rb2
-rw-r--r--activerecord/test/migrations/magic/1_currencies_have_symbols.rb2
-rw-r--r--activerecord/test/migrations/missing/1000_people_have_middle_names.rb2
-rw-r--r--activerecord/test/migrations/missing/1_people_have_last_names.rb2
-rw-r--r--activerecord/test/migrations/missing/3_we_need_reminders.rb2
-rw-r--r--activerecord/test/migrations/missing/4_innocent_jointable.rb2
-rw-r--r--activerecord/test/migrations/rename/1_we_need_things.rb2
-rw-r--r--activerecord/test/migrations/rename/2_rename_things.rb2
-rw-r--r--activerecord/test/migrations/to_copy/1_people_have_hobbies.rb2
-rw-r--r--activerecord/test/migrations/to_copy/2_people_have_descriptions.rb2
-rw-r--r--activerecord/test/migrations/to_copy2/1_create_articles.rb2
-rw-r--r--activerecord/test/migrations/to_copy2/2_create_comments.rb2
-rw-r--r--activerecord/test/migrations/to_copy_with_name_collision/1_people_have_hobbies.rb2
-rw-r--r--activerecord/test/migrations/to_copy_with_timestamps/20090101010101_people_have_hobbies.rb2
-rw-r--r--activerecord/test/migrations/to_copy_with_timestamps/20090101010202_people_have_descriptions.rb2
-rw-r--r--activerecord/test/migrations/to_copy_with_timestamps2/20090101010101_create_articles.rb2
-rw-r--r--activerecord/test/migrations/to_copy_with_timestamps2/20090101010202_create_comments.rb2
-rw-r--r--activerecord/test/migrations/valid/1_valid_people_have_last_names.rb2
-rw-r--r--activerecord/test/migrations/valid/2_we_need_reminders.rb2
-rw-r--r--activerecord/test/migrations/valid/3_innocent_jointable.rb2
-rw-r--r--activerecord/test/migrations/valid_with_subdirectories/1_valid_people_have_last_names.rb2
-rw-r--r--activerecord/test/migrations/valid_with_subdirectories/sub/2_we_need_reminders.rb2
-rw-r--r--activerecord/test/migrations/valid_with_subdirectories/sub1/3_innocent_jointable.rb2
-rw-r--r--activerecord/test/migrations/valid_with_timestamps/20100101010101_valid_with_timestamps_people_have_last_names.rb2
-rw-r--r--activerecord/test/migrations/valid_with_timestamps/20100201010101_valid_with_timestamps_we_need_reminders.rb2
-rw-r--r--activerecord/test/migrations/valid_with_timestamps/20100301010101_valid_with_timestamps_innocent_jointable.rb2
-rw-r--r--activerecord/test/migrations/version_check/20131219224947_migration_version_check.rb2
-rw-r--r--activerecord/test/models/bulb.rb7
-rw-r--r--activerecord/test/models/car.rb1
-rw-r--r--activerecord/test/schema/mysql_specific_schema.rb62
-rw-r--r--activerecord/test/schema/schema.rb4
-rw-r--r--activesupport/CHANGELOG.md87
-rw-r--r--activesupport/README.rdoc3
-rw-r--r--activesupport/activesupport.gemspec2
-rwxr-xr-xactivesupport/bin/generate_tables5
-rw-r--r--activesupport/lib/active_support.rb2
-rw-r--r--activesupport/lib/active_support/cache.rb41
-rw-r--r--activesupport/lib/active_support/cache/file_store.rb36
-rw-r--r--activesupport/lib/active_support/cache/mem_cache_store.rb67
-rw-r--r--activesupport/lib/active_support/cache/strategy/local_cache.rb13
-rw-r--r--activesupport/lib/active_support/callbacks.rb9
-rw-r--r--activesupport/lib/active_support/core_ext/class/subclasses.rb5
-rw-r--r--activesupport/lib/active_support/core_ext/enumerable.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/module.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb141
-rw-r--r--activesupport/lib/active_support/core_ext/module/qualified_const.rb42
-rw-r--r--activesupport/lib/active_support/core_ext/range/conversions.rb17
-rw-r--r--activesupport/lib/active_support/core_ext/time/calculations.rb1
-rw-r--r--activesupport/lib/active_support/deprecation.rb2
-rw-r--r--activesupport/lib/active_support/evented_file_update_checker.rb (renamed from activesupport/lib/active_support/file_evented_update_checker.rb)17
-rw-r--r--activesupport/lib/active_support/gem_version.rb2
-rw-r--r--activesupport/lib/active_support/logger.rb8
-rw-r--r--activesupport/lib/active_support/logger_silence.rb5
-rw-r--r--activesupport/lib/active_support/message_verifier.rb2
-rw-r--r--activesupport/lib/active_support/notifications/fanout.rb4
-rw-r--r--activesupport/lib/active_support/notifications/instrumenter.rb9
-rw-r--r--activesupport/lib/active_support/ordered_hash.rb2
-rw-r--r--activesupport/lib/active_support/per_thread_registry.rb5
-rw-r--r--activesupport/lib/active_support/values/time_zone.rb3
-rw-r--r--activesupport/test/broadcast_logger_test.rb50
-rw-r--r--activesupport/test/caching_test.rb65
-rw-r--r--activesupport/test/callbacks_test.rb18
-rw-r--r--activesupport/test/core_ext/module/attribute_accessor_per_thread_test.rb109
-rw-r--r--activesupport/test/core_ext/module/qualified_const_test.rb130
-rw-r--r--activesupport/test/deprecation_test.rb6
-rw-r--r--activesupport/test/evented_file_update_checker_test.rb (renamed from activesupport/test/file_evented_update_checker_test.rb)13
-rw-r--r--activesupport/test/file_update_checker_shared_tests.rb1
-rw-r--r--activesupport/test/multibyte_conformance_test.rb5
-rw-r--r--activesupport/test/notifications_test.rb15
-rwxr-xr-xci/travis.rb19
-rw-r--r--guides/CHANGELOG.md5
-rw-r--r--guides/rails_guides/generator.rb2
-rw-r--r--guides/rails_guides/kindle.rb2
-rw-r--r--guides/source/action_controller_overview.md4
-rw-r--r--guides/source/action_mailer_basics.md2
-rw-r--r--guides/source/action_view_overview.md16
-rw-r--r--guides/source/active_model_basics.md2
-rw-r--r--guides/source/active_record_basics.md21
-rw-r--r--guides/source/active_record_callbacks.md51
-rw-r--r--guides/source/active_record_migrations.md68
-rw-r--r--guides/source/active_record_postgresql.md30
-rw-r--r--guides/source/active_record_querying.md87
-rw-r--r--guides/source/active_record_validations.md137
-rw-r--r--guides/source/active_support_core_extensions.md28
-rw-r--r--guides/source/api_app.md14
-rw-r--r--guides/source/api_documentation_guidelines.md2
-rw-r--r--guides/source/asset_pipeline.md8
-rw-r--r--guides/source/association_basics.md260
-rw-r--r--guides/source/autoloading_and_reloading_constants.md10
-rw-r--r--guides/source/caching_with_rails.md6
-rw-r--r--guides/source/configuring.md14
-rw-r--r--guides/source/contributing_to_ruby_on_rails.md38
-rw-r--r--guides/source/debugging_rails_applications.md6
-rw-r--r--guides/source/engines.md18
-rw-r--r--guides/source/form_helpers.md8
-rw-r--r--guides/source/getting_started.md25
-rw-r--r--guides/source/i18n.md2
-rw-r--r--guides/source/initialization.md12
-rw-r--r--guides/source/layouts_and_rendering.md7
-rw-r--r--guides/source/nested_model_forms.md6
-rw-r--r--guides/source/plugins.md37
-rw-r--r--guides/source/routing.md10
-rw-r--r--guides/source/security.md6
-rw-r--r--guides/source/testing.md76
-rw-r--r--guides/source/upgrading_ruby_on_rails.md21
-rw-r--r--guides/source/working_with_javascript_in_rails.md4
-rw-r--r--rails.gemspec1
-rw-r--r--railties/CHANGELOG.md55
-rw-r--r--railties/Rakefile29
-rw-r--r--railties/lib/rails/all.rb19
-rw-r--r--railties/lib/rails/api/task.rb7
-rw-r--r--railties/lib/rails/application.rb6
-rw-r--r--railties/lib/rails/application/configuration.rb102
-rw-r--r--railties/lib/rails/application/default_middleware_stack.rb4
-rw-r--r--railties/lib/rails/command.rb70
-rw-r--r--railties/lib/rails/commands.rb7
-rw-r--r--railties/lib/rails/commands/commands_tasks.rb43
-rw-r--r--railties/lib/rails/commands/dbconsole.rb2
-rw-r--r--railties/lib/rails/commands/dev_cache.rb21
-rw-r--r--railties/lib/rails/commands/rake_proxy.rb34
-rw-r--r--railties/lib/rails/gem_version.rb2
-rw-r--r--railties/lib/rails/generators.rb1
-rw-r--r--railties/lib/rails/generators/actions/create_migration.rb2
-rw-r--r--railties/lib/rails/generators/app_base.rb56
-rw-r--r--railties/lib/rails/generators/erb/mailer/mailer_generator.rb7
-rw-r--r--railties/lib/rails/generators/erb/mailer/templates/layout.html.erb5
-rw-r--r--railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb6
-rw-r--r--railties/lib/rails/generators/named_base.rb12
-rw-r--r--railties/lib/rails/generators/rails/app/USAGE1
-rw-r--r--railties/lib/rails/generators/rails/app/app_generator.rb19
-rw-r--r--railties/lib/rails/generators/rails/app/templates/Gemfile15
-rw-r--r--railties/lib/rails/generators/rails/app/templates/app/assets/config/manifest.js.tt1
-rw-r--r--railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/cable.coffee11
-rw-r--r--railties/lib/rails/generators/rails/app/templates/app/channels/application_cable/channel.rb5
-rw-r--r--railties/lib/rails/generators/rails/app/templates/app/channels/application_cable/connection.rb5
-rw-r--r--railties/lib/rails/generators/rails/app/templates/app/mailers/application_mailer.rb (renamed from actionmailer/lib/rails/generators/mailer/templates/application_mailer.rb)2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/app/models/application_record.rb3
-rw-r--r--railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt8
-rw-r--r--railties/lib/rails/generators/rails/app/templates/app/views/layouts/mailer.html.erb.tt13
-rw-r--r--railties/lib/rails/generators/rails/app/templates/app/views/layouts/mailer.text.erb.tt (renamed from railties/lib/rails/generators/erb/mailer/templates/layout.text.erb)0
-rw-r--r--railties/lib/rails/generators/rails/app/templates/bin/setup6
-rw-r--r--railties/lib/rails/generators/rails/app/templates/bin/update6
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config.ru4
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config.ru.tt11
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/application.rb9
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt7
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt6
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/initializers/active_record_belongs_to_required_by_default.rb3
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/initializers/application_controller_renderer.rb4
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/initializers/callback_terminator.rb3
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/initializers/cookies_serializer.rb2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/initializers/request_forgery_protection.rb4
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/redis/cable.yml9
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/routes.rb3
-rw-r--r--railties/lib/rails/generators/rails/app/templates/db/seeds.rb.tt6
-rw-r--r--railties/lib/rails/generators/rails/app/templates/gitignore3
-rw-r--r--railties/lib/rails/generators/rails/plugin/plugin_generator.rb7
-rw-r--r--railties/lib/rails/generators/rails/plugin/templates/%name%.gemspec7
-rw-r--r--railties/lib/rails/generators/rails/plugin/templates/Gemfile2
-rw-r--r--railties/lib/rails/generators/rails/plugin/templates/README.md3
-rw-r--r--railties/lib/rails/generators/rails/plugin/templates/README.rdoc3
-rw-r--r--railties/lib/rails/generators/rails/plugin/templates/Rakefile2
-rw-r--r--railties/lib/rails/generators/rails/plugin/templates/app/models/application_record.rb.tt6
-rw-r--r--railties/lib/rails/generators/rails/plugin/templates/bin/test.tt8
-rw-r--r--railties/lib/rails/generators/rails/plugin/templates/rails/routes.rb1
-rw-r--r--railties/lib/rails/generators/rails/plugin/templates/test/test_helper.rb4
-rw-r--r--railties/lib/rails/generators/rails/scaffold/templates/scaffold.css4
-rw-r--r--railties/lib/rails/generators/rails/scaffold_controller/templates/api_controller.rb2
-rw-r--r--railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb2
-rw-r--r--railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb8
-rw-r--r--railties/lib/rails/generators/test_unit/scaffold/templates/api_functional_test.rb19
-rw-r--r--railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb23
-rw-r--r--railties/lib/rails/tasks.rb1
-rw-r--r--railties/lib/rails/tasks/dev.rake15
-rw-r--r--railties/lib/rails/test_unit/minitest_plugin.rb11
-rw-r--r--railties/lib/rails/test_unit/reporter.rb6
-rw-r--r--railties/test/application/asset_debugging_test.rb5
-rw-r--r--railties/test/application/assets_test.rb8
-rw-r--r--railties/test/application/configuration_test.rb59
-rw-r--r--railties/test/application/loading_test.rb6
-rw-r--r--railties/test/application/middleware/static_test.rb8
-rw-r--r--railties/test/application/rake/dbs_test.rb8
-rw-r--r--railties/test/application/rake/dev_test.rb35
-rw-r--r--railties/test/application/rake/migrations_test.rb6
-rw-r--r--railties/test/application/rake_test.rb8
-rw-r--r--railties/test/commands/dbconsole_test.rb6
-rw-r--r--railties/test/commands/dev_cache_test.rb32
-rw-r--r--railties/test/generators/actions_test.rb9
-rw-r--r--railties/test/generators/api_app_generator_test.rb4
-rw-r--r--railties/test/generators/app_generator_test.rb12
-rw-r--r--railties/test/generators/generator_test.rb15
-rw-r--r--railties/test/generators/mailer_generator_test.rb23
-rw-r--r--railties/test/generators/migration_generator_test.rb4
-rw-r--r--railties/test/generators/model_generator_test.rb27
-rw-r--r--railties/test/generators/namespaced_generators_test.rb16
-rw-r--r--railties/test/generators/plugin_generator_test.rb21
-rw-r--r--railties/test/generators/plugin_test_helper.rb24
-rw-r--r--railties/test/generators/plugin_test_runner_test.rb104
-rw-r--r--railties/test/generators/resource_generator_test.rb2
-rw-r--r--railties/test/generators/scaffold_controller_generator_test.rb20
-rw-r--r--railties/test/generators/scaffold_generator_test.rb20
-rw-r--r--railties/test/generators/shared_generator_tests.rb3
-rw-r--r--railties/test/generators/test_runner_in_engine_test.rb31
-rw-r--r--railties/test/railties/engine_test.rb18
-rw-r--r--tasks/release.rb6
-rw-r--r--version.rb2
507 files changed, 8740 insertions, 4139 deletions
diff --git a/.travis.yml b/.travis.yml
index 46be91d18e..f1031a3750 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -16,19 +16,18 @@ env:
matrix:
- "GEM=railties"
- "GEM=ap"
+ - "GEM=ac"
- "GEM=am,amo,as,av,aj"
- - "GEM=ar:mysql"
- "GEM=ar:mysql2"
- "GEM=ar:sqlite3"
- "GEM=ar:postgresql"
- "GEM=aj:integration"
- "GEM=guides"
rvm:
- - 2.2.3
+ - 2.2.4
- ruby-head
matrix:
allow_failures:
- - env: "GEM=ar:mysql"
- rvm: ruby-head
fast_finish: true
notifications:
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 699b6fd2d1..6871664a22 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,16 +1,42 @@
-Ruby on Rails is a volunteer effort. We encourage you to pitch in. [Join the team](http://contributors.rubyonrails.org)!
+## How to contribute to Ruby on Rails
-* If you want to submit a bug report please make sure to follow our [reporting guidelines](http://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#reporting-an-issue).
+#### **Did you find a bug?**
-* If you want to submit a patch, please read the [Contributing to Ruby on Rails](http://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html) guide.
+* **Ensure the bug was not already reported** by searching on GitHub under [Issues](https://github.com/rails/rails/issues).
-* If you want to contribute to Rails documentation, please read the [Contributing to the Rails Documentation](http://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#contributing-to-the-rails-documentation) section of the aforementioned guide.
+* If unable to find an open issue addressing the problem, [open a new one](https://github.com/rails/rails/issues/new). Be sure to include a **title and clear description**, as much relevant information as possible, and a **code sample** or an **executable test case** demonstrating the expected behavior that is not occurring.
-*We only accept bug reports and pull requests on GitHub*.
+* If possible, use the relevant bug report templates to create the issue. Simply copy the content of the appropriate template into a .rb file, make the necessary changes to demonstrate the issue, and **paste the content into the issue description**:
+ * [**Active Record** (models, database) issues](https://github.com/rails/rails/blob/master/guides/bug_report_templates/active_record_master.rb)
+ * [**Action Pack** (controllers, routing) issues](https://github.com/rails/rails/blob/master/guides/bug_report_templates/action_controller_master.rb)
+ * [**Generic template** for other issues](https://github.com/rails/rails/blob/master/guides/bug_report_templates/generic_master.rb)
-* If you have a question about how to use Ruby on Rails, please [ask it on the rubyonrails-talk mailing list](https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-talk).
+* For more detailed information on submitting a bug report and creating an issue, visit our [reporting guidelines](http://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#reporting-an-issue).
-* If you have a change or new feature in mind, please [suggest it on the rubyonrails-core mailing list](https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core) and start writing code.
+#### **Did you write a patch that fixes a bug?**
+
+* Open a new GitHub pull request with the patch.
+
+* Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable.
+
+* Before submitting, please read the [Contributing to Ruby on Rails](http://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html) guide to know more about coding conventions and benchmarks.
+
+#### **Do you intend to add a new feature or change an existing one?**
+
+* Suggest your change in the [rubyonrails-core mailing list](https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core) and start writing code.
+
+* Do not open an issue on GitHub until you have collected positive feedback about the change. GitHub issues are primarily intended for bug reports and fixes.
+
+#### **Do you have questions about the source code?**
+
+* Ask any question about how to use Ruby on Rails in the [rubyonrails-talk mailing list](https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-talk).
+
+#### **Do you want to contribute to the Rails documentation?**
+
+* Please read [Contributing to the Rails Documentation](http://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#contributing-to-the-rails-documentation).
+
+</br>
+Ruby on Rails is a volunteer effort. We encourage you to pitch in and [join the team](http://contributors.rubyonrails.org)!
Thanks! :heart: :heart: :heart:
diff --git a/Gemfile b/Gemfile
index b9fc37cba2..51e7c0043c 100644
--- a/Gemfile
+++ b/Gemfile
@@ -5,29 +5,25 @@ gemspec
# We need a newish Rake since Active Job sets its test tasks' descriptions.
gem 'rake', '>= 10.3'
-# Active Job depends on URI::GID::MissingModelIDError, which isn't released yet.
-gem 'globalid', github: 'rails/globalid', branch: 'master'
-gem 'rack', github: 'rack/rack', branch: 'master'
-
# This needs to be with require false to ensure correct loading order, as has to
# be loaded after loading the test library.
gem 'mocha', '~> 0.14', require: false
gem 'rack-cache', '~> 1.2'
-gem 'jquery-rails', github: 'rails/jquery-rails', branch: 'master'
+gem 'jquery-rails'
gem 'coffee-rails', '~> 4.1.0'
-gem 'turbolinks', github: 'rails/turbolinks', branch: 'master'
-gem 'arel', github: 'rails/arel', branch: 'master'
-gem 'mail', github: 'mikel/mail', branch: 'master'
-
-gem 'sprockets', '~> 4.0', github: 'rails/sprockets', branch: 'master'
-gem 'sprockets-rails', '~> 3.0.0.beta3', github: 'rails/sprockets-rails', branch: 'master'
-gem 'sass-rails', github: 'rails/sass-rails', branch: 'master'
+gem 'turbolinks'
# require: false so bcrypt is loaded only when has_secure_password is used.
# This is to avoid Active Model (and by extension the entire framework)
# being dependent on a binary library.
-gem 'bcrypt', '~> 3.1.10', require: false
+platforms :mingw, :x64_mingw, :mswin, :mswin64 do
+ gem 'bcrypt-ruby', '~> 3.0.0', require: false
+end
+
+platforms :ruby, :jruby, :rbx do
+ gem 'bcrypt', '~> 3.1.10', require: false
+end
# This needs to be with require false to avoid it being automatically loaded by
# sprockets.
@@ -45,7 +41,7 @@ end
# Active Support.
gem 'dalli', '>= 2.2.1'
-gem 'listen', '~> 3.0.4'
+gem 'listen', '~> 3.0.5', require: false
# Active Job.
group :job do
@@ -64,6 +60,11 @@ group :job do
gem 'sequel', require: false
end
+# Action Cable
+group :cable do
+ gem 'puma', require: false
+end
+
# Add your own local bundler stuff.
local_gemfile = File.dirname(__FILE__) + "/.Gemfile"
instance_eval File.read local_gemfile if File.exist? local_gemfile
@@ -80,8 +81,8 @@ group :test do
gem 'benchmark-ips'
end
-platforms :ruby do
- gem 'nokogiri', '>= 1.6.7.rc3'
+platforms :ruby, :mswin, :mswin64, :mingw, :x64_mingw do
+ gem 'nokogiri', '>= 1.6.7.1'
# Needed for compiling the ActionDispatch::Journey parser.
gem 'racc', '>=1.4.6', require: false
@@ -91,7 +92,6 @@ platforms :ruby do
group :db do
gem 'pg', '>= 0.18.0'
- gem 'mysql', '>= 2.9.0'
gem 'mysql2', '>= 0.4.0'
end
end
diff --git a/Gemfile.lock b/Gemfile.lock
index 0f5a48e524..4e8c1e1744 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -20,143 +20,74 @@ GIT
redis-namespace
GIT
- remote: git://github.com/mikel/mail.git
- revision: 9c313a401729b9aa9177878836829a61adf67b54
- branch: master
- specs:
- mail (2.6.3.edge)
- mime-types (>= 1.16, < 3)
-
-GIT
- remote: git://github.com/rack/rack.git
- revision: 35599cfc2751e0ee611c0ff799924b8e7fe0c0b4
- branch: master
- specs:
- rack (2.0.0.alpha)
- json
-
-GIT
- remote: git://github.com/rails/arel.git
- revision: 3c429c5d86e9e2201c2a35d934ca6a8911c18e69
- branch: master
- specs:
- arel (7.0.0.alpha)
-
-GIT
- remote: git://github.com/rails/globalid.git
- revision: 1d8fca667740570d204fd955a0bd39ac539bac7f
- branch: master
- specs:
- globalid (0.3.6)
- activesupport (>= 4.1.0)
-
-GIT
- remote: git://github.com/rails/jquery-rails.git
- revision: 04fcfa29b859eef9479f89b6a799d00212902385
- branch: master
- specs:
- jquery-rails (4.0.5)
- rails-dom-testing (~> 1.0)
- railties (>= 4.2.0)
- thor (>= 0.14, < 2.0)
-
-GIT
- remote: git://github.com/rails/sass-rails.git
- revision: 6e4eee736bcbfa5b2962467673c7a51abf434c67
- branch: master
- specs:
- sass-rails (6.0.0)
- railties (>= 4.0.0, < 5.0)
- sass (~> 3.4)
- sprockets (>= 4.0)
- sprockets-rails (< 4.0)
-
-GIT
- remote: git://github.com/rails/sprockets-rails.git
- revision: 93a45b1c463a063ec7cf4d160107b67aa3db7a1a
- branch: master
- specs:
- sprockets-rails (3.0.0.beta3)
- actionpack (>= 4.0)
- activesupport (>= 4.0)
- sprockets (>= 3.0.0)
-
-GIT
- remote: git://github.com/rails/sprockets.git
- revision: 5a77f8b007b8ec61edd783c48baf9d971f1c684d
- branch: master
- specs:
- sprockets (4.0.0)
- rack (>= 1, < 3)
-
-GIT
- remote: git://github.com/rails/turbolinks.git
- revision: 83d4b3d2c52a681f07900c28adb28bc8da604733
- branch: master
- specs:
- turbolinks (3.0.0)
- coffee-rails
-
-GIT
remote: git://github.com/sass/sass.git
- revision: 4e3e1d5684cc29073a507578fc977434ff488c93
+ revision: bce9509f396225d721501ea1070a6871b708abb1
branch: stable
specs:
- sass (3.4.19)
+ sass (3.4.20)
PATH
remote: .
specs:
- actionmailer (5.0.0.alpha)
- actionpack (= 5.0.0.alpha)
- actionview (= 5.0.0.alpha)
- activejob (= 5.0.0.alpha)
+ actioncable (5.0.0.beta1)
+ actionpack (= 5.0.0.beta1)
+ celluloid (~> 0.17.2)
+ coffee-rails (~> 4.1.0)
+ em-hiredis (~> 0.3.0)
+ faye-websocket (~> 0.10.0)
+ redis (~> 3.0)
+ websocket-driver (~> 0.6.1)
+ actionmailer (5.0.0.beta1)
+ actionpack (= 5.0.0.beta1)
+ actionview (= 5.0.0.beta1)
+ activejob (= 5.0.0.beta1)
mail (~> 2.5, >= 2.5.4)
rails-dom-testing (~> 1.0, >= 1.0.5)
- actionpack (5.0.0.alpha)
- actionview (= 5.0.0.alpha)
- activesupport (= 5.0.0.alpha)
+ actionpack (5.0.0.beta1)
+ actionview (= 5.0.0.beta1)
+ activesupport (= 5.0.0.beta1)
rack (~> 2.x)
rack-test (~> 0.6.3)
rails-dom-testing (~> 1.0, >= 1.0.5)
rails-html-sanitizer (~> 1.0, >= 1.0.2)
- actionview (5.0.0.alpha)
- activesupport (= 5.0.0.alpha)
+ actionview (5.0.0.beta1)
+ activesupport (= 5.0.0.beta1)
builder (~> 3.1)
erubis (~> 2.7.0)
rails-dom-testing (~> 1.0, >= 1.0.5)
rails-html-sanitizer (~> 1.0, >= 1.0.2)
- activejob (5.0.0.alpha)
- activesupport (= 5.0.0.alpha)
- globalid (>= 0.3.0)
- activemodel (5.0.0.alpha)
- activesupport (= 5.0.0.alpha)
+ activejob (5.0.0.beta1)
+ activesupport (= 5.0.0.beta1)
+ globalid (>= 0.3.6)
+ activemodel (5.0.0.beta1)
+ activesupport (= 5.0.0.beta1)
builder (~> 3.1)
- activerecord (5.0.0.alpha)
- activemodel (= 5.0.0.alpha)
- activesupport (= 5.0.0.alpha)
- arel (= 7.0.0.alpha)
- activesupport (5.0.0.alpha)
- concurrent-ruby (~> 1.0.0.pre5, < 2.0.0)
+ activerecord (5.0.0.beta1)
+ activemodel (= 5.0.0.beta1)
+ activesupport (= 5.0.0.beta1)
+ arel (~> 7.0)
+ activesupport (5.0.0.beta1)
+ concurrent-ruby (~> 1.0)
i18n (~> 0.7)
json (~> 1.7, >= 1.7.7)
method_source
minitest (~> 5.1)
tzinfo (~> 1.1)
- rails (5.0.0.alpha)
- actionmailer (= 5.0.0.alpha)
- actionpack (= 5.0.0.alpha)
- actionview (= 5.0.0.alpha)
- activejob (= 5.0.0.alpha)
- activemodel (= 5.0.0.alpha)
- activerecord (= 5.0.0.alpha)
- activesupport (= 5.0.0.alpha)
+ rails (5.0.0.beta1)
+ actioncable (= 5.0.0.beta1)
+ actionmailer (= 5.0.0.beta1)
+ actionpack (= 5.0.0.beta1)
+ actionview (= 5.0.0.beta1)
+ activejob (= 5.0.0.beta1)
+ activemodel (= 5.0.0.beta1)
+ activerecord (= 5.0.0.beta1)
+ activesupport (= 5.0.0.beta1)
bundler (>= 1.3.0, < 2.0)
- railties (= 5.0.0.alpha)
+ railties (= 5.0.0.beta1)
sprockets-rails (>= 2.0.0)
- railties (5.0.0.alpha)
- actionpack (= 5.0.0.alpha)
- activesupport (= 5.0.0.alpha)
+ railties (5.0.0.beta1)
+ actionpack (= 5.0.0.beta1)
+ activesupport (= 5.0.0.beta1)
method_source
rake (>= 0.8.7)
thor (>= 0.18.1, < 2.0)
@@ -165,18 +96,19 @@ GEM
remote: https://rubygems.org/
specs:
amq-protocol (2.0.0)
- backburner (1.1.0)
+ arel (7.0.0)
+ backburner (1.2.0)
beaneater (~> 1.0)
dante (> 0.1.5)
bcrypt (3.1.10)
- bcrypt (3.1.10-x64-mingw32)
- bcrypt (3.1.10-x86-mingw32)
+ bcrypt-ruby (3.0.1)
+ bcrypt-ruby (3.0.1-x86-mingw32)
beaneater (1.0.0)
benchmark-ips (2.3.0)
builder (3.2.2)
- bunny (2.2.0)
+ bunny (2.2.1)
amq-protocol (>= 2.0.0)
- byebug (6.0.2)
+ byebug (8.2.1)
celluloid (0.17.2)
celluloid-essentials
celluloid-extras
@@ -200,52 +132,78 @@ GEM
coffee-script (2.4.1)
coffee-script-source
execjs
- coffee-script-source (1.9.1.1)
- concurrent-ruby (1.0.0.pre5)
+ coffee-script-source (1.10.0)
+ concurrent-ruby (1.0.0)
connection_pool (2.2.0)
- dalli (2.7.4)
+ dalli (2.7.5)
dante (0.2.0)
delayed_job (4.1.1)
activesupport (>= 3.0, < 5.0)
delayed_job_active_record (4.1.0)
activerecord (>= 3.0, < 5)
delayed_job (>= 3.0, < 5)
+ em-hiredis (0.3.0)
+ eventmachine (~> 1.0)
+ hiredis (~> 0.5.0)
erubis (2.7.0)
+ eventmachine (1.0.8)
execjs (2.6.0)
+ faye-websocket (0.10.2)
+ eventmachine (>= 0.12.0)
+ websocket-driver (>= 0.5.1)
ffi (1.9.10)
ffi (1.9.10-x64-mingw32)
ffi (1.9.10-x86-mingw32)
+ globalid (0.3.6)
+ activesupport (>= 4.1.0)
+ hiredis (0.5.2)
hitimes (1.2.3)
hitimes (1.2.3-x86-mingw32)
i18n (0.7.0)
+ jquery-rails (4.0.5)
+ rails-dom-testing (~> 1.0)
+ railties (>= 4.2.0)
+ thor (>= 0.14, < 2.0)
json (1.8.3)
kindlerb (0.1.1)
mustache
nokogiri
- listen (3.0.4)
+ listen (3.0.5)
rb-fsevent (>= 0.9.3)
rb-inotify (>= 0.9)
loofah (2.0.3)
nokogiri (>= 1.5.9)
+ mail (2.6.3)
+ mime-types (>= 1.16, < 3)
metaclass (0.0.4)
method_source (0.8.2)
- mime-types (2.6.2)
- mini_portile (0.7.0.rc4)
+ mime-types (2.99)
+ mini_portile2 (2.0.0)
minitest (5.3.3)
mocha (0.14.0)
metaclass (~> 0.0.1)
mono_logger (1.1.0)
multi_json (1.11.2)
mustache (1.0.2)
- mysql (2.9.1)
- mysql2 (0.4.1)
- nokogiri (1.6.7.rc3)
- mini_portile (~> 0.7.0.rc4)
- pg (0.18.3)
- psych (2.0.15)
+ mysql2 (0.4.2)
+ mysql2 (0.4.2-x64-mingw32)
+ mysql2 (0.4.2-x86-mingw32)
+ nokogiri (1.6.7.1)
+ mini_portile2 (~> 2.0.0.rc2)
+ nokogiri (1.6.7.1-x64-mingw32)
+ mini_portile2 (~> 2.0.0.rc2)
+ nokogiri (1.6.7.1-x86-mingw32)
+ mini_portile2 (~> 2.0.0.rc2)
+ pg (0.18.4)
+ pg (0.18.4-x64-mingw32)
+ pg (0.18.4-x86-mingw32)
+ psych (2.0.16)
+ puma (2.15.3)
que (0.11.2)
- racc (1.4.13)
- rack-cache (1.5.0)
+ racc (1.4.14)
+ rack (2.0.0.alpha)
+ json
+ rack-cache (1.5.1)
rack (>= 0.4)
rack-test (0.6.3)
rack (>= 1.0)
@@ -263,7 +221,7 @@ GEM
ffi (>= 0.5.0)
rdoc (4.2.0)
redcarpet (3.2.3)
- redis (3.2.1)
+ redis (3.2.2)
redis-namespace (1.5.2)
redis (~> 3.0, >= 3.0.4)
resque (1.25.2)
@@ -277,19 +235,18 @@ GEM
redis (~> 3.0)
resque (~> 1.25)
rufus-scheduler (~> 3.0)
- rufus-scheduler (3.1.7)
+ rufus-scheduler (3.1.10)
sdoc (0.4.1)
json (~> 1.7, >= 1.7.7)
rdoc (~> 4.0)
- sequel (4.27.0)
+ sequel (4.29.0)
serverengine (1.5.11)
sigdump (~> 0.2.2)
- sidekiq (3.5.1)
- celluloid (~> 0.17.2)
+ sidekiq (4.0.1)
+ concurrent-ruby (~> 1.0)
connection_pool (~> 2.2, >= 2.2.0)
json (~> 1.0)
redis (~> 3.2, >= 3.2.1)
- redis-namespace (~> 1.5, >= 1.5.2)
sigdump (0.2.3)
sinatra (1.0)
rack (>= 1.0)
@@ -298,7 +255,16 @@ GEM
serverengine (~> 1.5.11)
thor
thread (~> 0.1.7)
+ sprockets (3.5.2)
+ concurrent-ruby (~> 1.0)
+ rack (> 1, < 3)
+ sprockets-rails (3.0.0)
+ actionpack (>= 4.0)
+ activesupport (>= 4.0)
+ sprockets (>= 3.0.0)
sqlite3 (1.3.11)
+ sqlite3 (1.3.11-x64-mingw32)
+ sqlite3 (1.3.11-x86-mingw32)
stackprof (0.2.7)
sucker_punch (1.6.0)
celluloid (~> 0.17.2)
@@ -307,6 +273,8 @@ GEM
thread_safe (0.3.5)
timers (4.1.1)
hitimes
+ turbolinks (2.5.3)
+ coffee-rails
tzinfo (1.2.2)
thread_safe (~> 0.1)
tzinfo-data (1.2015.7)
@@ -319,6 +287,9 @@ GEM
w3c_validators (1.2)
json
nokogiri
+ websocket-driver (0.6.3)
+ websocket-extensions (>= 0.1.0)
+ websocket-extensions (0.1.2)
PLATFORMS
ruby
@@ -329,34 +300,31 @@ DEPENDENCIES
activerecord-jdbcmysql-adapter (>= 1.3.0)
activerecord-jdbcpostgresql-adapter (>= 1.3.0)
activerecord-jdbcsqlite3-adapter (>= 1.3.0)
- arel!
backburner
bcrypt (~> 3.1.10)
+ bcrypt-ruby (~> 3.0.0)
benchmark-ips
byebug
coffee-rails (~> 4.1.0)
dalli (>= 2.2.1)
delayed_job
delayed_job_active_record
- globalid!
- jquery-rails!
+ jquery-rails
json
kindlerb (= 0.1.1)
- listen (~> 3.0.4)
- mail!
+ listen (~> 3.0.5)
minitest (< 5.3.4)
mocha (~> 0.14)
- mysql (>= 2.9.0)
mysql2 (>= 0.4.0)
- nokogiri (>= 1.6.7.rc3)
+ nokogiri (>= 1.6.7.1)
pg (>= 0.18.0)
psych (~> 2.0)
+ puma
qu-rails!
qu-redis
que
queue_classic!
racc (>= 1.4.6)
- rack!
rack-cache (~> 1.2)
rails!
rake (>= 10.3)
@@ -364,20 +332,17 @@ DEPENDENCIES
resque
resque-scheduler
sass!
- sass-rails!
sdoc (~> 0.4.0)
sequel
sidekiq
sneakers
- sprockets (~> 4.0)!
- sprockets-rails (~> 3.0.0.beta3)!
sqlite3 (~> 1.3.6)
stackprof
sucker_punch
- turbolinks!
+ turbolinks
tzinfo-data
uglifier (>= 1.3.0)
w3c_validators
BUNDLED WITH
- 1.10.6
+ 1.11.2
diff --git a/RAILS_VERSION b/RAILS_VERSION
index 2b915d7d5c..80bb1e4be2 100644
--- a/RAILS_VERSION
+++ b/RAILS_VERSION
@@ -1 +1 @@
-5.0.0.alpha
+5.0.0.beta1
diff --git a/README.md b/README.md
index f823a49f7d..b4f32940fc 100644
--- a/README.md
+++ b/README.md
@@ -38,7 +38,9 @@ Active Record, Active Model, Action Pack, and Action View can each be used indep
In addition to them, Rails also comes with Action Mailer ([README](actionmailer/README.rdoc)), a library
to generate and send emails; Active Job ([README](activejob/README.md)), a
framework for declaring jobs and making them run on a variety of queueing
-backends; and Active Support ([README](activesupport/README.rdoc)), a collection
+backends; Action Cable ([README](actioncable/README.md)), a framework to
+integrate WebSockets with a Rails application;
+and Active Support ([README](activesupport/README.rdoc)), a collection
of utility classes and standard library extensions that are useful for Rails,
and may also be used independently outside Rails.
@@ -46,18 +48,18 @@ and may also be used independently outside Rails.
1. Install Rails at the command prompt if you haven't yet:
- gem install rails
+ $ gem install rails
2. At the command prompt, create a new Rails application:
- rails new myapp
+ $ rails new myapp
where "myapp" is the application name.
3. Change directory to `myapp` and start the web server:
- cd myapp
- rails server
+ $ cd myapp
+ $ rails server
Run with `--help` or `-h` for options.
diff --git a/Rakefile b/Rakefile
index 2ec39a1c85..b4517e2545 100644
--- a/Rakefile
+++ b/Rakefile
@@ -7,11 +7,12 @@ require 'railties/lib/rails/api/task'
desc "Build gem files for all projects"
task :build => "all:build"
+desc "Prepare the release"
+task :prep_release => "all:prep_release"
+
desc "Release all gems to rubygems and create a tag"
task :release => "all:release"
-PROJECTS = %w(activesupport activemodel actionpack actionview actionmailer activerecord railties activejob)
-
desc 'Run all tests by default'
task :default => %w(test test:isolated)
@@ -19,7 +20,7 @@ task :default => %w(test test:isolated)
desc "Run #{task_name} task for all projects"
task task_name do
errors = []
- PROJECTS.each do |project|
+ FRAMEWORKS.each do |project|
system(%(cd #{project} && #{$0} #{task_name})) || errors << project
end
fail("Errors in #{errors.join(', ')}") unless errors.empty?
@@ -28,7 +29,7 @@ end
desc "Smoke-test all projects"
task :smoke do
- (PROJECTS - %w(activerecord)).each do |project|
+ (FRAMEWORKS - %w(activerecord)).each do |project|
system %(cd #{project} && #{$0} test:isolated)
end
system %(cd activerecord && #{$0} sqlite3:isolated_test)
diff --git a/actioncable/CHANGELOG.md b/actioncable/CHANGELOG.md
new file mode 100644
index 0000000000..64aea88588
--- /dev/null
+++ b/actioncable/CHANGELOG.md
@@ -0,0 +1,8 @@
+## Rails 5.0.0.beta1 (December 18, 2015) ##
+
+* No changes.
+
+
+* Added to Rails!
+
+ *DHH* \ No newline at end of file
diff --git a/actioncable/MIT-LICENSE b/actioncable/MIT-LICENSE
new file mode 100644
index 0000000000..a4910677eb
--- /dev/null
+++ b/actioncable/MIT-LICENSE
@@ -0,0 +1,20 @@
+Copyright (c) 2015 Basecamp, LLC
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/actioncable/README.md b/actioncable/README.md
new file mode 100644
index 0000000000..32f49c215f
--- /dev/null
+++ b/actioncable/README.md
@@ -0,0 +1,457 @@
+# Action Cable –- Integrated WebSockets for Rails
+
+Action Cable seamlessly integrates WebSockets with the rest of your Rails application.
+It allows for real-time features to be written in Ruby in the same style
+and form as the rest of your Rails application, while still being performant
+and scalable. It's a full-stack offering that provides both a client-side
+JavaScript framework and a server-side Ruby framework. You have access to your full
+domain model written with Active Record or your ORM of choice.
+
+
+## Terminology
+
+A single Action Cable server can handle multiple connection instances. It has one
+connection instance per WebSocket connection. A single user may have multiple
+WebSockets open to your application if they use multiple browser tabs or devices.
+The client of a WebSocket connection is called the consumer.
+
+Each consumer can in turn subscribe to multiple cable channels. Each channel encapsulates
+a logical unit of work, similar to what a controller does in a regular MVC setup. For example,
+you could have a `ChatChannel` and a `AppearancesChannel`, and a consumer could be subscribed to either
+or to both of these channels. At the very least, a consumer should be subscribed to one channel.
+
+When the consumer is subscribed to a channel, they act as a subscriber. The connection between
+the subscriber and the channel is, surprise-surprise, called a subscription. A consumer
+can act as a subscriber to a given channel any number of times. For example, a consumer
+could subscribe to multiple chat rooms at the same time. (And remember that a physical user may
+have multiple consumers, one per tab/device open to your connection).
+
+Each channel can then again be streaming zero or more broadcastings. A broadcasting is a
+pubsub link where anything transmitted by the broadcaster is sent directly to the channel
+subscribers who are streaming that named broadcasting.
+
+As you can see, this is a fairly deep architectural stack. There's a lot of new terminology
+to identify the new pieces, and on top of that, you're dealing with both client and server side
+reflections of each unit.
+
+## Examples
+
+### A full-stack example
+
+The first thing you must do is define your `ApplicationCable::Connection` class in Ruby. This
+is the place where you authorize the incoming connection, and proceed to establish it
+if all is well. Here's the simplest example starting with the server-side connection class:
+
+```ruby
+# app/channels/application_cable/connection.rb
+module ApplicationCable
+ class Connection < ActionCable::Connection::Base
+ identified_by :current_user
+
+ def connect
+ self.current_user = find_verified_user
+ end
+
+ protected
+ def find_verified_user
+ if current_user = User.find_by(id: cookies.signed[:user_id])
+ current_user
+ else
+ reject_unauthorized_connection
+ end
+ end
+ end
+end
+```
+Here `identified_by` is a connection identifier that can be used to find the specific connection again or later.
+Note that anything marked as an identifier will automatically create a delegate by the same name on any channel instances created off the connection.
+
+Then you should define your `ApplicationCable::Channel` class in Ruby. This is the place where you put
+shared logic between your channels.
+
+```ruby
+# app/channels/application_cable/channel.rb
+module ApplicationCable
+ class Channel < ActionCable::Channel::Base
+ end
+end
+```
+
+This relies on the fact that you will already have handled authentication of the user, and
+that a successful authentication sets a signed cookie with the `user_id`. This cookie is then
+automatically sent to the connection instance when a new connection is attempted, and you
+use that to set the `current_user`. By identifying the connection by this same current_user,
+you're also ensuring that you can later retrieve all open connections by a given user (and
+potentially disconnect them all if the user is deleted or deauthorized).
+
+The client-side needs to setup a consumer instance of this connection. That's done like so:
+
+```coffeescript
+# app/assets/javascripts/cable.coffee
+#= require action_cable
+
+@App = {}
+App.cable = ActionCable.createConsumer("ws://cable.example.com")
+```
+
+The ws://cable.example.com address must point to your set of Action Cable servers, and it
+must share a cookie namespace with the rest of the application (which may live under http://example.com).
+This ensures that the signed cookie will be correctly sent.
+
+That's all you need to establish the connection! But of course, this isn't very useful in
+itself. This just gives you the plumbing. To make stuff happen, you need content. That content
+is defined by declaring channels on the server and allowing the consumer to subscribe to them.
+
+
+### Channel example 1: User appearances
+
+Here's a simple example of a channel that tracks whether a user is online or not and what page they're on.
+(This is useful for creating presence features like showing a green dot next to a user name if they're online).
+
+First you declare the server-side channel:
+
+```ruby
+# app/channels/appearance_channel.rb
+class AppearanceChannel < ApplicationCable::Channel
+ def subscribed
+ current_user.appear
+ end
+
+ def unsubscribed
+ current_user.disappear
+ end
+
+ def appear(data)
+ current_user.appear on: data['appearing_on']
+ end
+
+ def away
+ current_user.away
+ end
+end
+```
+
+The `#subscribed` callback is invoked when, as we'll show below, a client-side subscription is initiated. In this case,
+we take that opportunity to say "the current user has indeed appeared". That appear/disappear API could be backed by
+Redis or a database or whatever else. Here's what the client-side of that looks like:
+
+```coffeescript
+# app/assets/javascripts/cable/subscriptions/appearance.coffee
+App.cable.subscriptions.create "AppearanceChannel",
+ # Called when the subscription is ready for use on the server
+ connected: ->
+ @install()
+ @appear()
+
+ # Called when the WebSocket connection is closed
+ disconnected: ->
+ @uninstall()
+
+ # Called when the subscription is rejected by the server
+ rejected: ->
+ @uninstall()
+
+ appear: ->
+ # Calls `AppearanceChannel#appear(data)` on the server
+ @perform("appear", appearing_on: $("main").data("appearing-on"))
+
+ away: ->
+ # Calls `AppearanceChannel#away` on the server
+ @perform("away")
+
+
+ buttonSelector = "[data-behavior~=appear_away]"
+
+ install: ->
+ $(document).on "page:change.appearance", =>
+ @appear()
+
+ $(document).on "click.appearance", buttonSelector, =>
+ @away()
+ false
+
+ $(buttonSelector).show()
+
+ uninstall: ->
+ $(document).off(".appearance")
+ $(buttonSelector).hide()
+```
+
+Simply calling `App.cable.subscriptions.create` will setup the subscription, which will call `AppearanceChannel#subscribed`,
+which in turn is linked to original `App.cable` -> `ApplicationCable::Connection` instances.
+
+We then link the client-side `appear` method to `AppearanceChannel#appear(data)`. This is possible because the server-side
+channel instance will automatically expose the public methods declared on the class (minus the callbacks), so that these
+can be reached as remote procedure calls via a subscription's `perform` method.
+
+### Channel example 2: Receiving new web notifications
+
+The appearance example was all about exposing server functionality to client-side invocation over the WebSocket connection.
+But the great thing about WebSockets is that it's a two-way street. So now let's show an example where the server invokes
+action on the client.
+
+This is a web notification channel that allows you to trigger client-side web notifications when you broadcast to the right
+streams:
+
+```ruby
+# app/channels/web_notifications_channel.rb
+class WebNotificationsChannel < ApplicationCable::Channel
+ def subscribed
+ stream_from "web_notifications_#{current_user.id}"
+ end
+end
+```
+
+```coffeescript
+# Client-side, which assumes you've already requested the right to send web notifications
+App.cable.subscriptions.create "WebNotificationsChannel",
+ received: (data) ->
+ new Notification data["title"], body: data["body"]
+```
+
+```ruby
+# Somewhere in your app this is called, perhaps from a NewCommentJob
+ActionCable.server.broadcast \
+ "web_notifications_#{current_user.id}", { title: 'New things!', body: 'All the news that is fit to print' }
+```
+
+The `ActionCable.server.broadcast` call places a message in the Redis' pubsub queue under a separate broadcasting name for each user. For a user with an ID of 1, the broadcasting name would be `web_notifications_1`.
+The channel has been instructed to stream everything that arrives at `web_notifications_1` directly to the client by invoking the
+`#received(data)` callback. The data is the hash sent as the second parameter to the server-side broadcast call, JSON encoded for the trip
+across the wire, and unpacked for the data argument arriving to `#received`.
+
+
+### Passing Parameters to Channel
+
+You can pass parameters from the client side to the server side when creating a subscription. For example:
+
+```ruby
+# app/channels/chat_channel.rb
+class ChatChannel < ApplicationCable::Channel
+ def subscribed
+ stream_from "chat_#{params[:room]}"
+ end
+end
+```
+
+Pass an object as the first argument to `subscriptions.create`, and that object will become your params hash in your cable channel. The keyword `channel` is required.
+
+```coffeescript
+# Client-side, which assumes you've already requested the right to send web notifications
+App.cable.subscriptions.create { channel: "ChatChannel", room: "Best Room" },
+ received: (data) ->
+ @appendLine(data)
+
+ appendLine: (data) ->
+ html = @createLine(data)
+ $("[data-chat-room='Best Room']").append(html)
+
+ createLine: (data) ->
+ """
+ <article class="chat-line">
+ <span class="speaker">#{data["sent_by"]}</span>
+ <span class="body">#{data["body"]}</span>
+ </article>
+ """
+```
+
+```ruby
+# Somewhere in your app this is called, perhaps from a NewCommentJob
+ActionCable.server.broadcast \
+ "chat_#{room}", { sent_by: 'Paul', body: 'This is a cool chat app.' }
+```
+
+
+### Rebroadcasting message
+
+A common use case is to rebroadcast a message sent by one client to any other connected clients.
+
+```ruby
+# app/channels/chat_channel.rb
+class ChatChannel < ApplicationCable::Channel
+ def subscribed
+ stream_from "chat_#{params[:room]}"
+ end
+
+ def receive(data)
+ ActionCable.server.broadcast "chat_#{params[:room]}", data
+ end
+end
+```
+
+```coffeescript
+# Client-side, which assumes you've already requested the right to send web notifications
+App.chatChannel = App.cable.subscriptions.create { channel: "ChatChannel", room: "Best Room" },
+ received: (data) ->
+ # data => { sent_by: "Paul", body: "This is a cool chat app." }
+
+App.chatChannel.send({ sent_by: "Paul", body: "This is a cool chat app." })
+```
+
+The rebroadcast will be received by all connected clients, _including_ the client that sent the message. Note that params are the same as they were when you subscribed to the channel.
+
+
+### More complete examples
+
+See the [rails/actioncable-examples](http://github.com/rails/actioncable-examples) repository for a full example of how to setup Action Cable in a Rails app and adding channels.
+
+
+## Configuration
+
+Action Cable has two required configurations: the Redis connection and specifying allowed request origins.
+
+### Redis
+
+By default, `ActionCable::Server::Base` will look for a configuration file in `Rails.root.join('config/redis/cable.yml')`. The file must follow the following format:
+
+```yaml
+production: &production
+ url: redis://10.10.3.153:6381
+development: &development
+ url: redis://localhost:6379
+test: *development
+```
+
+This format allows you to specify one configuration per Rails environment. You can also change the location of the Redis config file in
+a Rails initializer with something like:
+
+```ruby
+Rails.application.paths.add "config/redis/cable", with: "somewhere/else/cable.yml"
+```
+
+### Allowed Request Origins
+
+Action Cable will only accept requests from specified origins, which are passed to the server config as an array. The origins can be instances of strings or regular expressions, against which a check for match will be performed.
+
+```ruby
+ActionCable.server.config.allowed_request_origins = ['http://rubyonrails.com', /http:\/\/ruby.*/]
+```
+
+To disable and allow requests from any origin:
+
+```ruby
+ActionCable.server.config.disable_request_forgery_protection = true
+```
+
+By default, Action Cable allows all requests from localhost:3000 when running in the development environment.
+
+### Other Configurations
+
+The other common option to configure is the log tags applied to the per-connection logger. Here's close to what we're using in Basecamp:
+
+```ruby
+ActionCable.server.config.log_tags = [
+ -> request { request.env['bc.account_id'] || "no-account" },
+ :action_cable,
+ -> request { request.uuid }
+]
+```
+
+Your websocket url might change between environments. If you host your production server via https, you will need to use the wss scheme
+for your ActionCable server, but development might remain http and use the ws scheme. You might use localhost in development and your
+domain in production. In any case, to vary the websocket url between environments, add the following configuration to each environment:
+
+```ruby
+config.action_cable.url = "ws://example.com:28080"
+```
+
+Then add the following line to your layout before your JavaScript tag:
+
+```erb
+<%= action_cable_meta_tag %>
+```
+
+And finally, create your consumer like so:
+
+```coffeescript
+App.cable = Cable.createConsumer()
+```
+
+For a full list of all configuration options, see the `ActionCable::Server::Configuration` class.
+
+Also note that your server must provide at least the same number of database connections as you have workers. The default worker pool is set to 100, so that means you have to make at least that available. You can change that in `config/database.yml` through the `pool` attribute.
+
+
+## Running the cable server
+
+### Standalone
+The cable server(s) is separated from your normal application server. It's still a rack application, but it is its own rack
+application. The recommended basic setup is as follows:
+
+```ruby
+# cable/config.ru
+require ::File.expand_path('../../config/environment', __FILE__)
+Rails.application.eager_load!
+
+require 'action_cable/process/logging'
+
+run ActionCable.server
+```
+
+Then you start the server using a binstub in bin/cable ala:
+```
+#!/bin/bash
+bundle exec puma -p 28080 cable/config.ru
+```
+
+The above will start a cable server on port 28080. Remember to point your client-side setup against that using something like:
+`App.cable = ActionCable.createConsumer("ws://basecamp.dev:28080")`.
+
+### In app
+
+If you are using a threaded server like Puma or Thin, the current implementation of ActionCable can run side-along with your Rails application. For example, to listen for WebSocket requests on `/websocket`, match requests on that path:
+
+```ruby
+# config/routes.rb
+Example::Application.routes.draw do
+ match "/websocket", :to => ActionCable.server, via: [:get, :post]
+end
+```
+
+You can use `App.cable = Cable.createConsumer("/websocket")` to connect to the cable server.
+
+For every instance of your server you create and for every worker your server spawns, you will also have a new instance of ActionCable, but the use of Redis keeps messages synced across connections.
+
+### Notes
+
+Beware that currently the cable server will _not_ auto-reload any changes in the framework. As we've discussed, long-running cable connections mean long-running objects. We don't yet have a way of reloading the classes of those objects in a safe manner. So when you change your channels, or the model your channels use, you must restart the cable server.
+
+We'll get all this abstracted properly when the framework is integrated into Rails.
+
+The WebSocket server doesn't have access to the session, but it has access to the cookies. This can be used when you need to handle authentication. You can see one way of doing that with Devise in this [article](http://www.rubytutorial.io/actioncable-devise-authentication).
+
+## Dependencies
+
+Action Cable is currently tied to Redis through its use of the pubsub feature to route
+messages back and forth over the WebSocket cable connection. This dependency may well
+be alleviated in the future, but for the moment that's what it is. So be sure to have
+Redis installed and running.
+
+The Ruby side of things is built on top of [faye-websocket](https://github.com/faye/faye-websocket-ruby) and [celluloid](https://github.com/celluloid/celluloid).
+
+
+## Deployment
+
+Action Cable is powered by a combination of EventMachine and threads. The
+framework plumbing needed for connection handling is handled in the
+EventMachine loop, but the actual channel, user-specified, work is handled
+in a normal Ruby thread. This means you can use all your regular Rails models
+with no problem, as long as you haven't committed any thread-safety sins.
+
+But this also means that Action Cable needs to run in its own server process.
+So you'll have one set of server processes for your normal web work, and another
+set of server processes for the Action Cable. The former can be single-threaded,
+like Unicorn, but the latter must be multi-threaded, like Puma.
+
+## License
+
+Action Cable is released under the MIT license:
+
+* http://www.opensource.org/licenses/MIT
+
+
+## Support
+
+Bug reports can be filed for the alpha development project here:
+
+* https://github.com/rails/actioncable/issues
diff --git a/actioncable/Rakefile b/actioncable/Rakefile
new file mode 100644
index 0000000000..b6c56e9195
--- /dev/null
+++ b/actioncable/Rakefile
@@ -0,0 +1,13 @@
+require 'rake/testtask'
+
+dir = File.dirname(__FILE__)
+
+task :default => :test
+
+Rake::TestTask.new do |t|
+ t.libs << "test"
+ t.test_files = Dir.glob("#{dir}/test/**/*_test.rb")
+ t.warning = true
+ t.verbose = true
+ t.ruby_opts = ["--dev"] if defined?(JRUBY_VERSION)
+end
diff --git a/actioncable/actioncable.gemspec b/actioncable/actioncable.gemspec
new file mode 100644
index 0000000000..74c21bd24d
--- /dev/null
+++ b/actioncable/actioncable.gemspec
@@ -0,0 +1,32 @@
+version = File.read(File.expand_path('../../RAILS_VERSION', __FILE__)).strip
+
+Gem::Specification.new do |s|
+ s.platform = Gem::Platform::RUBY
+ s.name = 'actioncable'
+ s.version = version
+ s.summary = 'WebSocket framework for Rails.'
+ s.description = 'Structure many real-time application concerns into channels over a single WebSocket connection.'
+
+ s.required_ruby_version = '>= 2.2.2'
+
+ s.license = 'MIT'
+
+ s.author = ['Pratik Naik', 'David Heinemeier Hansson']
+ s.email = ['pratiknaik@gmail.com', 'david@loudthinking.com']
+ s.homepage = 'http://rubyonrails.org'
+
+ s.files = Dir['CHANGELOG.md', 'MIT-LICENSE', 'README.md', 'lib/**/*']
+ s.require_path = 'lib'
+
+ s.add_dependency 'actionpack', version
+
+ s.add_dependency 'coffee-rails', '~> 4.1.0'
+ s.add_dependency 'faye-websocket', '~> 0.10.0'
+ s.add_dependency 'websocket-driver', '~> 0.6.1'
+ s.add_dependency 'celluloid', '~> 0.17.2'
+ s.add_dependency 'em-hiredis', '~> 0.3.0'
+ s.add_dependency 'redis', '~> 3.0'
+
+ s.add_development_dependency 'puma'
+ s.add_development_dependency 'mocha'
+end
diff --git a/actioncable/lib/action_cable.rb b/actioncable/lib/action_cable.rb
new file mode 100644
index 0000000000..f27698765c
--- /dev/null
+++ b/actioncable/lib/action_cable.rb
@@ -0,0 +1,50 @@
+#--
+# Copyright (c) 2015 Basecamp, LLC
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#++
+
+require 'active_support'
+require 'active_support/rails'
+require 'action_cable/version'
+
+module ActionCable
+ extend ActiveSupport::Autoload
+
+ INTERNAL = {
+ identifiers: {
+ ping: '_ping'.freeze
+ },
+ message_types: {
+ confirmation: 'confirm_subscription'.freeze,
+ rejection: 'reject_subscription'.freeze
+ }
+ }
+
+ # Singleton instance of the server
+ module_function def server
+ @server ||= ActionCable::Server::Base.new
+ end
+
+ autoload :Server
+ autoload :Connection
+ autoload :Channel
+ autoload :RemoteConnections
+end
diff --git a/actioncable/lib/action_cable/channel.rb b/actioncable/lib/action_cable/channel.rb
new file mode 100644
index 0000000000..7ae262ce5f
--- /dev/null
+++ b/actioncable/lib/action_cable/channel.rb
@@ -0,0 +1,14 @@
+module ActionCable
+ module Channel
+ extend ActiveSupport::Autoload
+
+ eager_autoload do
+ autoload :Base
+ autoload :Broadcasting
+ autoload :Callbacks
+ autoload :Naming
+ autoload :PeriodicTimers
+ autoload :Streams
+ end
+ end
+end
diff --git a/actioncable/lib/action_cable/channel/base.rb b/actioncable/lib/action_cable/channel/base.rb
new file mode 100644
index 0000000000..ce9d62635c
--- /dev/null
+++ b/actioncable/lib/action_cable/channel/base.rb
@@ -0,0 +1,277 @@
+require 'set'
+
+module ActionCable
+ module Channel
+ # The channel provides the basic structure of grouping behavior into logical units when communicating over the WebSocket connection.
+ # You can think of a channel like a form of controller, but one that's capable of pushing content to the subscriber in addition to simply
+ # responding to the subscriber's direct requests.
+ #
+ # Channel instances are long-lived. A channel object will be instantiated when the cable consumer becomes a subscriber, and then
+ # lives until the consumer disconnects. This may be seconds, minutes, hours, or even days. That means you have to take special care
+ # not to do anything silly in a channel that would balloon its memory footprint or whatever. The references are forever, so they won't be released
+ # as is normally the case with a controller instance that gets thrown away after every request.
+ #
+ # Long-lived channels (and connections) also mean you're responsible for ensuring that the data is fresh. If you hold a reference to a user
+ # record, but the name is changed while that reference is held, you may be sending stale data if you don't take precautions to avoid it.
+ #
+ # The upside of long-lived channel instances is that you can use instance variables to keep reference to objects that future subscriber requests
+ # can interact with. Here's a quick example:
+ #
+ # class ChatChannel < ApplicationCable::Channel
+ # def subscribed
+ # @room = Chat::Room[params[:room_number]]
+ # end
+ #
+ # def speak(data)
+ # @room.speak data, user: current_user
+ # end
+ # end
+ #
+ # The #speak action simply uses the Chat::Room object that was created when the channel was first subscribed to by the consumer when that
+ # subscriber wants to say something in the room.
+ #
+ # == Action processing
+ #
+ # Unlike Action Controllers, channels do not follow a REST constraint form for its actions. It's a remote-procedure call model. You can
+ # declare any public method on the channel (optionally taking a data argument), and this method is automatically exposed as callable to the client.
+ #
+ # Example:
+ #
+ # class AppearanceChannel < ApplicationCable::Channel
+ # def subscribed
+ # @connection_token = generate_connection_token
+ # end
+ #
+ # def unsubscribed
+ # current_user.disappear @connection_token
+ # end
+ #
+ # def appear(data)
+ # current_user.appear @connection_token, on: data['appearing_on']
+ # end
+ #
+ # def away
+ # current_user.away @connection_token
+ # end
+ #
+ # private
+ # def generate_connection_token
+ # SecureRandom.hex(36)
+ # end
+ # end
+ #
+ # In this example, subscribed/unsubscribed are not callable methods, as they were already declared in ActionCable::Channel::Base, but #appear/away
+ # are. #generate_connection_token is also not callable as its a private method. You'll see that appear accepts a data parameter, which it then
+ # uses as part of its model call. #away does not, it's simply a trigger action.
+ #
+ # Also note that in this example, current_user is available because it was marked as an identifying attribute on the connection.
+ # All such identifiers will automatically create a delegation method of the same name on the channel instance.
+ #
+ # == Rejecting subscription requests
+ #
+ # A channel can reject a subscription request in the #subscribed callback by invoking #reject!
+ #
+ # Example:
+ #
+ # class ChatChannel < ApplicationCable::Channel
+ # def subscribed
+ # @room = Chat::Room[params[:room_number]]
+ # reject unless current_user.can_access?(@room)
+ # end
+ # end
+ #
+ # In this example, the subscription will be rejected if the current_user does not have access to the chat room.
+ # On the client-side, Channel#rejected callback will get invoked when the server rejects the subscription request.
+ class Base
+ include Callbacks
+ include PeriodicTimers
+ include Streams
+ include Naming
+ include Broadcasting
+
+ attr_reader :params, :connection, :identifier
+ delegate :logger, to: :connection
+
+ class << self
+ # A list of method names that should be considered actions. This
+ # includes all public instance methods on a channel, less
+ # any internal methods (defined on Base), adding back in
+ # any methods that are internal, but still exist on the class
+ # itself.
+ #
+ # ==== Returns
+ # * <tt>Set</tt> - A set of all methods that should be considered actions.
+ def action_methods
+ @action_methods ||= begin
+ # All public instance methods of this class, including ancestors
+ methods = (public_instance_methods(true) -
+ # Except for public instance methods of Base and its ancestors
+ ActionCable::Channel::Base.public_instance_methods(true) +
+ # Be sure to include shadowed public instance methods of this class
+ public_instance_methods(false)).uniq.map(&:to_s)
+ methods.to_set
+ end
+ end
+
+ protected
+ # action_methods are cached and there is sometimes need to refresh
+ # them. ::clear_action_methods! allows you to do that, so next time
+ # you run action_methods, they will be recalculated
+ def clear_action_methods!
+ @action_methods = nil
+ end
+
+ # Refresh the cached action_methods when a new action_method is added.
+ def method_added(name)
+ super
+ clear_action_methods!
+ end
+ end
+
+ def initialize(connection, identifier, params = {})
+ @connection = connection
+ @identifier = identifier
+ @params = params
+
+ # When a channel is streaming via redis pubsub, we want to delay the confirmation
+ # transmission until redis pubsub subscription is confirmed.
+ @defer_subscription_confirmation = false
+
+ @reject_subscription = nil
+ @subscription_confirmation_sent = nil
+
+ delegate_connection_identifiers
+ subscribe_to_channel
+ end
+
+ # Extract the action name from the passed data and process it via the channel. The process will ensure
+ # that the action requested is a public method on the channel declared by the user (so not one of the callbacks
+ # like #subscribed).
+ def perform_action(data)
+ action = extract_action(data)
+
+ if processable_action?(action)
+ dispatch_action(action, data)
+ else
+ logger.error "Unable to process #{action_signature(action, data)}"
+ end
+ end
+
+ # Called by the cable connection when its cut so the channel has a chance to cleanup with callbacks.
+ # This method is not intended to be called directly by the user. Instead, overwrite the #unsubscribed callback.
+ def unsubscribe_from_channel
+ run_callbacks :unsubscribe do
+ unsubscribed
+ end
+ end
+
+
+ protected
+ # Called once a consumer has become a subscriber of the channel. Usually the place to setup any streams
+ # you want this channel to be sending to the subscriber.
+ def subscribed
+ # Override in subclasses
+ end
+
+ # Called once a consumer has cut its cable connection. Can be used for cleaning up connections or marking
+ # people as offline or the like.
+ def unsubscribed
+ # Override in subclasses
+ end
+
+ # Transmit a hash of data to the subscriber. The hash will automatically be wrapped in a JSON envelope with
+ # the proper channel identifier marked as the recipient.
+ def transmit(data, via: nil)
+ logger.info "#{self.class.name} transmitting #{data.inspect}".tap { |m| m << " (via #{via})" if via }
+ connection.transmit ActiveSupport::JSON.encode(identifier: @identifier, message: data)
+ end
+
+ def defer_subscription_confirmation!
+ @defer_subscription_confirmation = true
+ end
+
+ def defer_subscription_confirmation?
+ @defer_subscription_confirmation
+ end
+
+ def subscription_confirmation_sent?
+ @subscription_confirmation_sent
+ end
+
+ def reject
+ @reject_subscription = true
+ end
+
+ def subscription_rejected?
+ @reject_subscription
+ end
+
+ private
+ def delegate_connection_identifiers
+ connection.identifiers.each do |identifier|
+ define_singleton_method(identifier) do
+ connection.send(identifier)
+ end
+ end
+ end
+
+
+ def subscribe_to_channel
+ run_callbacks :subscribe do
+ subscribed
+ end
+
+ if subscription_rejected?
+ reject_subscription
+ else
+ transmit_subscription_confirmation unless defer_subscription_confirmation?
+ end
+ end
+
+
+ def extract_action(data)
+ (data['action'].presence || :receive).to_sym
+ end
+
+ def processable_action?(action)
+ self.class.action_methods.include?(action.to_s)
+ end
+
+ def dispatch_action(action, data)
+ logger.info action_signature(action, data)
+
+ if method(action).arity == 1
+ public_send action, data
+ else
+ public_send action
+ end
+ end
+
+ def action_signature(action, data)
+ "#{self.class.name}##{action}".tap do |signature|
+ if (arguments = data.except('action')).any?
+ signature << "(#{arguments.inspect})"
+ end
+ end
+ end
+
+ def transmit_subscription_confirmation
+ unless subscription_confirmation_sent?
+ logger.info "#{self.class.name} is transmitting the subscription confirmation"
+ connection.transmit ActiveSupport::JSON.encode(identifier: @identifier, type: ActionCable::INTERNAL[:message_types][:confirmation])
+ @subscription_confirmation_sent = true
+ end
+ end
+
+ def reject_subscription
+ connection.subscriptions.remove_subscription self
+ transmit_subscription_rejection
+ end
+
+ def transmit_subscription_rejection
+ logger.info "#{self.class.name} is transmitting the subscription rejection"
+ connection.transmit ActiveSupport::JSON.encode(identifier: @identifier, type: ActionCable::INTERNAL[:message_types][:rejection])
+ end
+ end
+ end
+end
diff --git a/actioncable/lib/action_cable/channel/broadcasting.rb b/actioncable/lib/action_cable/channel/broadcasting.rb
new file mode 100644
index 0000000000..afc23d7d1a
--- /dev/null
+++ b/actioncable/lib/action_cable/channel/broadcasting.rb
@@ -0,0 +1,29 @@
+require 'active_support/core_ext/object/to_param'
+
+module ActionCable
+ module Channel
+ module Broadcasting
+ extend ActiveSupport::Concern
+
+ delegate :broadcasting_for, to: :class
+
+ class_methods do
+ # Broadcast a hash to a unique broadcasting for this <tt>model</tt> in this channel.
+ def broadcast_to(model, message)
+ ActionCable.server.broadcast(broadcasting_for([ channel_name, model ]), message)
+ end
+
+ def broadcasting_for(model) #:nodoc:
+ case
+ when model.is_a?(Array)
+ model.map { |m| broadcasting_for(m) }.join(':')
+ when model.respond_to?(:to_gid_param)
+ model.to_gid_param
+ else
+ model.to_param
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/actioncable/lib/action_cable/channel/callbacks.rb b/actioncable/lib/action_cable/channel/callbacks.rb
new file mode 100644
index 0000000000..295d750e86
--- /dev/null
+++ b/actioncable/lib/action_cable/channel/callbacks.rb
@@ -0,0 +1,35 @@
+require 'active_support/callbacks'
+
+module ActionCable
+ module Channel
+ module Callbacks
+ extend ActiveSupport::Concern
+ include ActiveSupport::Callbacks
+
+ included do
+ define_callbacks :subscribe
+ define_callbacks :unsubscribe
+ end
+
+ class_methods do
+ def before_subscribe(*methods, &block)
+ set_callback(:subscribe, :before, *methods, &block)
+ end
+
+ def after_subscribe(*methods, &block)
+ set_callback(:subscribe, :after, *methods, &block)
+ end
+ alias_method :on_subscribe, :after_subscribe
+
+ def before_unsubscribe(*methods, &block)
+ set_callback(:unsubscribe, :before, *methods, &block)
+ end
+
+ def after_unsubscribe(*methods, &block)
+ set_callback(:unsubscribe, :after, *methods, &block)
+ end
+ alias_method :on_unsubscribe, :after_unsubscribe
+ end
+ end
+ end
+end
diff --git a/actioncable/lib/action_cable/channel/naming.rb b/actioncable/lib/action_cable/channel/naming.rb
new file mode 100644
index 0000000000..4c9d53b15a
--- /dev/null
+++ b/actioncable/lib/action_cable/channel/naming.rb
@@ -0,0 +1,22 @@
+module ActionCable
+ module Channel
+ module Naming
+ extend ActiveSupport::Concern
+
+ class_methods do
+ # Returns the name of the channel, underscored, without the <tt>Channel</tt> ending.
+ # If the channel is in a namespace, then the namespaces are represented by single
+ # colon separators in the channel name.
+ #
+ # ChatChannel.channel_name # => 'chat'
+ # Chats::AppearancesChannel.channel_name # => 'chats:appearances'
+ def channel_name
+ @channel_name ||= name.sub(/Channel$/, '').gsub('::',':').underscore
+ end
+ end
+
+ # Delegates to the class' <tt>channel_name</tt>
+ delegate :channel_name, to: :class
+ end
+ end
+end
diff --git a/actioncable/lib/action_cable/channel/periodic_timers.rb b/actioncable/lib/action_cable/channel/periodic_timers.rb
new file mode 100644
index 0000000000..25fe8e5e54
--- /dev/null
+++ b/actioncable/lib/action_cable/channel/periodic_timers.rb
@@ -0,0 +1,41 @@
+module ActionCable
+ module Channel
+ module PeriodicTimers
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :periodic_timers, instance_reader: false
+ self.periodic_timers = []
+
+ after_subscribe :start_periodic_timers
+ after_unsubscribe :stop_periodic_timers
+ end
+
+ module ClassMethods
+ # Allow you to call a private method <tt>every</tt> so often seconds. This periodic timer can be useful
+ # for sending a steady flow of updates to a client based off an object that was configured on subscription.
+ # It's an alternative to using streams if the channel is able to do the work internally.
+ def periodically(callback, every:)
+ self.periodic_timers += [ [ callback, every: every ] ]
+ end
+ end
+
+ private
+ def active_periodic_timers
+ @active_periodic_timers ||= []
+ end
+
+ def start_periodic_timers
+ self.class.periodic_timers.each do |callback, options|
+ active_periodic_timers << EventMachine::PeriodicTimer.new(options[:every]) do
+ connection.worker_pool.async.run_periodic_timer(self, callback)
+ end
+ end
+ end
+
+ def stop_periodic_timers
+ active_periodic_timers.each { |timer| timer.cancel }
+ end
+ end
+ end
+end
diff --git a/actioncable/lib/action_cable/channel/streams.rb b/actioncable/lib/action_cable/channel/streams.rb
new file mode 100644
index 0000000000..b5ffa17f72
--- /dev/null
+++ b/actioncable/lib/action_cable/channel/streams.rb
@@ -0,0 +1,114 @@
+module ActionCable
+ module Channel
+ # Streams allow channels to route broadcastings to the subscriber. A broadcasting is, as discussed elsewhere, a pub/sub queue where any data
+ # put into it is automatically sent to the clients that are connected at that time. It's purely an online queue, though. If you're not
+ # streaming a broadcasting at the very moment it sends out an update, you'll not get that update when connecting later.
+ #
+ # Most commonly, the streamed broadcast is sent straight to the subscriber on the client-side. The channel just acts as a connector between
+ # the two parties (the broadcaster and the channel subscriber). Here's an example of a channel that allows subscribers to get all new
+ # comments on a given page:
+ #
+ # class CommentsChannel < ApplicationCable::Channel
+ # def follow(data)
+ # stream_from "comments_for_#{data['recording_id']}"
+ # end
+ #
+ # def unfollow
+ # stop_all_streams
+ # end
+ # end
+ #
+ # So the subscribers of this channel will get whatever data is put into the, let's say, `comments_for_45` broadcasting as soon as it's put there.
+ # That looks like so from that side of things:
+ #
+ # ActionCable.server.broadcast "comments_for_45", author: 'DHH', content: 'Rails is just swell'
+ #
+ # If you have a stream that is related to a model, then the broadcasting used can be generated from the model and channel.
+ # The following example would subscribe to a broadcasting like `comments:Z2lkOi8vVGVzdEFwcC9Qb3N0LzE`
+ #
+ # class CommentsChannel < ApplicationCable::Channel
+ # def subscribed
+ # post = Post.find(params[:id])
+ # stream_for post
+ # end
+ # end
+ #
+ # You can then broadcast to this channel using:
+ #
+ # CommentsChannel.broadcast_to(@post, @comment)
+ #
+ # If you don't just want to parlay the broadcast unfiltered to the subscriber, you can supply a callback that lets you alter what goes out.
+ # Example below shows how you can use this to provide performance introspection in the process:
+ #
+ # class ChatChannel < ApplicationCable::Channel
+ # def subscribed
+ # @room = Chat::Room[params[:room_number]]
+ #
+ # stream_for @room, -> (encoded_message) do
+ # message = ActiveSupport::JSON.decode(encoded_message)
+ #
+ # if message['originated_at'].present?
+ # elapsed_time = (Time.now.to_f - message['originated_at']).round(2)
+ #
+ # ActiveSupport::Notifications.instrument :performance, measurement: 'Chat.message_delay', value: elapsed_time, action: :timing
+ # logger.info "Message took #{elapsed_time}s to arrive"
+ # end
+ #
+ # transmit message
+ # end
+ # end
+ #
+ # You can stop streaming from all broadcasts by calling #stop_all_streams.
+ module Streams
+ extend ActiveSupport::Concern
+
+ included do
+ on_unsubscribe :stop_all_streams
+ end
+
+ # Start streaming from the named <tt>broadcasting</tt> pubsub queue. Optionally, you can pass a <tt>callback</tt> that'll be used
+ # instead of the default of just transmitting the updates straight to the subscriber.
+ def stream_from(broadcasting, callback = nil)
+ # Hold off the confirmation until pubsub#subscribe is successful
+ defer_subscription_confirmation!
+
+ callback ||= default_stream_callback(broadcasting)
+ streams << [ broadcasting, callback ]
+
+ EM.next_tick do
+ pubsub.subscribe(broadcasting, &callback).callback do |reply|
+ transmit_subscription_confirmation
+ logger.info "#{self.class.name} is streaming from #{broadcasting}"
+ end
+ end
+ end
+
+ # Start streaming the pubsub queue for the <tt>model</tt> in this channel. Optionally, you can pass a
+ # <tt>callback</tt> that'll be used instead of the default of just transmitting the updates straight
+ # to the subscriber.
+ def stream_for(model, callback = nil)
+ stream_from(broadcasting_for([ channel_name, model ]), callback)
+ end
+
+ def stop_all_streams
+ streams.each do |broadcasting, callback|
+ pubsub.unsubscribe_proc broadcasting, callback
+ logger.info "#{self.class.name} stopped streaming from #{broadcasting}"
+ end.clear
+ end
+
+ private
+ delegate :pubsub, to: :connection
+
+ def streams
+ @_streams ||= []
+ end
+
+ def default_stream_callback(broadcasting)
+ -> (message) do
+ transmit ActiveSupport::JSON.decode(message), via: "streamed from #{broadcasting}"
+ end
+ end
+ end
+ end
+end
diff --git a/actioncable/lib/action_cable/connection.rb b/actioncable/lib/action_cable/connection.rb
new file mode 100644
index 0000000000..b672e00682
--- /dev/null
+++ b/actioncable/lib/action_cable/connection.rb
@@ -0,0 +1,16 @@
+module ActionCable
+ module Connection
+ extend ActiveSupport::Autoload
+
+ eager_autoload do
+ autoload :Authorization
+ autoload :Base
+ autoload :Identification
+ autoload :InternalChannel
+ autoload :MessageBuffer
+ autoload :WebSocket
+ autoload :Subscriptions
+ autoload :TaggedLoggerProxy
+ end
+ end
+end
diff --git a/actioncable/lib/action_cable/connection/authorization.rb b/actioncable/lib/action_cable/connection/authorization.rb
new file mode 100644
index 0000000000..070a70e4e2
--- /dev/null
+++ b/actioncable/lib/action_cable/connection/authorization.rb
@@ -0,0 +1,13 @@
+module ActionCable
+ module Connection
+ module Authorization
+ class UnauthorizedError < StandardError; end
+
+ private
+ def reject_unauthorized_connection
+ logger.error "An unauthorized connection attempt was rejected"
+ raise UnauthorizedError
+ end
+ end
+ end
+end \ No newline at end of file
diff --git a/actioncable/lib/action_cable/connection/base.rb b/actioncable/lib/action_cable/connection/base.rb
new file mode 100644
index 0000000000..f7b18a85ae
--- /dev/null
+++ b/actioncable/lib/action_cable/connection/base.rb
@@ -0,0 +1,221 @@
+require 'action_dispatch'
+
+module ActionCable
+ module Connection
+ # For every WebSocket the cable server is accepting, a Connection object will be instantiated. This instance becomes the parent
+ # of all the channel subscriptions that are created from there on. Incoming messages are then routed to these channel subscriptions
+ # based on an identifier sent by the cable consumer. The Connection itself does not deal with any specific application logic beyond
+ # authentication and authorization.
+ #
+ # Here's a basic example:
+ #
+ # module ApplicationCable
+ # class Connection < ActionCable::Connection::Base
+ # identified_by :current_user
+ #
+ # def connect
+ # self.current_user = find_verified_user
+ # logger.add_tags current_user.name
+ # end
+ #
+ # def disconnect
+ # # Any cleanup work needed when the cable connection is cut.
+ # end
+ #
+ # protected
+ # def find_verified_user
+ # if current_user = User.find_by_identity cookies.signed[:identity_id]
+ # current_user
+ # else
+ # reject_unauthorized_connection
+ # end
+ # end
+ # end
+ # end
+ #
+ # First, we declare that this connection can be identified by its current_user. This allows us later to be able to find all connections
+ # established for that current_user (and potentially disconnect them if the user was removed from an account). You can declare as many
+ # identification indexes as you like. Declaring an identification means that a attr_accessor is automatically set for that key.
+ #
+ # Second, we rely on the fact that the WebSocket connection is established with the cookies from the domain being sent along. This makes
+ # it easy to use signed cookies that were set when logging in via a web interface to authorize the WebSocket connection.
+ #
+ # Finally, we add a tag to the connection-specific logger with name of the current user to easily distinguish their messages in the log.
+ #
+ # Pretty simple, eh?
+ class Base
+ include Identification
+ include InternalChannel
+ include Authorization
+
+ attr_reader :server, :env, :subscriptions
+ delegate :worker_pool, :pubsub, to: :server
+
+ attr_reader :logger
+
+ def initialize(server, env)
+ @server, @env = server, env
+
+ @logger = new_tagged_logger
+
+ @websocket = ActionCable::Connection::WebSocket.new(env)
+ @subscriptions = ActionCable::Connection::Subscriptions.new(self)
+ @message_buffer = ActionCable::Connection::MessageBuffer.new(self)
+
+ @_internal_redis_subscriptions = nil
+ @started_at = Time.now
+ end
+
+ # Called by the server when a new WebSocket connection is established. This configures the callbacks intended for overwriting by the user.
+ # This method should not be called directly. Rely on the #connect (and #disconnect) callback instead.
+ def process
+ logger.info started_request_message
+
+ if websocket.possible? && allow_request_origin?
+ websocket.on(:open) { |event| send_async :on_open }
+ websocket.on(:message) { |event| on_message event.data }
+ websocket.on(:close) { |event| send_async :on_close }
+
+ respond_to_successful_request
+ else
+ respond_to_invalid_request
+ end
+ end
+
+ # Data received over the cable is handled by this method. It's expected that everything inbound is JSON encoded.
+ # The data is routed to the proper channel that the connection has subscribed to.
+ def receive(data_in_json)
+ if websocket.alive?
+ subscriptions.execute_command ActiveSupport::JSON.decode(data_in_json)
+ else
+ logger.error "Received data without a live WebSocket (#{data_in_json.inspect})"
+ end
+ end
+
+ # Send raw data straight back down the WebSocket. This is not intended to be called directly. Use the #transmit available on the
+ # Channel instead, as that'll automatically address the correct subscriber and wrap the message in JSON.
+ def transmit(data)
+ websocket.transmit data
+ end
+
+ # Close the WebSocket connection.
+ def close
+ websocket.close
+ end
+
+ # Invoke a method on the connection asynchronously through the pool of thread workers.
+ def send_async(method, *arguments)
+ worker_pool.async.invoke(self, method, *arguments)
+ end
+
+ # Return a basic hash of statistics for the connection keyed with `identifier`, `started_at`, and `subscriptions`.
+ # This can be returned by a health check against the connection.
+ def statistics
+ {
+ identifier: connection_identifier,
+ started_at: @started_at,
+ subscriptions: subscriptions.identifiers,
+ request_id: @env['action_dispatch.request_id']
+ }
+ end
+
+ def beat
+ transmit ActiveSupport::JSON.encode(identifier: ActionCable::INTERNAL[:identifiers][:ping], message: Time.now.to_i)
+ end
+
+
+ protected
+ # The request that initiated the WebSocket connection is available here. This gives access to the environment, cookies, etc.
+ def request
+ @request ||= begin
+ environment = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application
+ ActionDispatch::Request.new(environment || env)
+ end
+ end
+
+ # The cookies of the request that initiated the WebSocket connection. Useful for performing authorization checks.
+ def cookies
+ request.cookie_jar
+ end
+
+
+ protected
+ attr_reader :websocket
+ attr_reader :message_buffer
+
+ private
+ def on_open
+ connect if respond_to?(:connect)
+ subscribe_to_internal_channel
+ beat
+
+ message_buffer.process!
+ server.add_connection(self)
+ rescue ActionCable::Connection::Authorization::UnauthorizedError
+ respond_to_invalid_request
+ end
+
+ def on_message(message)
+ message_buffer.append message
+ end
+
+ def on_close
+ logger.info finished_request_message
+
+ server.remove_connection(self)
+
+ subscriptions.unsubscribe_from_all
+ unsubscribe_from_internal_channel
+
+ disconnect if respond_to?(:disconnect)
+ end
+
+
+ def allow_request_origin?
+ return true if server.config.disable_request_forgery_protection
+
+ if Array(server.config.allowed_request_origins).any? { |allowed_origin| allowed_origin === env['HTTP_ORIGIN'] }
+ true
+ else
+ logger.error("Request origin not allowed: #{env['HTTP_ORIGIN']}")
+ false
+ end
+ end
+
+ def respond_to_successful_request
+ websocket.rack_response
+ end
+
+ def respond_to_invalid_request
+ close if websocket.alive?
+
+ logger.info finished_request_message
+ [ 404, { 'Content-Type' => 'text/plain' }, [ 'Page not found' ] ]
+ end
+
+
+ # Tags are declared in the server but computed in the connection. This allows us per-connection tailored tags.
+ def new_tagged_logger
+ TaggedLoggerProxy.new server.logger,
+ tags: server.config.log_tags.map { |tag| tag.respond_to?(:call) ? tag.call(request) : tag.to_s.camelize }
+ end
+
+ def started_request_message
+ 'Started %s "%s"%s for %s at %s' % [
+ request.request_method,
+ request.filtered_path,
+ websocket.possible? ? ' [WebSocket]' : '',
+ request.ip,
+ Time.now.to_s ]
+ end
+
+ def finished_request_message
+ 'Finished "%s"%s for %s at %s' % [
+ request.filtered_path,
+ websocket.possible? ? ' [WebSocket]' : '',
+ request.ip,
+ Time.now.to_s ]
+ end
+ end
+ end
+end
diff --git a/actioncable/lib/action_cable/connection/identification.rb b/actioncable/lib/action_cable/connection/identification.rb
new file mode 100644
index 0000000000..2d75ff8d6d
--- /dev/null
+++ b/actioncable/lib/action_cable/connection/identification.rb
@@ -0,0 +1,46 @@
+require 'set'
+
+module ActionCable
+ module Connection
+ module Identification
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :identifiers
+ self.identifiers = Set.new
+ end
+
+ class_methods do
+ # Mark a key as being a connection identifier index that can then used to find the specific connection again later.
+ # Common identifiers are current_user and current_account, but could be anything really.
+ #
+ # Note that anything marked as an identifier will automatically create a delegate by the same name on any
+ # channel instances created off the connection.
+ def identified_by(*identifiers)
+ Array(identifiers).each { |identifier| attr_accessor identifier }
+ self.identifiers += identifiers
+ end
+ end
+
+ # Return a single connection identifier that combines the value of all the registered identifiers into a single gid.
+ def connection_identifier
+ unless defined? @connection_identifier
+ @connection_identifier = connection_gid identifiers.map { |id| instance_variable_get("@#{id}") }.compact
+ end
+
+ @connection_identifier
+ end
+
+ private
+ def connection_gid(ids)
+ ids.map do |o|
+ if o.respond_to? :to_gid_param
+ o.to_gid_param
+ else
+ o.to_s
+ end
+ end.sort.join(":")
+ end
+ end
+ end
+end
diff --git a/actioncable/lib/action_cable/connection/internal_channel.rb b/actioncable/lib/action_cable/connection/internal_channel.rb
new file mode 100644
index 0000000000..c065a24ab7
--- /dev/null
+++ b/actioncable/lib/action_cable/connection/internal_channel.rb
@@ -0,0 +1,45 @@
+module ActionCable
+ module Connection
+ # Makes it possible for the RemoteConnection to disconnect a specific connection.
+ module InternalChannel
+ extend ActiveSupport::Concern
+
+ private
+ def internal_redis_channel
+ "action_cable/#{connection_identifier}"
+ end
+
+ def subscribe_to_internal_channel
+ if connection_identifier.present?
+ callback = -> (message) { process_internal_message(message) }
+ @_internal_redis_subscriptions ||= []
+ @_internal_redis_subscriptions << [ internal_redis_channel, callback ]
+
+ EM.next_tick { pubsub.subscribe(internal_redis_channel, &callback) }
+ logger.info "Registered connection (#{connection_identifier})"
+ end
+ end
+
+ def unsubscribe_from_internal_channel
+ if @_internal_redis_subscriptions.present?
+ @_internal_redis_subscriptions.each { |channel, callback| EM.next_tick { pubsub.unsubscribe_proc(channel, callback) } }
+ end
+ end
+
+ def process_internal_message(message)
+ message = ActiveSupport::JSON.decode(message)
+
+ case message['type']
+ when 'disconnect'
+ logger.info "Removing connection (#{connection_identifier})"
+ websocket.close
+ end
+ rescue Exception => e
+ logger.error "There was an exception - #{e.class}(#{e.message})"
+ logger.error e.backtrace.join("\n")
+
+ close
+ end
+ end
+ end
+end
diff --git a/actioncable/lib/action_cable/connection/message_buffer.rb b/actioncable/lib/action_cable/connection/message_buffer.rb
new file mode 100644
index 0000000000..2f65a1e84a
--- /dev/null
+++ b/actioncable/lib/action_cable/connection/message_buffer.rb
@@ -0,0 +1,54 @@
+module ActionCable
+ module Connection
+ # Allows us to buffer messages received from the WebSocket before the Connection has been fully initialized and is ready to receive them.
+ # Entirely internal operation and should not be used directly by the user.
+ class MessageBuffer
+ def initialize(connection)
+ @connection = connection
+ @buffered_messages = []
+ end
+
+ def append(message)
+ if valid? message
+ if processing?
+ receive message
+ else
+ buffer message
+ end
+ else
+ connection.logger.error "Couldn't handle non-string message: #{message.class}"
+ end
+ end
+
+ def processing?
+ @processing
+ end
+
+ def process!
+ @processing = true
+ receive_buffered_messages
+ end
+
+ protected
+ attr_reader :connection
+ attr_accessor :buffered_messages
+
+ private
+ def valid?(message)
+ message.is_a?(String)
+ end
+
+ def receive(message)
+ connection.send_async :receive, message
+ end
+
+ def buffer(message)
+ buffered_messages << message
+ end
+
+ def receive_buffered_messages
+ receive buffered_messages.shift until buffered_messages.empty?
+ end
+ end
+ end
+end
diff --git a/actioncable/lib/action_cable/connection/subscriptions.rb b/actioncable/lib/action_cable/connection/subscriptions.rb
new file mode 100644
index 0000000000..65d6634bb0
--- /dev/null
+++ b/actioncable/lib/action_cable/connection/subscriptions.rb
@@ -0,0 +1,76 @@
+require 'active_support/core_ext/hash/indifferent_access'
+
+module ActionCable
+ module Connection
+ # Collection class for all the channel subscriptions established on a given connection. Responsible for routing incoming commands that arrive on
+ # the connection to the proper channel. Should not be used directly by the user.
+ class Subscriptions
+ def initialize(connection)
+ @connection = connection
+ @subscriptions = {}
+ end
+
+ def execute_command(data)
+ case data['command']
+ when 'subscribe' then add data
+ when 'unsubscribe' then remove data
+ when 'message' then perform_action data
+ else
+ logger.error "Received unrecognized command in #{data.inspect}"
+ end
+ rescue Exception => e
+ logger.error "Could not execute command from #{data.inspect}) [#{e.class} - #{e.message}]: #{e.backtrace.first(5).join(" | ")}"
+ end
+
+ def add(data)
+ id_key = data['identifier']
+ id_options = ActiveSupport::JSON.decode(id_key).with_indifferent_access
+
+ subscription_klass = connection.server.channel_classes[id_options[:channel]]
+
+ if subscription_klass
+ subscriptions[id_key] ||= subscription_klass.new(connection, id_key, id_options)
+ else
+ logger.error "Subscription class not found (#{data.inspect})"
+ end
+ end
+
+ def remove(data)
+ logger.info "Unsubscribing from channel: #{data['identifier']}"
+ remove_subscription subscriptions[data['identifier']]
+ end
+
+ def remove_subscription(subscription)
+ subscription.unsubscribe_from_channel
+ subscriptions.delete(subscription.identifier)
+ end
+
+ def perform_action(data)
+ find(data).perform_action ActiveSupport::JSON.decode(data['data'])
+ end
+
+
+ def identifiers
+ subscriptions.keys
+ end
+
+ def unsubscribe_from_all
+ subscriptions.each { |id, channel| channel.unsubscribe_from_channel }
+ end
+
+ protected
+ attr_reader :connection, :subscriptions
+
+ private
+ delegate :logger, to: :connection
+
+ def find(data)
+ if subscription = subscriptions[data['identifier']]
+ subscription
+ else
+ raise "Unable to find subscription with identifier: #{data['identifier']}"
+ end
+ end
+ end
+ end
+end
diff --git a/actioncable/lib/action_cable/connection/tagged_logger_proxy.rb b/actioncable/lib/action_cable/connection/tagged_logger_proxy.rb
new file mode 100644
index 0000000000..41afa9680a
--- /dev/null
+++ b/actioncable/lib/action_cable/connection/tagged_logger_proxy.rb
@@ -0,0 +1,40 @@
+module ActionCable
+ module Connection
+ # Allows the use of per-connection tags against the server logger. This wouldn't work using the traditional
+ # <tt>ActiveSupport::TaggedLogging</tt> enhanced Rails.logger, as that logger will reset the tags between requests.
+ # The connection is long-lived, so it needs its own set of tags for its independent duration.
+ class TaggedLoggerProxy
+ attr_reader :tags
+
+ def initialize(logger, tags:)
+ @logger = logger
+ @tags = tags.flatten
+ end
+
+ def add_tags(*tags)
+ @tags += tags.flatten
+ @tags = @tags.uniq
+ end
+
+ def tag(logger)
+ if logger.respond_to?(:tagged)
+ current_tags = tags - logger.formatter.current_tags
+ logger.tagged(*current_tags) { yield }
+ else
+ yield
+ end
+ end
+
+ %i( debug info warn error fatal unknown ).each do |severity|
+ define_method(severity) do |message|
+ log severity, message
+ end
+ end
+
+ protected
+ def log(type, message)
+ tag(@logger) { @logger.send type, message }
+ end
+ end
+ end
+end
diff --git a/actioncable/lib/action_cable/connection/web_socket.rb b/actioncable/lib/action_cable/connection/web_socket.rb
new file mode 100644
index 0000000000..670d5690ae
--- /dev/null
+++ b/actioncable/lib/action_cable/connection/web_socket.rb
@@ -0,0 +1,29 @@
+require 'faye/websocket'
+
+module ActionCable
+ module Connection
+ # Decorate the Faye::WebSocket with helpers we need.
+ class WebSocket
+ delegate :rack_response, :close, :on, to: :websocket
+
+ def initialize(env)
+ @websocket = Faye::WebSocket.websocket?(env) ? Faye::WebSocket.new(env) : nil
+ end
+
+ def possible?
+ websocket
+ end
+
+ def alive?
+ websocket && websocket.ready_state == Faye::WebSocket::API::OPEN
+ end
+
+ def transmit(data)
+ websocket.send data
+ end
+
+ protected
+ attr_reader :websocket
+ end
+ end
+end
diff --git a/actioncable/lib/action_cable/engine.rb b/actioncable/lib/action_cable/engine.rb
new file mode 100644
index 0000000000..2d3caa5b0a
--- /dev/null
+++ b/actioncable/lib/action_cable/engine.rb
@@ -0,0 +1,38 @@
+require "rails"
+require "action_cable"
+require "action_cable/helpers/action_cable_helper"
+require "active_support/core_ext/hash/indifferent_access"
+
+module ActionCable
+ class Railtie < Rails::Engine # :nodoc:
+ config.action_cable = ActiveSupport::OrderedOptions.new
+ config.action_cable.url = '/cable'
+
+ config.eager_load_namespaces << ActionCable
+
+ initializer "action_cable.helpers" do
+ ActiveSupport.on_load(:action_view) do
+ include ActionCable::Helpers::ActionCableHelper
+ end
+ end
+
+ initializer "action_cable.logger" do
+ ActiveSupport.on_load(:action_cable) { self.logger ||= ::Rails.logger }
+ end
+
+ initializer "action_cable.set_configs" do |app|
+ options = app.config.action_cable
+ options.allowed_request_origins ||= "http://localhost:3000" if ::Rails.env.development?
+
+ app.paths.add "config/redis/cable", with: "config/redis/cable.yml"
+
+ ActiveSupport.on_load(:action_cable) do
+ if (redis_cable_path = Pathname.new(app.config.paths["config/redis/cable"].first)).exist?
+ self.redis = Rails.application.config_for(redis_cable_path).with_indifferent_access
+ end
+
+ options.each { |k,v| send("#{k}=", v) }
+ end
+ end
+ end
+end
diff --git a/actioncable/lib/action_cable/gem_version.rb b/actioncable/lib/action_cable/gem_version.rb
new file mode 100644
index 0000000000..b1286aea6f
--- /dev/null
+++ b/actioncable/lib/action_cable/gem_version.rb
@@ -0,0 +1,15 @@
+module ActionCable
+ # Returns the version of the currently loaded Action Cable as a <tt>Gem::Version</tt>.
+ def self.gem_version
+ Gem::Version.new VERSION::STRING
+ end
+
+ module VERSION
+ MAJOR = 5
+ MINOR = 0
+ TINY = 0
+ PRE = "beta1"
+
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
+ end
+end
diff --git a/actioncable/lib/action_cable/helpers/action_cable_helper.rb b/actioncable/lib/action_cable/helpers/action_cable_helper.rb
new file mode 100644
index 0000000000..b82751468a
--- /dev/null
+++ b/actioncable/lib/action_cable/helpers/action_cable_helper.rb
@@ -0,0 +1,29 @@
+module ActionCable
+ module Helpers
+ module ActionCableHelper
+ # Returns an "action-cable-url" meta tag with the value of the url specified in your
+ # configuration. Ensure this is above your javascript tag:
+ #
+ # <head>
+ # <%= action_cable_meta_tag %>
+ # <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
+ # </head>
+ #
+ # This is then used by ActionCable to determine the url of your websocket server.
+ # Your CoffeeScript can then connect to the server without needing to specify the
+ # url directly:
+ #
+ # #= require cable
+ # @App = {}
+ # App.cable = Cable.createConsumer()
+ #
+ # Make sure to specify the correct server location in each of your environments
+ # config file:
+ #
+ # config.action_cable.url = "ws://example.com:28080"
+ def action_cable_meta_tag
+ tag "meta", name: "action-cable-url", content: Rails.application.config.action_cable.url
+ end
+ end
+ end
+end
diff --git a/actioncable/lib/action_cable/process/logging.rb b/actioncable/lib/action_cable/process/logging.rb
new file mode 100644
index 0000000000..72b1a080d1
--- /dev/null
+++ b/actioncable/lib/action_cable/process/logging.rb
@@ -0,0 +1,10 @@
+require 'action_cable/server'
+require 'eventmachine'
+require 'celluloid'
+
+EM.error_handler do |e|
+ puts "Error raised inside the event loop: #{e.message}"
+ puts e.backtrace.join("\n")
+end
+
+Celluloid.logger = ActionCable.server.logger
diff --git a/actioncable/lib/action_cable/remote_connections.rb b/actioncable/lib/action_cable/remote_connections.rb
new file mode 100644
index 0000000000..1230d905ad
--- /dev/null
+++ b/actioncable/lib/action_cable/remote_connections.rb
@@ -0,0 +1,64 @@
+module ActionCable
+ # If you need to disconnect a given connection, you go through the RemoteConnections. You find the connections you're looking for by
+ # searching the identifier declared on the connection. Example:
+ #
+ # module ApplicationCable
+ # class Connection < ActionCable::Connection::Base
+ # identified_by :current_user
+ # ....
+ # end
+ # end
+ #
+ # ActionCable.server.remote_connections.where(current_user: User.find(1)).disconnect
+ #
+ # That will disconnect all the connections established for User.find(1) across all servers running on all machines (because it uses
+ # the internal channel that all these servers are subscribed to).
+ class RemoteConnections
+ attr_reader :server
+
+ def initialize(server)
+ @server = server
+ end
+
+ def where(identifier)
+ RemoteConnection.new(server, identifier)
+ end
+
+ private
+ # Represents a single remote connection found via ActionCable.server.remote_connections.where(*).
+ # Exists for the solely for the purpose of calling #disconnect on that connection.
+ class RemoteConnection
+ class InvalidIdentifiersError < StandardError; end
+
+ include Connection::Identification, Connection::InternalChannel
+
+ def initialize(server, ids)
+ @server = server
+ set_identifier_instance_vars(ids)
+ end
+
+ # Uses the internal channel to disconnect the connection.
+ def disconnect
+ server.broadcast internal_redis_channel, type: 'disconnect'
+ end
+
+ # Returns all the identifiers that were applied to this connection.
+ def identifiers
+ server.connection_identifiers
+ end
+
+ private
+ attr_reader :server
+
+ def set_identifier_instance_vars(ids)
+ raise InvalidIdentifiersError unless valid_identifiers?(ids)
+ ids.each { |k,v| instance_variable_set("@#{k}", v) }
+ end
+
+ def valid_identifiers?(ids)
+ keys = ids.keys
+ identifiers.all? { |id| keys.include?(id) }
+ end
+ end
+ end
+end
diff --git a/actioncable/lib/action_cable/server.rb b/actioncable/lib/action_cable/server.rb
new file mode 100644
index 0000000000..a2a89d5f1e
--- /dev/null
+++ b/actioncable/lib/action_cable/server.rb
@@ -0,0 +1,19 @@
+require 'eventmachine'
+EventMachine.epoll if EventMachine.epoll?
+EventMachine.kqueue if EventMachine.kqueue?
+
+module ActionCable
+ module Server
+ extend ActiveSupport::Autoload
+
+ eager_autoload do
+ autoload :Base
+ autoload :Broadcasting
+ autoload :Connections
+ autoload :Configuration
+
+ autoload :Worker
+ autoload :ActiveRecordConnectionManagement, 'action_cable/server/worker/active_record_connection_management'
+ end
+ end
+end
diff --git a/actioncable/lib/action_cable/server/base.rb b/actioncable/lib/action_cable/server/base.rb
new file mode 100644
index 0000000000..740e4b301e
--- /dev/null
+++ b/actioncable/lib/action_cable/server/base.rb
@@ -0,0 +1,77 @@
+# FIXME: Cargo culted fix from https://github.com/celluloid/celluloid-pool/issues/10
+require 'celluloid/current'
+
+require 'em-hiredis'
+
+module ActionCable
+ module Server
+ # A singleton ActionCable::Server instance is available via ActionCable.server. It's used by the rack process that starts the cable server, but
+ # also by the user to reach the RemoteConnections instead for finding and disconnecting connections across all servers.
+ #
+ # Also, this is the server instance used for broadcasting. See Broadcasting for details.
+ class Base
+ include ActionCable::Server::Broadcasting
+ include ActionCable::Server::Connections
+
+ cattr_accessor(:config, instance_accessor: true) { ActionCable::Server::Configuration.new }
+
+ def self.logger; config.logger; end
+ delegate :logger, to: :config
+
+ def initialize
+ end
+
+ # Called by rack to setup the server.
+ def call(env)
+ setup_heartbeat_timer
+ config.connection_class.new(self, env).process
+ end
+
+ # Disconnect all the connections identified by `identifiers` on this server or any others via RemoteConnections.
+ def disconnect(identifiers)
+ remote_connections.where(identifiers).disconnect
+ end
+
+ # Gateway to RemoteConnections. See that class for details.
+ def remote_connections
+ @remote_connections ||= RemoteConnections.new(self)
+ end
+
+ # The thread worker pool for handling all the connection work on this server. Default size is set by config.worker_pool_size.
+ def worker_pool
+ @worker_pool ||= ActionCable::Server::Worker.pool(size: config.worker_pool_size)
+ end
+
+ # Requires and returns a hash of all the channel class constants keyed by name.
+ def channel_classes
+ @channel_classes ||= begin
+ config.channel_paths.each { |channel_path| require channel_path }
+ config.channel_class_names.each_with_object({}) { |name, hash| hash[name] = name.constantize }
+ end
+ end
+
+ # The redis pubsub adapter used for all streams/broadcasting.
+ def pubsub
+ @pubsub ||= redis.pubsub
+ end
+
+ # The EventMachine Redis instance used by the pubsub adapter.
+ def redis
+ @redis ||= EM::Hiredis.connect(config.redis[:url]).tap do |redis|
+ redis.on(:reconnect_failed) do
+ logger.info "[ActionCable] Redis reconnect failed."
+ # logger.info "[ActionCable] Redis reconnected. Closing all the open connections."
+ # @connections.map &:close
+ end
+ end
+ end
+
+ # All the identifiers applied to the connection class associated with this server.
+ def connection_identifiers
+ config.connection_class.identifiers
+ end
+ end
+
+ ActiveSupport.run_load_hooks(:action_cable, Base.config)
+ end
+end
diff --git a/actioncable/lib/action_cable/server/broadcasting.rb b/actioncable/lib/action_cable/server/broadcasting.rb
new file mode 100644
index 0000000000..c759239a0e
--- /dev/null
+++ b/actioncable/lib/action_cable/server/broadcasting.rb
@@ -0,0 +1,54 @@
+require 'redis'
+
+module ActionCable
+ module Server
+ # Broadcasting is how other parts of your application can send messages to the channel subscribers. As explained in Channel, most of the time, these
+ # broadcastings are streamed directly to the clients subscribed to the named broadcasting. Let's explain with a full-stack example:
+ #
+ # class WebNotificationsChannel < ApplicationCable::Channel
+ # def subscribed
+ # stream_from "web_notifications_#{current_user.id}"
+ # end
+ # end
+ #
+ # # Somewhere in your app this is called, perhaps from a NewCommentJob
+ # ActionCable.server.broadcast \
+ # "web_notifications_1", { title: 'New things!', body: 'All shit fit for print' }
+ #
+ # # Client-side coffescript, which assumes you've already requested the right to send web notifications
+ # App.cable.subscriptions.create "WebNotificationsChannel",
+ # received: (data) ->
+ # new Notification data['title'], body: data['body']
+ module Broadcasting
+ # Broadcast a hash directly to a named <tt>broadcasting</tt>. It'll automatically be JSON encoded.
+ def broadcast(broadcasting, message)
+ broadcaster_for(broadcasting).broadcast(message)
+ end
+
+ # Returns a broadcaster for a named <tt>broadcasting</tt> that can be reused. Useful when you have a object that
+ # may need multiple spots to transmit to a specific broadcasting over and over.
+ def broadcaster_for(broadcasting)
+ Broadcaster.new(self, broadcasting)
+ end
+
+ # The redis instance used for broadcasting. Not intended for direct user use.
+ def broadcasting_redis
+ @broadcasting_redis ||= Redis.new(config.redis)
+ end
+
+ private
+ class Broadcaster
+ attr_reader :server, :broadcasting
+
+ def initialize(server, broadcasting)
+ @server, @broadcasting = server, broadcasting
+ end
+
+ def broadcast(message)
+ server.logger.info "[ActionCable] Broadcasting to #{broadcasting}: #{message}"
+ server.broadcasting_redis.publish broadcasting, ActiveSupport::JSON.encode(message)
+ end
+ end
+ end
+ end
+end
diff --git a/actioncable/lib/action_cable/server/configuration.rb b/actioncable/lib/action_cable/server/configuration.rb
new file mode 100644
index 0000000000..935133cbba
--- /dev/null
+++ b/actioncable/lib/action_cable/server/configuration.rb
@@ -0,0 +1,35 @@
+module ActionCable
+ module Server
+ # An instance of this configuration object is available via ActionCable.server.config, which allows you to tweak the configuration points
+ # in a Rails config initializer.
+ class Configuration
+ attr_accessor :logger, :log_tags
+ attr_accessor :connection_class, :worker_pool_size
+ attr_accessor :redis, :channels_path
+ attr_accessor :disable_request_forgery_protection, :allowed_request_origins
+ attr_accessor :url
+
+ def initialize
+ @log_tags = []
+
+ @connection_class = ApplicationCable::Connection
+ @worker_pool_size = 100
+
+ @channels_path = Rails.root.join('app/channels')
+
+ @disable_request_forgery_protection = false
+ end
+
+ def channel_paths
+ @channels ||= Dir["#{channels_path}/**/*_channel.rb"]
+ end
+
+ def channel_class_names
+ @channel_class_names ||= channel_paths.collect do |channel_path|
+ Pathname.new(channel_path).basename.to_s.split('.').first.camelize
+ end
+ end
+ end
+ end
+end
+
diff --git a/actioncable/lib/action_cable/server/connections.rb b/actioncable/lib/action_cable/server/connections.rb
new file mode 100644
index 0000000000..47dcea8c20
--- /dev/null
+++ b/actioncable/lib/action_cable/server/connections.rb
@@ -0,0 +1,37 @@
+module ActionCable
+ module Server
+ # Collection class for all the connections that's been established on this specific server. Remember, usually you'll run many cable servers, so
+ # you can't use this collection as an full list of all the connections established against your application. Use RemoteConnections for that.
+ # As such, this is primarily for internal use.
+ module Connections
+ BEAT_INTERVAL = 3
+
+ def connections
+ @connections ||= []
+ end
+
+ def add_connection(connection)
+ connections << connection
+ end
+
+ def remove_connection(connection)
+ connections.delete connection
+ end
+
+ # WebSocket connection implementations differ on when they'll mark a connection as stale. We basically never want a connection to go stale, as you
+ # then can't rely on being able to receive and send to it. So there's a 3 second heartbeat running on all connections. If the beat fails, we automatically
+ # disconnect.
+ def setup_heartbeat_timer
+ EM.next_tick do
+ @heartbeat_timer ||= EventMachine.add_periodic_timer(BEAT_INTERVAL) do
+ EM.next_tick { connections.map(&:beat) }
+ end
+ end
+ end
+
+ def open_connections_statistics
+ connections.map(&:statistics)
+ end
+ end
+ end
+end
diff --git a/actioncable/lib/action_cable/server/worker.rb b/actioncable/lib/action_cable/server/worker.rb
new file mode 100644
index 0000000000..e063b2a2e1
--- /dev/null
+++ b/actioncable/lib/action_cable/server/worker.rb
@@ -0,0 +1,42 @@
+require 'celluloid'
+require 'active_support/callbacks'
+
+module ActionCable
+ module Server
+ # Worker used by Server.send_async to do connection work in threads. Only for internal use.
+ class Worker
+ include ActiveSupport::Callbacks
+ include Celluloid
+
+ attr_reader :connection
+ define_callbacks :work
+ include ActiveRecordConnectionManagement
+
+ def invoke(receiver, method, *args)
+ @connection = receiver
+
+ run_callbacks :work do
+ receiver.send method, *args
+ end
+ rescue Exception => e
+ logger.error "There was an exception - #{e.class}(#{e.message})"
+ logger.error e.backtrace.join("\n")
+
+ receiver.handle_exception if receiver.respond_to?(:handle_exception)
+ end
+
+ def run_periodic_timer(channel, callback)
+ @connection = channel.connection
+
+ run_callbacks :work do
+ callback.respond_to?(:call) ? channel.instance_exec(&callback) : channel.send(callback)
+ end
+ end
+
+ private
+ def logger
+ ActionCable.server.logger
+ end
+ end
+ end
+end
diff --git a/actioncable/lib/action_cable/server/worker/active_record_connection_management.rb b/actioncable/lib/action_cable/server/worker/active_record_connection_management.rb
new file mode 100644
index 0000000000..ecece4e270
--- /dev/null
+++ b/actioncable/lib/action_cable/server/worker/active_record_connection_management.rb
@@ -0,0 +1,22 @@
+module ActionCable
+ module Server
+ class Worker
+ # Clear active connections between units of work so the long-running channel or connection processes do not hoard connections.
+ module ActiveRecordConnectionManagement
+ extend ActiveSupport::Concern
+
+ included do
+ if defined?(ActiveRecord::Base)
+ set_callback :work, :around, :with_database_connections
+ end
+ end
+
+ def with_database_connections
+ connection.logger.tag(ActiveRecord::Base.logger) { yield }
+ ensure
+ ActiveRecord::Base.clear_active_connections!
+ end
+ end
+ end
+ end
+end \ No newline at end of file
diff --git a/actioncable/lib/action_cable/version.rb b/actioncable/lib/action_cable/version.rb
new file mode 100644
index 0000000000..e17877202b
--- /dev/null
+++ b/actioncable/lib/action_cable/version.rb
@@ -0,0 +1,8 @@
+require_relative 'gem_version'
+
+module ActionCable
+ # Returns the version of the currently loaded Action Cable as a <tt>Gem::Version</tt>
+ def self.version
+ gem_version
+ end
+end
diff --git a/actioncable/lib/assets/javascripts/action_cable.coffee.erb b/actioncable/lib/assets/javascripts/action_cable.coffee.erb
new file mode 100644
index 0000000000..7daea4ebcd
--- /dev/null
+++ b/actioncable/lib/assets/javascripts/action_cable.coffee.erb
@@ -0,0 +1,23 @@
+#= require_self
+#= require action_cable/consumer
+
+@ActionCable =
+ INTERNAL: <%= ActionCable::INTERNAL.to_json %>
+
+ createConsumer: (url = @getConfig("url")) ->
+ new ActionCable.Consumer @createWebSocketURL(url)
+
+ getConfig: (name) ->
+ element = document.head.querySelector("meta[name='action-cable-#{name}']")
+ element?.getAttribute("content")
+
+ createWebSocketURL: (url) ->
+ if url and not /^wss?:/i.test(url)
+ a = document.createElement("a")
+ a.href = url
+ # Fix populating Location properties in IE. Otherwise, protocol will be blank.
+ a.href = a.href
+ a.protocol = a.protocol.replace("http", "ws")
+ a.href
+ else
+ url
diff --git a/actioncable/lib/assets/javascripts/action_cable/connection.coffee b/actioncable/lib/assets/javascripts/action_cable/connection.coffee
new file mode 100644
index 0000000000..2f69a9b26c
--- /dev/null
+++ b/actioncable/lib/assets/javascripts/action_cable/connection.coffee
@@ -0,0 +1,84 @@
+# Encapsulate the cable connection held by the consumer. This is an internal class not intended for direct user manipulation.
+
+{message_types} = ActionCable.INTERNAL
+
+class ActionCable.Connection
+ @reopenDelay: 500
+
+ constructor: (@consumer) ->
+ @open()
+
+ send: (data) ->
+ if @isOpen()
+ @webSocket.send(JSON.stringify(data))
+ true
+ else
+ false
+
+ open: =>
+ if @webSocket and not @isState("closed")
+ throw new Error("Existing connection must be closed before opening")
+ else
+ @webSocket = new WebSocket(@consumer.url)
+ @installEventHandlers()
+ true
+
+ close: ->
+ @webSocket?.close()
+
+ reopen: ->
+ if @isState("closed")
+ @open()
+ else
+ try
+ @close()
+ finally
+ setTimeout(@open, @constructor.reopenDelay)
+
+ isOpen: ->
+ @isState("open")
+
+ # Private
+
+ isState: (states...) ->
+ @getState() in states
+
+ getState: ->
+ return state.toLowerCase() for state, value of WebSocket when value is @webSocket?.readyState
+ null
+
+ installEventHandlers: ->
+ for eventName of @events
+ handler = @events[eventName].bind(this)
+ @webSocket["on#{eventName}"] = handler
+ return
+
+ events:
+ message: (event) ->
+ {identifier, message, type} = JSON.parse(event.data)
+
+ switch type
+ when message_types.confirmation
+ @consumer.subscriptions.notify(identifier, "connected")
+ when message_types.rejection
+ @consumer.subscriptions.reject(identifier)
+ else
+ @consumer.subscriptions.notify(identifier, "received", message)
+
+ open: ->
+ @disconnected = false
+ @consumer.subscriptions.reload()
+
+ close: ->
+ @disconnect()
+
+ error: ->
+ @disconnect()
+
+ disconnect: ->
+ return if @disconnected
+ @disconnected = true
+ @consumer.subscriptions.notifyAll("disconnected")
+
+ toJSON: ->
+ state: @getState()
diff --git a/actioncable/lib/assets/javascripts/action_cable/connection_monitor.coffee b/actioncable/lib/assets/javascripts/action_cable/connection_monitor.coffee
new file mode 100644
index 0000000000..b594802be1
--- /dev/null
+++ b/actioncable/lib/assets/javascripts/action_cable/connection_monitor.coffee
@@ -0,0 +1,84 @@
+# Responsible for ensuring the cable connection is in good health by validating the heartbeat pings sent from the server, and attempting
+# revival reconnections if things go astray. Internal class, not intended for direct user manipulation.
+class ActionCable.ConnectionMonitor
+ @pollInterval:
+ min: 3
+ max: 30
+
+ @staleThreshold: 6 # Server::Connections::BEAT_INTERVAL * 2 (missed two pings)
+
+ identifier: ActionCable.INTERNAL.identifiers.ping
+
+ constructor: (@consumer) ->
+ @consumer.subscriptions.add(this)
+ @start()
+
+ connected: ->
+ @reset()
+ @pingedAt = now()
+ delete @disconnectedAt
+
+ disconnected: ->
+ @disconnectedAt = now()
+
+ received: ->
+ @pingedAt = now()
+
+ reset: ->
+ @reconnectAttempts = 0
+
+ start: ->
+ @reset()
+ delete @stoppedAt
+ @startedAt = now()
+ @poll()
+ document.addEventListener("visibilitychange", @visibilityDidChange)
+
+ stop: ->
+ @stoppedAt = now()
+ document.removeEventListener("visibilitychange", @visibilityDidChange)
+
+ poll: ->
+ setTimeout =>
+ unless @stoppedAt
+ @reconnectIfStale()
+ @poll()
+ , @getInterval()
+
+ getInterval: ->
+ {min, max} = @constructor.pollInterval
+ interval = 5 * Math.log(@reconnectAttempts + 1)
+ clamp(interval, min, max) * 1000
+
+ reconnectIfStale: ->
+ if @connectionIsStale()
+ @reconnectAttempts++
+ unless @disconnectedRecently()
+ @consumer.connection.reopen()
+
+ connectionIsStale: ->
+ secondsSince(@pingedAt ? @startedAt) > @constructor.staleThreshold
+
+ disconnectedRecently: ->
+ @disconnectedAt and secondsSince(@disconnectedAt) < @constructor.staleThreshold
+
+ visibilityDidChange: =>
+ if document.visibilityState is "visible"
+ setTimeout =>
+ if @connectionIsStale() or not @consumer.connection.isOpen()
+ @consumer.connection.reopen()
+ , 200
+
+ toJSON: ->
+ interval = @getInterval()
+ connectionIsStale = @connectionIsStale()
+ {@startedAt, @stoppedAt, @pingedAt, @reconnectAttempts, connectionIsStale, interval}
+
+ now = ->
+ new Date().getTime()
+
+ secondsSince = (time) ->
+ (now() - time) / 1000
+
+ clamp = (number, min, max) ->
+ Math.max(min, Math.min(max, number))
diff --git a/actioncable/lib/assets/javascripts/action_cable/consumer.coffee b/actioncable/lib/assets/javascripts/action_cable/consumer.coffee
new file mode 100644
index 0000000000..5cf8978d77
--- /dev/null
+++ b/actioncable/lib/assets/javascripts/action_cable/consumer.coffee
@@ -0,0 +1,31 @@
+#= require action_cable/connection
+#= require action_cable/connection_monitor
+#= require action_cable/subscriptions
+#= require action_cable/subscription
+
+# The ActionCable.Consumer establishes the connection to a server-side Ruby Connection object. Once established,
+# the ActionCable.ConnectionMonitor will ensure that its properly maintained through heartbeats and checking for stale updates.
+# The Consumer instance is also the gateway to establishing subscriptions to desired channels through the #createSubscription
+# method.
+#
+# The following example shows how this can be setup:
+#
+# @App = {}
+# App.cable = ActionCable.createConsumer "ws://example.com/accounts/1"
+# App.appearance = App.cable.subscriptions.create "AppearanceChannel"
+#
+# For more details on how you'd configure an actual channel subscription, see ActionCable.Subscription.
+class ActionCable.Consumer
+ constructor: (@url) ->
+ @subscriptions = new ActionCable.Subscriptions this
+ @connection = new ActionCable.Connection this
+ @connectionMonitor = new ActionCable.ConnectionMonitor this
+
+ send: (data) ->
+ @connection.send(data)
+
+ inspect: ->
+ JSON.stringify(this, null, 2)
+
+ toJSON: ->
+ {@url, @subscriptions, @connection, @connectionMonitor}
diff --git a/actioncable/lib/assets/javascripts/action_cable/subscription.coffee b/actioncable/lib/assets/javascripts/action_cable/subscription.coffee
new file mode 100644
index 0000000000..339d676933
--- /dev/null
+++ b/actioncable/lib/assets/javascripts/action_cable/subscription.coffee
@@ -0,0 +1,68 @@
+# A new subscription is created through the ActionCable.Subscriptions instance available on the consumer.
+# It provides a number of callbacks and a method for calling remote procedure calls on the corresponding
+# Channel instance on the server side.
+#
+# An example demonstrates the basic functionality:
+#
+# App.appearance = App.cable.subscriptions.create "AppearanceChannel",
+# connected: ->
+# # Called once the subscription has been successfully completed
+#
+# appear: ->
+# @perform 'appear', appearing_on: @appearingOn()
+#
+# away: ->
+# @perform 'away'
+#
+# appearingOn: ->
+# $('main').data 'appearing-on'
+#
+# The methods #appear and #away forward their intent to the remote AppearanceChannel instance on the server
+# by calling the `@perform` method with the first parameter being the action (which maps to AppearanceChannel#appear/away).
+# The second parameter is a hash that'll get JSON encoded and made available on the server in the data parameter.
+#
+# This is how the server component would look:
+#
+# class AppearanceChannel < ApplicationActionCable::Channel
+# def subscribed
+# current_user.appear
+# end
+#
+# def unsubscribed
+# current_user.disappear
+# end
+#
+# def appear(data)
+# current_user.appear on: data['appearing_on']
+# end
+#
+# def away
+# current_user.away
+# end
+# end
+#
+# The "AppearanceChannel" name is automatically mapped between the client-side subscription creation and the server-side Ruby class name.
+# The AppearanceChannel#appear/away public methods are exposed automatically to client-side invocation through the @perform method.
+class ActionCable.Subscription
+ constructor: (@subscriptions, params = {}, mixin) ->
+ @identifier = JSON.stringify(params)
+ extend(this, mixin)
+ @subscriptions.add(this)
+ @consumer = @subscriptions.consumer
+
+ # Perform a channel action with the optional data passed as an attribute
+ perform: (action, data = {}) ->
+ data.action = action
+ @send(data)
+
+ send: (data) ->
+ @consumer.send(command: "message", identifier: @identifier, data: JSON.stringify(data))
+
+ unsubscribe: ->
+ @subscriptions.remove(this)
+
+ extend = (object, properties) ->
+ if properties?
+ for key, value of properties
+ object[key] = value
+ object
diff --git a/actioncable/lib/assets/javascripts/action_cable/subscriptions.coffee b/actioncable/lib/assets/javascripts/action_cable/subscriptions.coffee
new file mode 100644
index 0000000000..0316f76a24
--- /dev/null
+++ b/actioncable/lib/assets/javascripts/action_cable/subscriptions.coffee
@@ -0,0 +1,78 @@
+# Collection class for creating (and internally managing) channel subscriptions. The only method intended to be triggered by the user
+# us ActionCable.Subscriptions#create, and it should be called through the consumer like so:
+#
+# @App = {}
+# App.cable = ActionCable.createConsumer "ws://example.com/accounts/1"
+# App.appearance = App.cable.subscriptions.create "AppearanceChannel"
+#
+# For more details on how you'd configure an actual channel subscription, see ActionCable.Subscription.
+class ActionCable.Subscriptions
+ constructor: (@consumer) ->
+ @subscriptions = []
+ @history = []
+
+ create: (channelName, mixin) ->
+ channel = channelName
+ params = if typeof channel is "object" then channel else {channel}
+ new ActionCable.Subscription this, params, mixin
+
+ # Private
+
+ add: (subscription) ->
+ @subscriptions.push(subscription)
+ @notify(subscription, "initialized")
+ @sendCommand(subscription, "subscribe")
+
+ remove: (subscription) ->
+ @forget(subscription)
+
+ unless @findAll(subscription.identifier).length
+ @sendCommand(subscription, "unsubscribe")
+
+ reject: (identifier) ->
+ for subscription in @findAll(identifier)
+ @forget(subscription)
+ @notify(subscription, "rejected")
+
+ forget: (subscription) ->
+ @subscriptions = (s for s in @subscriptions when s isnt subscription)
+
+ findAll: (identifier) ->
+ s for s in @subscriptions when s.identifier is identifier
+
+ reload: ->
+ for subscription in @subscriptions
+ @sendCommand(subscription, "subscribe")
+
+ notifyAll: (callbackName, args...) ->
+ for subscription in @subscriptions
+ @notify(subscription, callbackName, args...)
+
+ notify: (subscription, callbackName, args...) ->
+ if typeof subscription is "string"
+ subscriptions = @findAll(subscription)
+ else
+ subscriptions = [subscription]
+
+ for subscription in subscriptions
+ subscription[callbackName]?(args...)
+
+ if callbackName in ["initialized", "connected", "disconnected", "rejected"]
+ {identifier} = subscription
+ @record(notification: {identifier, callbackName, args})
+
+ sendCommand: (subscription, command) ->
+ {identifier} = subscription
+ if identifier is ActionCable.INTERNAL.identifiers.ping
+ @consumer.connection.isOpen()
+ else
+ @consumer.send({command, identifier})
+
+ record: (data) ->
+ data.time = new Date()
+ @history = @history.slice(-19)
+ @history.push(data)
+
+ toJSON: ->
+ history: @history
+ identifiers: (subscription.identifier for subscription in @subscriptions)
diff --git a/actioncable/lib/rails/generators/channel/USAGE b/actioncable/lib/rails/generators/channel/USAGE
new file mode 100644
index 0000000000..27a934c689
--- /dev/null
+++ b/actioncable/lib/rails/generators/channel/USAGE
@@ -0,0 +1,14 @@
+Description:
+============
+ Stubs out a new cable channel for the server (in Ruby) and client (in CoffeeScript).
+ Pass the channel name, either CamelCased or under_scored, and an optional list of channel actions as arguments.
+
+ Note: Turn on the cable connection in app/assets/javascript/cable.coffee after generating any channels.
+
+Example:
+========
+ rails generate channel Chat speak
+
+ creates a Chat channel class and CoffeeScript asset:
+ Channel: app/channels/chat_channel.rb
+ Assets: app/assets/javascript/channels/chat.coffee
diff --git a/actioncable/lib/rails/generators/channel/channel_generator.rb b/actioncable/lib/rails/generators/channel/channel_generator.rb
new file mode 100644
index 0000000000..2f37d8055b
--- /dev/null
+++ b/actioncable/lib/rails/generators/channel/channel_generator.rb
@@ -0,0 +1,21 @@
+module Rails
+ module Generators
+ class ChannelGenerator < NamedBase
+ source_root File.expand_path("../templates", __FILE__)
+
+ argument :actions, type: :array, default: [], banner: "method method"
+
+ check_class_collision suffix: "Channel"
+
+ def create_channel_file
+ template "channel.rb", File.join('app/channels', class_path, "#{file_name}_channel.rb")
+ template "assets/channel.coffee", File.join('app/assets/javascripts/channels', class_path, "#{file_name}.coffee")
+ end
+
+ protected
+ def file_name
+ @_file_name ||= super.gsub(/\_channel/i, '')
+ end
+ end
+ end
+end
diff --git a/actioncable/lib/rails/generators/channel/templates/assets/channel.coffee b/actioncable/lib/rails/generators/channel/templates/assets/channel.coffee
new file mode 100644
index 0000000000..5467811aba
--- /dev/null
+++ b/actioncable/lib/rails/generators/channel/templates/assets/channel.coffee
@@ -0,0 +1,14 @@
+App.<%= class_name.underscore %> = App.cable.subscriptions.create "<%= class_name %>Channel",
+ connected: ->
+ # Called when the subscription is ready for use on the server
+
+ disconnected: ->
+ # Called when the subscription has been terminated by the server
+
+ received: (data) ->
+ # Called when there's incoming data on the websocket for this channel
+<% actions.each do |action| -%>
+
+ <%= action %>: ->
+ @perform '<%= action %>'
+<% end -%>
diff --git a/actioncable/lib/rails/generators/channel/templates/channel.rb b/actioncable/lib/rails/generators/channel/templates/channel.rb
new file mode 100644
index 0000000000..6cf04ee61f
--- /dev/null
+++ b/actioncable/lib/rails/generators/channel/templates/channel.rb
@@ -0,0 +1,17 @@
+# Be sure to restart your server when you modify this file. Action Cable runs in an EventMachine loop that does not support auto reloading.
+<% module_namespacing do -%>
+class <%= class_name %>Channel < ApplicationCable::Channel
+ def subscribed
+ # stream_from "some_channel"
+ end
+
+ def unsubscribed
+ # Any cleanup needed when channel is unsubscribed
+ end
+<% actions.each do |action| -%>
+
+ def <%= action %>
+ end
+<% end -%>
+end
+<% end -%>
diff --git a/actioncable/test/channel/base_test.rb b/actioncable/test/channel/base_test.rb
new file mode 100644
index 0000000000..d41bf3064b
--- /dev/null
+++ b/actioncable/test/channel/base_test.rb
@@ -0,0 +1,184 @@
+require 'test_helper'
+require 'stubs/test_connection'
+require 'stubs/room'
+
+class ActionCable::Channel::BaseTest < ActiveSupport::TestCase
+ class ActionCable::Channel::Base
+ def kick
+ @last_action = [ :kick ]
+ end
+
+ def topic
+ end
+ end
+
+ class BasicChannel < ActionCable::Channel::Base
+ def chatters
+ @last_action = [ :chatters ]
+ end
+ end
+
+ class ChatChannel < BasicChannel
+ attr_reader :room, :last_action
+ after_subscribe :toggle_subscribed
+ after_unsubscribe :toggle_subscribed
+
+ def initialize(*)
+ @subscribed = false
+ super
+ end
+
+ def subscribed
+ @room = Room.new params[:id]
+ @actions = []
+ end
+
+ def unsubscribed
+ @room = nil
+ end
+
+ def toggle_subscribed
+ @subscribed = !@subscribed
+ end
+
+ def leave
+ @last_action = [ :leave ]
+ end
+
+ def speak(data)
+ @last_action = [ :speak, data ]
+ end
+
+ def topic(data)
+ @last_action = [ :topic, data ]
+ end
+
+ def subscribed?
+ @subscribed
+ end
+
+ def get_latest
+ transmit data: 'latest'
+ end
+
+ def receive
+ @last_action = [ :receive ]
+ end
+
+ private
+ def rm_rf
+ @last_action = [ :rm_rf ]
+ end
+ end
+
+ setup do
+ @user = User.new "lifo"
+ @connection = TestConnection.new(@user)
+ @channel = ChatChannel.new @connection, "{id: 1}", { id: 1 }
+ end
+
+ test "should subscribe to a channel on initialize" do
+ assert_equal 1, @channel.room.id
+ end
+
+ test "on subscribe callbacks" do
+ assert @channel.subscribed
+ end
+
+ test "channel params" do
+ assert_equal({ id: 1 }, @channel.params)
+ end
+
+ test "unsubscribing from a channel" do
+ assert @channel.room
+ assert @channel.subscribed?
+
+ @channel.unsubscribe_from_channel
+
+ assert ! @channel.room
+ assert ! @channel.subscribed?
+ end
+
+ test "connection identifiers" do
+ assert_equal @user.name, @channel.current_user.name
+ end
+
+ test "callable action without any argument" do
+ @channel.perform_action 'action' => :leave
+ assert_equal [ :leave ], @channel.last_action
+ end
+
+ test "callable action with arguments" do
+ data = { 'action' => :speak, 'content' => "Hello World" }
+
+ @channel.perform_action data
+ assert_equal [ :speak, data ], @channel.last_action
+ end
+
+ test "should not dispatch a private method" do
+ @channel.perform_action 'action' => :rm_rf
+ assert_nil @channel.last_action
+ end
+
+ test "should not dispatch a public method defined on Base" do
+ @channel.perform_action 'action' => :kick
+ assert_nil @channel.last_action
+ end
+
+ test "should dispatch a public method defined on Base and redefined on channel" do
+ data = { 'action' => :topic, 'content' => "This is Sparta!" }
+
+ @channel.perform_action data
+ assert_equal [ :topic, data ], @channel.last_action
+ end
+
+ test "should dispatch calling a public method defined in an ancestor" do
+ @channel.perform_action 'action' => :chatters
+ assert_equal [ :chatters ], @channel.last_action
+ end
+
+ test "should dispatch receive action when perform_action is called with empty action" do
+ data = { 'content' => 'hello' }
+ @channel.perform_action data
+ assert_equal [ :receive ], @channel.last_action
+ end
+
+ test "transmitting data" do
+ @channel.perform_action 'action' => :get_latest
+
+ expected = ActiveSupport::JSON.encode "identifier" => "{id: 1}", "message" => { "data" => "latest" }
+ assert_equal expected, @connection.last_transmission
+ end
+
+ test "subscription confirmation" do
+ expected = ActiveSupport::JSON.encode "identifier" => "{id: 1}", "type" => "confirm_subscription"
+ assert_equal expected, @connection.last_transmission
+ end
+
+ test "actions available on Channel" do
+ available_actions = %w(room last_action subscribed unsubscribed toggle_subscribed leave speak subscribed? get_latest receive chatters topic).to_set
+ assert_equal available_actions, ChatChannel.action_methods
+ end
+
+ test "invalid action on Channel" do
+ assert_logged("Unable to process ActionCable::Channel::BaseTest::ChatChannel#invalid_action") do
+ @channel.perform_action 'action' => :invalid_action
+ end
+ end
+
+ private
+ def assert_logged(message)
+ old_logger = @connection.logger
+ log = StringIO.new
+ @connection.instance_variable_set(:@logger, Logger.new(log))
+
+ begin
+ yield
+
+ log.rewind
+ assert_match message, log.read
+ ensure
+ @connection.instance_variable_set(:@logger, old_logger)
+ end
+ end
+end
diff --git a/actioncable/test/channel/broadcasting_test.rb b/actioncable/test/channel/broadcasting_test.rb
new file mode 100644
index 0000000000..1de04243e5
--- /dev/null
+++ b/actioncable/test/channel/broadcasting_test.rb
@@ -0,0 +1,29 @@
+require 'test_helper'
+require 'stubs/test_connection'
+require 'stubs/room'
+
+class ActionCable::Channel::BroadcastingTest < ActiveSupport::TestCase
+ class ChatChannel < ActionCable::Channel::Base
+ end
+
+ setup do
+ @connection = TestConnection.new
+ end
+
+ test "broadcasts_to" do
+ ActionCable.stubs(:server).returns mock().tap { |m| m.expects(:broadcast).with('action_cable:channel:broadcasting_test:chat:Room#1-Campfire', "Hello World") }
+ ChatChannel.broadcast_to(Room.new(1), "Hello World")
+ end
+
+ test "broadcasting_for with an object" do
+ assert_equal "Room#1-Campfire", ChatChannel.broadcasting_for(Room.new(1))
+ end
+
+ test "broadcasting_for with an array" do
+ assert_equal "Room#1-Campfire:Room#2-Campfire", ChatChannel.broadcasting_for([ Room.new(1), Room.new(2) ])
+ end
+
+ test "broadcasting_for with a string" do
+ assert_equal "hello", ChatChannel.broadcasting_for("hello")
+ end
+end
diff --git a/actioncable/test/channel/naming_test.rb b/actioncable/test/channel/naming_test.rb
new file mode 100644
index 0000000000..89ef6ad8b0
--- /dev/null
+++ b/actioncable/test/channel/naming_test.rb
@@ -0,0 +1,10 @@
+require 'test_helper'
+
+class ActionCable::Channel::NamingTest < ActiveSupport::TestCase
+ class ChatChannel < ActionCable::Channel::Base
+ end
+
+ test "channel_name" do
+ assert_equal "action_cable:channel:naming_test:chat", ChatChannel.channel_name
+ end
+end
diff --git a/actioncable/test/channel/periodic_timers_test.rb b/actioncable/test/channel/periodic_timers_test.rb
new file mode 100644
index 0000000000..1590a12f09
--- /dev/null
+++ b/actioncable/test/channel/periodic_timers_test.rb
@@ -0,0 +1,40 @@
+require 'test_helper'
+require 'stubs/test_connection'
+require 'stubs/room'
+
+class ActionCable::Channel::PeriodicTimersTest < ActiveSupport::TestCase
+ class ChatChannel < ActionCable::Channel::Base
+ periodically -> { ping }, every: 5
+ periodically :send_updates, every: 1
+
+ private
+ def ping
+ end
+ end
+
+ setup do
+ @connection = TestConnection.new
+ end
+
+ test "periodic timers definition" do
+ timers = ChatChannel.periodic_timers
+
+ assert_equal 2, timers.size
+
+ first_timer = timers[0]
+ assert_kind_of Proc, first_timer[0]
+ assert_equal 5, first_timer[1][:every]
+
+ second_timer = timers[1]
+ assert_equal :send_updates, second_timer[0]
+ assert_equal 1, second_timer[1][:every]
+ end
+
+ test "timer start and stop" do
+ EventMachine::PeriodicTimer.expects(:new).times(2).returns(true)
+ channel = ChatChannel.new @connection, "{id: 1}", { id: 1 }
+
+ channel.expects(:stop_periodic_timers).once
+ channel.unsubscribe_from_channel
+ end
+end
diff --git a/actioncable/test/channel/rejection_test.rb b/actioncable/test/channel/rejection_test.rb
new file mode 100644
index 0000000000..aa93396d44
--- /dev/null
+++ b/actioncable/test/channel/rejection_test.rb
@@ -0,0 +1,25 @@
+require 'test_helper'
+require 'stubs/test_connection'
+require 'stubs/room'
+
+class ActionCable::Channel::RejectionTest < ActiveSupport::TestCase
+ class SecretChannel < ActionCable::Channel::Base
+ def subscribed
+ reject if params[:id] > 0
+ end
+ end
+
+ setup do
+ @user = User.new "lifo"
+ @connection = TestConnection.new(@user)
+ end
+
+ test "subscription rejection" do
+ @connection.expects(:subscriptions).returns mock().tap { |m| m.expects(:remove_subscription).with instance_of(SecretChannel) }
+ @channel = SecretChannel.new @connection, "{id: 1}", { id: 1 }
+
+ expected = ActiveSupport::JSON.encode "identifier" => "{id: 1}", "type" => "reject_subscription"
+ assert_equal expected, @connection.last_transmission
+ end
+
+end
diff --git a/actioncable/test/channel/stream_test.rb b/actioncable/test/channel/stream_test.rb
new file mode 100644
index 0000000000..1424ded04c
--- /dev/null
+++ b/actioncable/test/channel/stream_test.rb
@@ -0,0 +1,80 @@
+require 'test_helper'
+require 'stubs/test_connection'
+require 'stubs/room'
+
+class ActionCable::Channel::StreamTest < ActionCable::TestCase
+ class ChatChannel < ActionCable::Channel::Base
+ def subscribed
+ if params[:id]
+ @room = Room.new params[:id]
+ stream_from "test_room_#{@room.id}"
+ end
+ end
+
+ def send_confirmation
+ transmit_subscription_confirmation
+ end
+
+ end
+
+ test "streaming start and stop" do
+ run_in_eventmachine do
+ connection = TestConnection.new
+ connection.expects(:pubsub).returns mock().tap { |m| m.expects(:subscribe).with("test_room_1").returns stub_everything(:pubsub) }
+ channel = ChatChannel.new connection, "{id: 1}", { id: 1 }
+
+ connection.expects(:pubsub).returns mock().tap { |m| m.expects(:unsubscribe_proc) }
+ channel.unsubscribe_from_channel
+ end
+ end
+
+ test "stream_for" do
+ run_in_eventmachine do
+ connection = TestConnection.new
+ EM.next_tick do
+ connection.expects(:pubsub).returns mock().tap { |m| m.expects(:subscribe).with("action_cable:channel:stream_test:chat:Room#1-Campfire").returns stub_everything(:pubsub) }
+ end
+
+ channel = ChatChannel.new connection, ""
+ channel.stream_for Room.new(1)
+ end
+ end
+
+ test "stream_from subscription confirmation" do
+ EM.run do
+ connection = TestConnection.new
+ connection.expects(:pubsub).returns EM::Hiredis.connect.pubsub
+
+ ChatChannel.new connection, "{id: 1}", { id: 1 }
+ assert_nil connection.last_transmission
+
+ EM::Timer.new(0.1) do
+ expected = ActiveSupport::JSON.encode "identifier" => "{id: 1}", "type" => "confirm_subscription"
+ assert_equal expected, connection.last_transmission, "Did not receive subscription confirmation within 0.1s"
+
+ EM.run_deferred_callbacks
+ EM.stop
+ end
+ end
+ end
+
+ test "subscription confirmation should only be sent out once" do
+ EM.run do
+ connection = TestConnection.new
+ connection.stubs(:pubsub).returns EM::Hiredis.connect.pubsub
+
+ channel = ChatChannel.new connection, "test_channel"
+ channel.send_confirmation
+ channel.send_confirmation
+
+ EM.run_deferred_callbacks
+
+ expected = ActiveSupport::JSON.encode "identifier" => "test_channel", "type" => "confirm_subscription"
+ assert_equal expected, connection.last_transmission, "Did not receive subscription confirmation"
+
+ assert_equal 1, connection.transmissions.size
+ EM.stop
+ end
+ end
+
+end
diff --git a/actioncable/test/connection/authorization_test.rb b/actioncable/test/connection/authorization_test.rb
new file mode 100644
index 0000000000..68668b2835
--- /dev/null
+++ b/actioncable/test/connection/authorization_test.rb
@@ -0,0 +1,32 @@
+require 'test_helper'
+require 'stubs/test_server'
+
+class ActionCable::Connection::AuthorizationTest < ActionCable::TestCase
+ class Connection < ActionCable::Connection::Base
+ attr_reader :websocket
+
+ def connect
+ reject_unauthorized_connection
+ end
+
+ def send_async(method, *args)
+ # Bypass Celluloid
+ send method, *args
+ end
+ end
+
+ test "unauthorized connection" do
+ run_in_eventmachine do
+ server = TestServer.new
+ server.config.allowed_request_origins = %w( http://rubyonrails.com )
+
+ env = Rack::MockRequest.env_for "/test", 'HTTP_CONNECTION' => 'upgrade', 'HTTP_UPGRADE' => 'websocket',
+ 'HTTP_ORIGIN' => 'http://rubyonrails.com'
+
+ connection = Connection.new(server, env)
+ connection.websocket.expects(:close)
+
+ connection.process
+ end
+ end
+end
diff --git a/actioncable/test/connection/base_test.rb b/actioncable/test/connection/base_test.rb
new file mode 100644
index 0000000000..da6041db4a
--- /dev/null
+++ b/actioncable/test/connection/base_test.rb
@@ -0,0 +1,118 @@
+require 'test_helper'
+require 'stubs/test_server'
+
+class ActionCable::Connection::BaseTest < ActionCable::TestCase
+ class Connection < ActionCable::Connection::Base
+ attr_reader :websocket, :subscriptions, :message_buffer, :connected
+
+ def connect
+ @connected = true
+ end
+
+ def disconnect
+ @connected = false
+ end
+
+ def send_async(method, *args)
+ # Bypass Celluloid
+ send method, *args
+ end
+ end
+
+ setup do
+ @server = TestServer.new
+ @server.config.allowed_request_origins = %w( http://rubyonrails.com )
+ end
+
+ test "making a connection with invalid headers" do
+ run_in_eventmachine do
+ connection = ActionCable::Connection::Base.new(@server, Rack::MockRequest.env_for("/test"))
+ response = connection.process
+ assert_equal 404, response[0]
+ end
+ end
+
+ test "websocket connection" do
+ run_in_eventmachine do
+ connection = open_connection
+ connection.process
+
+ assert connection.websocket.possible?
+ assert connection.websocket.alive?
+ end
+ end
+
+ test "rack response" do
+ run_in_eventmachine do
+ connection = open_connection
+ response = connection.process
+
+ assert_equal [ -1, {}, [] ], response
+ end
+ end
+
+ test "on connection open" do
+ run_in_eventmachine do
+ connection = open_connection
+ connection.process
+
+ connection.websocket.expects(:transmit).with(regexp_matches(/\_ping/))
+ connection.message_buffer.expects(:process!)
+
+ # Allow EM to run on_open callback
+ EM.next_tick do
+ assert_equal [ connection ], @server.connections
+ assert connection.connected
+ end
+ end
+ end
+
+ test "on connection close" do
+ run_in_eventmachine do
+ connection = open_connection
+ connection.process
+
+ # Setup the connection
+ EventMachine.stubs(:add_periodic_timer).returns(true)
+ connection.send :on_open
+ assert connection.connected
+
+ connection.subscriptions.expects(:unsubscribe_from_all)
+ connection.send :on_close
+
+ assert ! connection.connected
+ assert_equal [], @server.connections
+ end
+ end
+
+ test "connection statistics" do
+ run_in_eventmachine do
+ connection = open_connection
+ connection.process
+
+ statistics = connection.statistics
+
+ assert statistics[:identifier].blank?
+ assert_kind_of Time, statistics[:started_at]
+ assert_equal [], statistics[:subscriptions]
+ end
+ end
+
+ test "explicitly closing a connection" do
+ run_in_eventmachine do
+ connection = open_connection
+ connection.process
+
+ connection.websocket.expects(:close)
+ connection.close
+ end
+ end
+
+ private
+ def open_connection
+ env = Rack::MockRequest.env_for "/test", 'HTTP_CONNECTION' => 'upgrade', 'HTTP_UPGRADE' => 'websocket',
+ 'HTTP_ORIGIN' => 'http://rubyonrails.com'
+
+ Connection.new(@server, env)
+ end
+end
diff --git a/actioncable/test/connection/cross_site_forgery_test.rb b/actioncable/test/connection/cross_site_forgery_test.rb
new file mode 100644
index 0000000000..d445e08f2a
--- /dev/null
+++ b/actioncable/test/connection/cross_site_forgery_test.rb
@@ -0,0 +1,82 @@
+require 'test_helper'
+require 'stubs/test_server'
+
+class ActionCable::Connection::CrossSiteForgeryTest < ActionCable::TestCase
+ HOST = 'rubyonrails.com'
+
+ class Connection < ActionCable::Connection::Base
+ def send_async(method, *args)
+ # Bypass Celluloid
+ send method, *args
+ end
+ end
+
+ setup do
+ @server = TestServer.new
+ @server.config.allowed_request_origins = %w( http://rubyonrails.com )
+ end
+
+ teardown do
+ @server.config.disable_request_forgery_protection = false
+ @server.config.allowed_request_origins = []
+ end
+
+ test "disable forgery protection" do
+ @server.config.disable_request_forgery_protection = true
+ assert_origin_allowed 'http://rubyonrails.com'
+ assert_origin_allowed 'http://hax.com'
+ end
+
+ test "explicitly specified a single allowed origin" do
+ @server.config.allowed_request_origins = 'http://hax.com'
+ assert_origin_not_allowed 'http://rubyonrails.com'
+ assert_origin_allowed 'http://hax.com'
+ end
+
+ test "explicitly specified multiple allowed origins" do
+ @server.config.allowed_request_origins = %w( http://rubyonrails.com http://www.rubyonrails.com )
+ assert_origin_allowed 'http://rubyonrails.com'
+ assert_origin_allowed 'http://www.rubyonrails.com'
+ assert_origin_not_allowed 'http://hax.com'
+ end
+
+ test "explicitly specified a single regexp allowed origin" do
+ @server.config.allowed_request_origins = /.*ha.*/
+ assert_origin_not_allowed 'http://rubyonrails.com'
+ assert_origin_allowed 'http://hax.com'
+ end
+
+ test "explicitly specified multiple regexp allowed origins" do
+ @server.config.allowed_request_origins = [/http:\/\/ruby.*/, /.*rai.s.*com/, 'string' ]
+ assert_origin_allowed 'http://rubyonrails.com'
+ assert_origin_allowed 'http://www.rubyonrails.com'
+ assert_origin_not_allowed 'http://hax.com'
+ assert_origin_not_allowed 'http://rails.co.uk'
+ end
+
+ private
+ def assert_origin_allowed(origin)
+ response = connect_with_origin origin
+ assert_equal(-1, response[0])
+ end
+
+ def assert_origin_not_allowed(origin)
+ response = connect_with_origin origin
+ assert_equal 404, response[0]
+ end
+
+ def connect_with_origin(origin)
+ response = nil
+
+ run_in_eventmachine do
+ response = Connection.new(@server, env_for_origin(origin)).process
+ end
+
+ response
+ end
+
+ def env_for_origin(origin)
+ Rack::MockRequest.env_for "/test", 'HTTP_CONNECTION' => 'upgrade', 'HTTP_UPGRADE' => 'websocket', 'SERVER_NAME' => HOST,
+ 'HTTP_ORIGIN' => origin
+ end
+end
diff --git a/actioncable/test/connection/identifier_test.rb b/actioncable/test/connection/identifier_test.rb
new file mode 100644
index 0000000000..02e6b21845
--- /dev/null
+++ b/actioncable/test/connection/identifier_test.rb
@@ -0,0 +1,77 @@
+require 'test_helper'
+require 'stubs/test_server'
+require 'stubs/user'
+
+class ActionCable::Connection::IdentifierTest < ActionCable::TestCase
+ class Connection < ActionCable::Connection::Base
+ identified_by :current_user
+ attr_reader :websocket
+
+ public :process_internal_message
+
+ def connect
+ self.current_user = User.new "lifo"
+ end
+ end
+
+ test "connection identifier" do
+ run_in_eventmachine do
+ open_connection_with_stubbed_pubsub
+ assert_equal "User#lifo", @connection.connection_identifier
+ end
+ end
+
+ test "should subscribe to internal channel on open and unsubscribe on close" do
+ run_in_eventmachine do
+ pubsub = mock('pubsub')
+ pubsub.expects(:subscribe).with('action_cable/User#lifo')
+ pubsub.expects(:unsubscribe_proc).with('action_cable/User#lifo', kind_of(Proc))
+
+ server = TestServer.new
+ server.stubs(:pubsub).returns(pubsub)
+
+ open_connection server: server
+ close_connection
+ end
+ end
+
+ test "processing disconnect message" do
+ run_in_eventmachine do
+ open_connection_with_stubbed_pubsub
+
+ @connection.websocket.expects(:close)
+ message = ActiveSupport::JSON.encode('type' => 'disconnect')
+ @connection.process_internal_message message
+ end
+ end
+
+ test "processing invalid message" do
+ run_in_eventmachine do
+ open_connection_with_stubbed_pubsub
+
+ @connection.websocket.expects(:close).never
+ message = ActiveSupport::JSON.encode('type' => 'unknown')
+ @connection.process_internal_message message
+ end
+ end
+
+ protected
+ def open_connection_with_stubbed_pubsub
+ server = TestServer.new
+ server.stubs(:pubsub).returns(stub_everything('pubsub'))
+
+ open_connection server: server
+ end
+
+ def open_connection(server:)
+ env = Rack::MockRequest.env_for "/test", 'HTTP_CONNECTION' => 'upgrade', 'HTTP_UPGRADE' => 'websocket'
+ @connection = Connection.new(server, env)
+
+ @connection.process
+ @connection.send :on_open
+ end
+
+ def close_connection
+ @connection.send :on_close
+ end
+end
diff --git a/actioncable/test/connection/multiple_identifiers_test.rb b/actioncable/test/connection/multiple_identifiers_test.rb
new file mode 100644
index 0000000000..55a9f96cb3
--- /dev/null
+++ b/actioncable/test/connection/multiple_identifiers_test.rb
@@ -0,0 +1,41 @@
+require 'test_helper'
+require 'stubs/test_server'
+require 'stubs/user'
+
+class ActionCable::Connection::MultipleIdentifiersTest < ActionCable::TestCase
+ class Connection < ActionCable::Connection::Base
+ identified_by :current_user, :current_room
+
+ def connect
+ self.current_user = User.new "lifo"
+ self.current_room = Room.new "my", "room"
+ end
+ end
+
+ test "multiple connection identifiers" do
+ run_in_eventmachine do
+ open_connection_with_stubbed_pubsub
+ assert_equal "Room#my-room:User#lifo", @connection.connection_identifier
+ end
+ end
+
+ protected
+ def open_connection_with_stubbed_pubsub
+ server = TestServer.new
+ server.stubs(:pubsub).returns(stub_everything('pubsub'))
+
+ open_connection server: server
+ end
+
+ def open_connection(server:)
+ env = Rack::MockRequest.env_for "/test", 'HTTP_CONNECTION' => 'upgrade', 'HTTP_UPGRADE' => 'websocket'
+ @connection = Connection.new(server, env)
+
+ @connection.process
+ @connection.send :on_open
+ end
+
+ def close_connection
+ @connection.send :on_close
+ end
+end
diff --git a/actioncable/test/connection/string_identifier_test.rb b/actioncable/test/connection/string_identifier_test.rb
new file mode 100644
index 0000000000..ab69df57b3
--- /dev/null
+++ b/actioncable/test/connection/string_identifier_test.rb
@@ -0,0 +1,44 @@
+require 'test_helper'
+require 'stubs/test_server'
+
+class ActionCable::Connection::StringIdentifierTest < ActionCable::TestCase
+ class Connection < ActionCable::Connection::Base
+ identified_by :current_token
+
+ def connect
+ self.current_token = "random-string"
+ end
+
+ def send_async(method, *args)
+ # Bypass Celluloid
+ send method, *args
+ end
+ end
+
+ test "connection identifier" do
+ run_in_eventmachine do
+ open_connection_with_stubbed_pubsub
+ assert_equal "random-string", @connection.connection_identifier
+ end
+ end
+
+ protected
+ def open_connection_with_stubbed_pubsub
+ @server = TestServer.new
+ @server.stubs(:pubsub).returns(stub_everything('pubsub'))
+
+ open_connection
+ end
+
+ def open_connection
+ env = Rack::MockRequest.env_for "/test", 'HTTP_CONNECTION' => 'upgrade', 'HTTP_UPGRADE' => 'websocket'
+ @connection = Connection.new(@server, env)
+
+ @connection.process
+ @connection.send :on_open
+ end
+
+ def close_connection
+ @connection.send :on_close
+ end
+end
diff --git a/actioncable/test/connection/subscriptions_test.rb b/actioncable/test/connection/subscriptions_test.rb
new file mode 100644
index 0000000000..4f6760827e
--- /dev/null
+++ b/actioncable/test/connection/subscriptions_test.rb
@@ -0,0 +1,116 @@
+require 'test_helper'
+
+class ActionCable::Connection::SubscriptionsTest < ActionCable::TestCase
+ class Connection < ActionCable::Connection::Base
+ attr_reader :websocket
+
+ def send_async(method, *args)
+ # Bypass Celluloid
+ send method, *args
+ end
+ end
+
+ class ChatChannel < ActionCable::Channel::Base
+ attr_reader :room, :lines
+
+ def subscribed
+ @room = Room.new params[:id]
+ @lines = []
+ end
+
+ def speak(data)
+ @lines << data
+ end
+ end
+
+ setup do
+ @server = TestServer.new
+ @server.stubs(:channel_classes).returns(ChatChannel.name => ChatChannel)
+
+ @chat_identifier = ActiveSupport::JSON.encode(id: 1, channel: 'ActionCable::Connection::SubscriptionsTest::ChatChannel')
+ end
+
+ test "subscribe command" do
+ run_in_eventmachine do
+ setup_connection
+ channel = subscribe_to_chat_channel
+
+ assert_kind_of ChatChannel, channel
+ assert_equal 1, channel.room.id
+ end
+ end
+
+ test "subscribe command without an identifier" do
+ run_in_eventmachine do
+ setup_connection
+
+ @subscriptions.execute_command 'command' => 'subscribe'
+ assert @subscriptions.identifiers.empty?
+ end
+ end
+
+ test "unsubscribe command" do
+ run_in_eventmachine do
+ setup_connection
+ subscribe_to_chat_channel
+
+ channel = subscribe_to_chat_channel
+ channel.expects(:unsubscribe_from_channel)
+
+ @subscriptions.execute_command 'command' => 'unsubscribe', 'identifier' => @chat_identifier
+ assert @subscriptions.identifiers.empty?
+ end
+ end
+
+ test "unsubscribe command without an identifier" do
+ run_in_eventmachine do
+ setup_connection
+
+ @subscriptions.execute_command 'command' => 'unsubscribe'
+ assert @subscriptions.identifiers.empty?
+ end
+ end
+
+ test "message command" do
+ run_in_eventmachine do
+ setup_connection
+ channel = subscribe_to_chat_channel
+
+ data = { 'content' => 'Hello World!', 'action' => 'speak' }
+ @subscriptions.execute_command 'command' => 'message', 'identifier' => @chat_identifier, 'data' => ActiveSupport::JSON.encode(data)
+
+ assert_equal [ data ], channel.lines
+ end
+ end
+
+ test "unsubscrib from all" do
+ run_in_eventmachine do
+ setup_connection
+
+ channel1 = subscribe_to_chat_channel
+
+ channel2_id = ActiveSupport::JSON.encode(id: 2, channel: 'ActionCable::Connection::SubscriptionsTest::ChatChannel')
+ channel2 = subscribe_to_chat_channel(channel2_id)
+
+ channel1.expects(:unsubscribe_from_channel)
+ channel2.expects(:unsubscribe_from_channel)
+
+ @subscriptions.unsubscribe_from_all
+ end
+ end
+
+ private
+ def subscribe_to_chat_channel(identifier = @chat_identifier)
+ @subscriptions.execute_command 'command' => 'subscribe', 'identifier' => identifier
+ assert_equal identifier, @subscriptions.identifiers.last
+
+ @subscriptions.send :find, 'identifier' => identifier
+ end
+
+ def setup_connection
+ env = Rack::MockRequest.env_for "/test", 'HTTP_CONNECTION' => 'upgrade', 'HTTP_UPGRADE' => 'websocket'
+ @connection = Connection.new(@server, env)
+
+ @subscriptions = ActionCable::Connection::Subscriptions.new(@connection)
+ end
+end
diff --git a/actioncable/test/stubs/global_id.rb b/actioncable/test/stubs/global_id.rb
new file mode 100644
index 0000000000..334f0d03e8
--- /dev/null
+++ b/actioncable/test/stubs/global_id.rb
@@ -0,0 +1,8 @@
+class GlobalID
+ attr_reader :uri
+ delegate :to_param, :to_s, to: :uri
+
+ def initialize(gid, options = {})
+ @uri = gid
+ end
+end
diff --git a/actioncable/test/stubs/room.rb b/actioncable/test/stubs/room.rb
new file mode 100644
index 0000000000..cd66a0b687
--- /dev/null
+++ b/actioncable/test/stubs/room.rb
@@ -0,0 +1,16 @@
+class Room
+ attr_reader :id, :name
+
+ def initialize(id, name='Campfire')
+ @id = id
+ @name = name
+ end
+
+ def to_global_id
+ GlobalID.new("Room##{id}-#{name}")
+ end
+
+ def to_gid_param
+ to_global_id.to_param
+ end
+end
diff --git a/actioncable/test/stubs/test_connection.rb b/actioncable/test/stubs/test_connection.rb
new file mode 100644
index 0000000000..384abc5e76
--- /dev/null
+++ b/actioncable/test/stubs/test_connection.rb
@@ -0,0 +1,21 @@
+require 'stubs/user'
+
+class TestConnection
+ attr_reader :identifiers, :logger, :current_user, :transmissions
+
+ def initialize(user = User.new("lifo"))
+ @identifiers = [ :current_user ]
+
+ @current_user = user
+ @logger = ActiveSupport::TaggedLogging.new ActiveSupport::Logger.new(StringIO.new)
+ @transmissions = []
+ end
+
+ def transmit(data)
+ @transmissions << data
+ end
+
+ def last_transmission
+ @transmissions.last
+ end
+end
diff --git a/actioncable/test/stubs/test_server.rb b/actioncable/test/stubs/test_server.rb
new file mode 100644
index 0000000000..f9168f9b78
--- /dev/null
+++ b/actioncable/test/stubs/test_server.rb
@@ -0,0 +1,15 @@
+require 'ostruct'
+
+class TestServer
+ include ActionCable::Server::Connections
+
+ attr_reader :logger, :config
+
+ def initialize
+ @logger = ActiveSupport::TaggedLogging.new ActiveSupport::Logger.new(StringIO.new)
+ @config = OpenStruct.new(log_tags: [])
+ end
+
+ def send_async
+ end
+end
diff --git a/actioncable/test/stubs/user.rb b/actioncable/test/stubs/user.rb
new file mode 100644
index 0000000000..a66b4f87d5
--- /dev/null
+++ b/actioncable/test/stubs/user.rb
@@ -0,0 +1,15 @@
+class User
+ attr_reader :name
+
+ def initialize(name)
+ @name = name
+ end
+
+ def to_global_id
+ GlobalID.new("User##{name}")
+ end
+
+ def to_gid_param
+ to_global_id.to_param
+ end
+end
diff --git a/actioncable/test/test_helper.rb b/actioncable/test/test_helper.rb
new file mode 100644
index 0000000000..12dcd98402
--- /dev/null
+++ b/actioncable/test/test_helper.rb
@@ -0,0 +1,42 @@
+require File.expand_path('../../../load_paths', __FILE__)
+
+require 'action_cable'
+require 'active_support/testing/autorun'
+
+
+require 'puma'
+require 'em-hiredis'
+
+require 'mocha/setup'
+
+require 'rack/mock'
+
+# Require all the stubs and models
+Dir[File.dirname(__FILE__) + '/stubs/*.rb'].each {|file| require file }
+
+$CELLULOID_DEBUG = false
+$CELLULOID_TEST = false
+require 'celluloid'
+Celluloid.logger = Logger.new(StringIO.new)
+
+require 'faye/websocket'
+class << Faye::WebSocket
+ remove_method :ensure_reactor_running
+
+ # We don't want Faye to start the EM reactor in tests because it makes testing much harder.
+ # We want to be able to start and stop EM loop in tests to make things simpler.
+ def ensure_reactor_running
+ # no-op
+ end
+end
+
+class ActionCable::TestCase < ActiveSupport::TestCase
+ def run_in_eventmachine
+ EM.run do
+ yield
+
+ EM.run_deferred_callbacks
+ EM.stop
+ end
+ end
+end
diff --git a/actioncable/test/worker_test.rb b/actioncable/test/worker_test.rb
new file mode 100644
index 0000000000..69c4b6529d
--- /dev/null
+++ b/actioncable/test/worker_test.rb
@@ -0,0 +1,49 @@
+require 'test_helper'
+
+class WorkerTest < ActiveSupport::TestCase
+ class Receiver
+ attr_accessor :last_action
+
+ def run
+ @last_action = :run
+ end
+
+ def process(message)
+ @last_action = [ :process, message ]
+ end
+
+ def connection
+ end
+ end
+
+ setup do
+ Celluloid.boot
+
+ @worker = ActionCable::Server::Worker.new
+ @receiver = Receiver.new
+ end
+
+ teardown do
+ @receiver.last_action = nil
+ end
+
+ test "invoke" do
+ @worker.invoke @receiver, :run
+ assert_equal :run, @receiver.last_action
+ end
+
+ test "invoke with arguments" do
+ @worker.invoke @receiver, :process, "Hello"
+ assert_equal [ :process, "Hello" ], @receiver.last_action
+ end
+
+ test "running periodic timers with a proc" do
+ @worker.run_periodic_timer @receiver, @receiver.method(:run)
+ assert_equal :run, @receiver.last_action
+ end
+
+ test "running periodic timers with a method" do
+ @worker.run_periodic_timer @receiver, :run
+ assert_equal :run, @receiver.last_action
+ end
+end
diff --git a/actionmailer/CHANGELOG.md b/actionmailer/CHANGELOG.md
index 0ecb0235bc..73ce989a5a 100644
--- a/actionmailer/CHANGELOG.md
+++ b/actionmailer/CHANGELOG.md
@@ -1,3 +1,8 @@
+## Rails 5.0.0.beta1 (December 18, 2015) ##
+
+* No changes.
+
+
* `config.force_ssl = true` will set
`config.action_mailer.default_url_options = { protocol: 'https' }`
diff --git a/actionmailer/README.rdoc b/actionmailer/README.rdoc
index e5c2ed8c77..397ebe4201 100644
--- a/actionmailer/README.rdoc
+++ b/actionmailer/README.rdoc
@@ -146,7 +146,7 @@ The Base class has the full list of configuration options. Here's an example:
The latest version of Action Mailer can be installed with RubyGems:
- % gem install actionmailer
+ $ gem install actionmailer
Source code can be downloaded as part of the Rails project on GitHub
@@ -173,4 +173,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/actionmailer/actionmailer.gemspec b/actionmailer/actionmailer.gemspec
index 782b208ef4..fa6043fdd7 100644
--- a/actionmailer/actionmailer.gemspec
+++ b/actionmailer/actionmailer.gemspec
@@ -13,7 +13,7 @@ Gem::Specification.new do |s|
s.author = 'David Heinemeier Hansson'
s.email = 'david@loudthinking.com'
- s.homepage = 'http://www.rubyonrails.org'
+ s.homepage = 'http://rubyonrails.org'
s.files = Dir['CHANGELOG.md', 'README.rdoc', 'MIT-LICENSE', 'lib/**/*']
s.require_path = 'lib'
diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb
index cbd7cec70f..bb3cb1be45 100644
--- a/actionmailer/lib/action_mailer/base.rb
+++ b/actionmailer/lib/action_mailer/base.rb
@@ -464,30 +464,26 @@ module ActionMailer
# Either a class, string or symbol can be passed in as the Observer.
# If a string or symbol is passed in it will be camelized and constantized.
def register_observer(observer)
- delivery_observer = case observer
- when String, Symbol
- observer.to_s.camelize.constantize
- else
- observer
- end
-
- Mail.register_observer(delivery_observer)
+ Mail.register_observer(observer_class_for(observer))
end
# Register an Interceptor which will be called before mail is sent.
# Either a class, string or symbol can be passed in as the Interceptor.
# If a string or symbol is passed in it will be camelized and constantized.
def register_interceptor(interceptor)
- delivery_interceptor = case interceptor
- when String, Symbol
- interceptor.to_s.camelize.constantize
- else
- interceptor
- end
-
- Mail.register_interceptor(delivery_interceptor)
+ Mail.register_interceptor(observer_class_for(interceptor))
end
+ def observer_class_for(value) # :nodoc:
+ case value
+ when String, Symbol
+ value.to_s.camelize.constantize
+ else
+ value
+ end
+ end
+ private :observer_class_for
+
# Returns the name of current mailer. This method is also being used as a path for a view lookup.
# If this is an anonymous mailer, this method will return +anonymous+ instead.
def mailer_name
@@ -545,10 +541,6 @@ module ActionMailer
end
end
- def respond_to?(method, include_private = false) #:nodoc:
- super || action_methods.include?(method.to_s)
- end
-
protected
def set_payload_for_mail(payload, mail) #:nodoc:
@@ -570,6 +562,12 @@ module ActionMailer
super
end
end
+
+ private
+
+ def respond_to_missing?(method, include_all = false) #:nodoc:
+ action_methods.include?(method.to_s)
+ end
end
attr_internal :message
@@ -660,18 +658,18 @@ module ActionMailer
#
# mail.attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
#
- # If you do this, then Mail will take the file name and work out the mime type
- # set the Content-Type, Content-Disposition, Content-Transfer-Encoding and
- # base64 encode the contents of the attachment all for you.
+ # If you do this, then Mail will take the file name and work out the mime type.
+ # It will also set the Content-Type, Content-Disposition, Content-Transfer-Encoding
+ # and encode the contents of the attachment in Base64.
#
# You can also specify overrides if you want by passing a hash instead of a string:
#
# mail.attachments['filename.jpg'] = {mime_type: 'application/x-gzip',
# content: File.read('/path/to/filename.jpg')}
#
- # If you want to use a different encoding than Base64, you can pass an encoding in,
- # but then it is up to you to pass in the content pre-encoded, and don't expect
- # Mail to know how to decode this data:
+ # If you want to use encoding other than Base64 then you will need to pass encoding
+ # type along with the pre-encoded content as Mail doesn't know how to decode the
+ # data:
#
# file_content = SpecialEncode(File.read('/path/to/filename.jpg'))
# mail.attachments['filename.jpg'] = {mime_type: 'application/x-gzip',
@@ -796,52 +794,40 @@ module ActionMailer
# end
#
def mail(headers = {}, &block)
- return @_message if @_mail_was_called && headers.blank? && !block
-
- m = @_message
+ return message if @_mail_was_called && headers.blank? && !block
# At the beginning, do not consider class default for content_type
content_type = headers[:content_type]
- # Call all the procs (if any)
- default_values = {}
- self.class.default.each do |k,v|
- default_values[k] = v.is_a?(Proc) ? instance_eval(&v) : v
- end
-
- # Handle defaults
- headers = headers.reverse_merge(default_values)
- headers[:subject] ||= default_i18n_subject
+ headers = apply_defaults(headers)
# Apply charset at the beginning so all fields are properly quoted
- m.charset = charset = headers[:charset]
+ message.charset = charset = headers[:charset]
# Set configure delivery behavior
- wrap_delivery_behavior!(headers.delete(:delivery_method), headers.delete(:delivery_method_options))
+ wrap_delivery_behavior!(headers[:delivery_method], headers[:delivery_method_options])
- # Assign all headers except parts_order, content_type, body, template_name, and template_path
- assignable = headers.except(:parts_order, :content_type, :body, :template_name, :template_path)
- assignable.each { |k, v| m[k] = v }
+ assign_headers_to_message(message, headers)
# Render the templates and blocks
responses = collect_responses(headers, &block)
@_mail_was_called = true
- create_parts_from_responses(m, responses)
+ create_parts_from_responses(message, responses)
# Setup content type, reapply charset and handle parts order
- m.content_type = set_content_type(m, content_type, headers[:content_type])
- m.charset = charset
+ message.content_type = set_content_type(message, content_type, headers[:content_type])
+ message.charset = charset
- if m.multipart?
- m.body.set_sort_order(headers[:parts_order])
- m.body.sort_parts!
+ if message.multipart?
+ message.body.set_sort_order(headers[:parts_order])
+ message.body.sort_parts!
end
- m
+ message
end
- protected
+ protected
# Used by #mail to set the content type of the message.
#
@@ -879,36 +865,61 @@ module ActionMailer
I18n.t(:subject, interpolations.merge(scope: [mailer_scope, action_name], default: action_name.humanize))
end
- def collect_responses(headers) #:nodoc:
- responses = []
+ # Emails do not support relative path links.
+ def self.supports_path?
+ false
+ end
+
+ private
+
+ def apply_defaults(headers)
+ default_values = self.class.default.map do |key, value|
+ [
+ key,
+ value.is_a?(Proc) ? instance_eval(&value) : value
+ ]
+ end.to_h
+ headers_with_defaults = headers.reverse_merge(default_values)
+ headers_with_defaults[:subject] ||= default_i18n_subject
+ headers_with_defaults
+ end
+
+ def assign_headers_to_message(message, headers)
+ assignable = headers.except(:parts_order, :content_type, :body, :template_name,
+ :template_path, :delivery_method, :delivery_method_options)
+ assignable.each { |k, v| message[k] = v }
+ end
+
+ def collect_responses(headers)
if block_given?
collector = ActionMailer::Collector.new(lookup_context) { render(action_name) }
yield(collector)
- responses = collector.responses
+ collector.responses
elsif headers[:body]
- responses << {
+ [{
body: headers.delete(:body),
content_type: self.class.default[:content_type] || "text/plain"
- }
+ }]
else
- templates_path = headers.delete(:template_path) || self.class.mailer_name
- templates_name = headers.delete(:template_name) || action_name
+ collect_responses_from_templates(headers)
+ end
+ end
- each_template(Array(templates_path), templates_name) do |template|
- self.formats = template.formats
+ def collect_responses_from_templates(headers)
+ templates_path = headers[:template_path] || self.class.mailer_name
+ templates_name = headers[:template_name] || action_name
- responses << {
- body: render(template: template),
- content_type: template.type.to_s
- }
- end
+ each_template(Array(templates_path), templates_name).map do |template|
+ self.formats = template.formats
+ {
+ body: render(template: template),
+ content_type: template.type.to_s
+ }
end
-
- responses
end
- def each_template(paths, name, &block) #:nodoc:
+ def each_template(paths, name, &block)
templates = lookup_context.find_all(name, paths)
if templates.empty?
raise ActionView::MissingTemplate.new(paths, name, paths, false, 'mailer')
@@ -917,7 +928,7 @@ module ActionMailer
end
end
- def create_parts_from_responses(m, responses) #:nodoc:
+ def create_parts_from_responses(m, responses)
if responses.size == 1 && !m.has_attachments?
responses[0].each { |k,v| m[k] = v }
elsif responses.size > 1 && m.has_attachments?
@@ -930,17 +941,12 @@ module ActionMailer
end
end
- def insert_part(container, response, charset) #:nodoc:
+ def insert_part(container, response, charset)
response[:charset] ||= charset
part = Mail::Part.new(response)
container.add_part(part)
end
- # Emails do not support relative path links.
- def self.supports_path?
- false
- end
-
ActiveSupport.run_load_hooks(:action_mailer, self)
end
end
diff --git a/actionmailer/lib/action_mailer/gem_version.rb b/actionmailer/lib/action_mailer/gem_version.rb
index b35d2ed965..175122e00a 100644
--- a/actionmailer/lib/action_mailer/gem_version.rb
+++ b/actionmailer/lib/action_mailer/gem_version.rb
@@ -8,7 +8,7 @@ module ActionMailer
MAJOR = 5
MINOR = 0
TINY = 0
- PRE = "alpha"
+ PRE = "beta1"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/actionmailer/lib/action_mailer/log_subscriber.rb b/actionmailer/lib/action_mailer/log_subscriber.rb
index 7e9d916b66..2867bf90fb 100644
--- a/actionmailer/lib/action_mailer/log_subscriber.rb
+++ b/actionmailer/lib/action_mailer/log_subscriber.rb
@@ -8,7 +8,7 @@ module ActionMailer
def deliver(event)
info do
recipients = Array(event.payload[:to]).join(', ')
- "\nSent mail to #{recipients} (#{event.duration.round(1)}ms)"
+ "Sent mail to #{recipients} (#{event.duration.round(1)}ms)"
end
debug { event.payload[:mail] }
@@ -16,7 +16,7 @@ module ActionMailer
# An email was received.
def receive(event)
- info { "\nReceived mail (#{event.duration.round(1)}ms)" }
+ info { "Received mail (#{event.duration.round(1)}ms)" }
debug { event.payload[:mail] }
end
@@ -25,7 +25,7 @@ module ActionMailer
debug do
mailer = event.payload[:mailer]
action = event.payload[:action]
- "\n#{mailer}##{action}: processed outbound mail in #{event.duration.round(1)}ms"
+ "#{mailer}##{action}: processed outbound mail in #{event.duration.round(1)}ms"
end
end
diff --git a/actionmailer/lib/rails/generators/mailer/mailer_generator.rb b/actionmailer/lib/rails/generators/mailer/mailer_generator.rb
index 3ec7d3d896..5a5c9d32bb 100644
--- a/actionmailer/lib/rails/generators/mailer/mailer_generator.rb
+++ b/actionmailer/lib/rails/generators/mailer/mailer_generator.rb
@@ -9,9 +9,6 @@ module Rails
def create_mailer_file
template "mailer.rb", File.join('app/mailers', class_path, "#{file_name}_mailer.rb")
- if self.behavior == :invoke
- template "application_mailer.rb", 'app/mailers/application_mailer.rb'
- end
end
hook_for :template_engine, :test_framework
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md
index 40f447ada7..3314a0b77d 100644
--- a/actionpack/CHANGELOG.md
+++ b/actionpack/CHANGELOG.md
@@ -1,3 +1,71 @@
+## Rails 5.0.0.beta1 (December 18, 2015) ##
+
+* No changes.
+
+
+* Deprecate `redirect_to :back` in favor of `redirect_back`, which accepts a
+ required `fallback_location` argument, thus eliminating the possibility of a
+ `RedirectBackError`.
+
+ *Derek Prior*
+
+* Add `redirect_back` method to `ActionController::Redirecting` to provide a
+ way to safely redirect to the `HTTP_REFERER` if it is present, falling back
+ to a provided redirect otherwise.
+
+ *Derek Prior*
+
+* `ActionController::TestCase` will be moved to it's own gem in Rails 5.1
+
+ With the speed improvements made to `ActionDispatch::IntegrationTest` we no
+ longer need to keep two separate code bases for testing controllers. In
+ Rails 5.1 `ActionController::TestCase` will be deprecated and moved into a
+ gem outside of Rails source.
+
+ This is a documentation deprecation so that going forward so new tests will use
+ `ActionDispatch::IntegrationTest` instead of `ActionController::TestCase`.
+
+ *Eileen M. Uchitelle*
+
+* Add a `response_format` option to `ActionDispatch::DebugExceptions`
+ to configure the format of the response when errors occur in
+ development mode.
+
+ If `response_format` is `:default` the debug info will be rendered
+ in an HTML page. In the other hand, if the provided value is `:api`
+ the debug info will be rendered in the original response format.
+
+ *Jorge Bejar*
+
+* Change the `protect_from_forgery` prepend default to `false`
+
+ Per this comment
+ https://github.com/rails/rails/pull/18334#issuecomment-69234050 we want
+ `protect_from_forgery` to default to `prepend: false`.
+
+ `protect_from_forgery` will now be insterted into the callback chain at the
+ point it is called in your application. This is useful for cases where you
+ want to `protect_from_forgery` after you perform required authentication
+ callbacks or other callbacks that are required to run after forgery protection.
+
+ If you want `protect_from_forgery` callbacks to always run first, regardless of
+ position they are called in your application then you can add `prepend: true`
+ to your `protect_from_forgery` call.
+
+ Example:
+
+ ```ruby
+ protect_from_forgery prepend: true
+ ```
+
+ *Eileen M. Uchitelle*
+
+* In url_for, never append a question mark to the URL when the query string
+ is empty anyway. (It used to do that when called like `url_for(controller:
+ 'x', action: 'y', q: {})`.)
+
+ *Paul Grayson*
+
* Catch invalid UTF-8 querystring values and respond with BadRequest
Check querystring params for invalid UTF-8 characters, and raise an
diff --git a/actionpack/README.rdoc b/actionpack/README.rdoc
index 44c980b070..0720c66cb9 100644
--- a/actionpack/README.rdoc
+++ b/actionpack/README.rdoc
@@ -28,7 +28,7 @@ can be used outside of Rails.
The latest version of Action Pack can be installed with RubyGems:
- % gem install actionpack
+ $ gem install actionpack
Source code can be downloaded as part of the Rails project on GitHub
@@ -55,4 +55,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/actionpack/lib/abstract_controller/callbacks.rb b/actionpack/lib/abstract_controller/callbacks.rb
index d5317e4717..d63ce9c1c3 100644
--- a/actionpack/lib/abstract_controller/callbacks.rb
+++ b/actionpack/lib/abstract_controller/callbacks.rb
@@ -48,7 +48,8 @@ module AbstractController
def _normalize_callback_option(options, from, to) # :nodoc:
if from = options[from]
- from = Array(from).map {|o| "action_name == '#{o}'"}.join(" || ")
+ _from = Array(from).map(&:to_s).to_set
+ from = proc {|c| _from.include? c.action_name }
options[to] = Array(options[to]).unshift(from)
end
end
diff --git a/actionpack/lib/action_controller/caching/fragments.rb b/actionpack/lib/action_controller/caching/fragments.rb
index 2694d4c12f..b9ad51a9cf 100644
--- a/actionpack/lib/action_controller/caching/fragments.rb
+++ b/actionpack/lib/action_controller/caching/fragments.rb
@@ -14,12 +14,57 @@ module ActionController
#
# expire_fragment('name_of_cache')
module Fragments
+ extend ActiveSupport::Concern
+
+ included do
+ if respond_to?(:class_attribute)
+ class_attribute :fragment_cache_keys
+ else
+ mattr_writer :fragment_cache_keys
+ end
+
+ self.fragment_cache_keys = []
+
+ helper_method :fragment_cache_key if respond_to?(:helper_method)
+ end
+
+ module ClassMethods
+ # Allows you to specify controller-wide key prefixes for
+ # cache fragments. Pass either a constant +value+, or a block
+ # which computes a value each time a cache key is generated.
+ #
+ # For example, you may want to prefix all fragment cache keys
+ # with a global version identifier, so you can easily
+ # invalidate all caches.
+ #
+ # class ApplicationController
+ # fragment_cache_key "v1"
+ # end
+ #
+ # When it's time to invalidate all fragments, simply change
+ # the string constant. Or, progressively roll out the cache
+ # invalidation using a computed value:
+ #
+ # class ApplicationController
+ # fragment_cache_key do
+ # @account.id.odd? ? "v1" : "v2"
+ # end
+ # end
+ def fragment_cache_key(value = nil, &key)
+ self.fragment_cache_keys += [key || ->{ value }]
+ end
+ end
+
# Given a key (as described in +expire_fragment+), returns
# a key suitable for use in reading, writing, or expiring a
- # cached fragment. All keys are prefixed with <tt>views/</tt> and uses
- # ActiveSupport::Cache.expand_cache_key for the expansion.
+ # cached fragment. All keys begin with <tt>views/</tt>,
+ # followed by any controller-wide key prefix values, ending
+ # with the specified +key+ value. The key is expanded using
+ # ActiveSupport::Cache.expand_cache_key.
def fragment_cache_key(key)
- ActiveSupport::Cache.expand_cache_key(key.is_a?(Hash) ? url_for(key).split("://").last : key, :views)
+ head = self.class.fragment_cache_keys.map { |k| instance_exec(&k) }
+ tail = key.is_a?(Hash) ? url_for(key).split("://").last : key
+ ActiveSupport::Cache.expand_cache_key([*head, *tail], :views)
end
# Writes +content+ to the location signified by
diff --git a/actionpack/lib/action_controller/metal/http_authentication.rb b/actionpack/lib/action_controller/metal/http_authentication.rb
index 0a36fecd27..2ac6e37e34 100644
--- a/actionpack/lib/action_controller/metal/http_authentication.rb
+++ b/actionpack/lib/action_controller/metal/http_authentication.rb
@@ -397,7 +397,7 @@ module ActionController
# RewriteRule ^(.*)$ dispatch.fcgi [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]
module Token
TOKEN_KEY = 'token='
- TOKEN_REGEX = /^(Token|Bearer) /
+ TOKEN_REGEX = /^(Token|Bearer)\s+/
AUTHN_PAIR_DELIMITERS = /(?:,|;|\t+)/
extend self
diff --git a/actionpack/lib/action_controller/metal/live.rb b/actionpack/lib/action_controller/metal/live.rb
index 27b3eb4e58..e3c540bf5f 100644
--- a/actionpack/lib/action_controller/metal/live.rb
+++ b/actionpack/lib/action_controller/metal/live.rb
@@ -36,8 +36,7 @@ module ActionController
extend ActiveSupport::Concern
module ClassMethods
- def make_response!(response)
- request = response.request
+ def make_response!(request)
if request.get_header("HTTP_VERSION") == "HTTP/1.0"
super
else
@@ -223,12 +222,6 @@ module ActionController
jar.write self unless committed?
end
- def before_sending
- super
- request.cookie_jar.commit!
- headers.freeze
- end
-
def build_buffer(response, body)
buf = Live::Buffer.new response
body.each { |part| buf.write part }
@@ -293,9 +286,5 @@ module ActionController
super
response.close if response
end
-
- def set_response!(response)
- @_response = self.class.make_response! response
- end
end
end
diff --git a/actionpack/lib/action_controller/metal/redirecting.rb b/actionpack/lib/action_controller/metal/redirecting.rb
index 0febc905f1..b13ba06962 100644
--- a/actionpack/lib/action_controller/metal/redirecting.rb
+++ b/actionpack/lib/action_controller/metal/redirecting.rb
@@ -20,8 +20,6 @@ module ActionController
# * <tt>String</tt> starting with <tt>protocol://</tt> (like <tt>http://</tt>) or a protocol relative reference (like <tt>//</tt>) - Is passed straight through as the target for redirection.
# * <tt>String</tt> not containing a protocol - The current protocol and host is prepended to the string.
# * <tt>Proc</tt> - A block that will be executed in the controller's context. Should return any option accepted by +redirect_to+.
- # * <tt>:back</tt> - Back to the page that issued the request. Useful for forms that are triggered from multiple places.
- # Short-hand for <tt>redirect_to(request.env["HTTP_REFERER"])</tt>
#
# === Examples:
#
@@ -30,7 +28,6 @@ module ActionController
# redirect_to "http://www.rubyonrails.org"
# redirect_to "/images/screenshot.jpg"
# redirect_to articles_url
- # redirect_to :back
# redirect_to proc { edit_post_url(@post) }
#
# The redirection happens as a "302 Found" header unless otherwise specified using the <tt>:status</tt> option:
@@ -61,13 +58,8 @@ module ActionController
# redirect_to post_url(@post), status: 301, flash: { updated_post_id: @post.id }
# redirect_to({ action: 'atom' }, alert: "Something serious happened")
#
- # When using <tt>redirect_to :back</tt>, if there is no referrer,
- # <tt>ActionController::RedirectBackError</tt> will be raised. You
- # may specify some fallback behavior for this case by rescuing
- # <tt>ActionController::RedirectBackError</tt>.
def redirect_to(options = {}, response_status = {}) #:doc:
raise ActionControllerError.new("Cannot redirect to nil!") unless options
- raise ActionControllerError.new("Cannot redirect to a parameter hash!") if options.is_a?(ActionController::Parameters)
raise AbstractController::DoubleRenderError if response_body
self.status = _extract_redirect_to_status(options, response_status)
@@ -75,6 +67,32 @@ module ActionController
self.response_body = "<html><body>You are being <a href=\"#{ERB::Util.unwrapped_html_escape(location)}\">redirected</a>.</body></html>"
end
+ # Redirects the browser to the page that issued the request (the referrer)
+ # if possible, otherwise redirects to the provided default fallback
+ # location.
+ #
+ # The referrer information is pulled from the HTTP `Referer` (sic) header on
+ # the request. This is an optional header and its presence on the request is
+ # subject to browser security settings and user preferences. If the request
+ # is missing this header, the <tt>fallback_location</tt> will be used.
+ #
+ # redirect_back fallback_location: { action: "show", id: 5 }
+ # redirect_back fallback_location: post
+ # redirect_back fallback_location: "http://www.rubyonrails.org"
+ # redirect_back fallback_location: "/images/screenshot.jpg"
+ # redirect_back fallback_location: articles_url
+ # redirect_back fallback_location: proc { edit_post_url(@post) }
+ #
+ # All options that can be passed to <tt>redirect_to</tt> are accepted as
+ # options and the behavior is indetical.
+ def redirect_back(fallback_location:, **args)
+ if referer = request.headers["Referer"]
+ redirect_to referer, **args
+ else
+ redirect_to fallback_location, **args
+ end
+ end
+
def _compute_redirect_to_location(request, options) #:nodoc:
case options
# The scheme name consist of a letter followed by any combination of
@@ -87,6 +105,12 @@ module ActionController
when String
request.protocol + request.host_with_port + options
when :back
+ ActiveSupport::Deprecation.warn(<<-MESSAGE.squish)
+ `redirect_to :back` is deprecated and will be removed from Rails 5.1.
+ Please use `redirect_back(fallback_location: fallback_location)` where
+ `fallback_location` represents the location to use if the request has
+ no HTTP referer information.
+ MESSAGE
request.headers["Referer"] or raise RedirectBackError
when Proc
_compute_redirect_to_location request, options.call
diff --git a/actionpack/lib/action_controller/metal/request_forgery_protection.rb b/actionpack/lib/action_controller/metal/request_forgery_protection.rb
index 64f6f7cf51..26c4550f89 100644
--- a/actionpack/lib/action_controller/metal/request_forgery_protection.rb
+++ b/actionpack/lib/action_controller/metal/request_forgery_protection.rb
@@ -77,6 +77,10 @@ module ActionController #:nodoc:
config_accessor :log_warning_on_csrf_failure
self.log_warning_on_csrf_failure = true
+ # Controls whether the Origin header is checked in addition to the CSRF token.
+ config_accessor :forgery_protection_origin_check
+ self.forgery_protection_origin_check = false
+
helper_method :form_authenticity_token
helper_method :protect_against_forgery?
end
@@ -98,13 +102,13 @@ module ActionController #:nodoc:
#
# Valid Options:
#
- # * <tt>:only/:except</tt> - Only apply forgery protection to a subset of actions. Like <tt>only: [ :create, :create_all ]</tt>.
+ # * <tt>:only/:except</tt> - Only apply forgery protection to a subset of actions. For example <tt>only: [ :create, :create_all ]</tt>.
# * <tt>:if/:unless</tt> - Turn off the forgery protection entirely depending on the passed Proc or method reference.
- # * <tt>:prepend</tt> - By default, the verification of the authentication token is added to the front of the
- # callback chain. If you need to make the verification depend on other callbacks, like authentication methods
- # (say cookies vs OAuth), this might not work for you. Pass <tt>prepend: false</tt> to just add the
- # verification callback in the position of the protect_from_forgery call. This means any callbacks added
- # before are run first.
+ # * <tt>:prepend</tt> - By default, the verification of the authentication token will be added at the position of the
+ # protect_from_forgery call in your application. This means any callbacks added before are run first. This is useful
+ # when you want your forgery protection to depend on other callbacks, like authentication methods (Oauth vs Cookie auth).
+ #
+ # If you need to add verification to the beginning of the callback chain, use <tt>prepend: true</tt>.
# * <tt>:with</tt> - Set the method to handle unverified request.
#
# Valid unverified request handling methods are:
@@ -112,7 +116,7 @@ module ActionController #:nodoc:
# * <tt>:reset_session</tt> - Resets the session.
# * <tt>:null_session</tt> - Provides an empty session during request but doesn't reset it completely. Used as default if <tt>:with</tt> option is not specified.
def protect_from_forgery(options = {})
- options = options.reverse_merge(prepend: true)
+ options = options.reverse_merge(prepend: false)
self.forgery_protection_strategy = protection_method_class(options[:with] || :null_session)
self.request_forgery_protection_token ||= :authenticity_token
@@ -257,8 +261,19 @@ module ActionController #:nodoc:
# * Does the X-CSRF-Token header match the form_authenticity_token
def verified_request?
!protect_against_forgery? || request.get? || request.head? ||
- valid_authenticity_token?(session, form_authenticity_param) ||
- valid_authenticity_token?(session, request.headers['X-CSRF-Token'])
+ (valid_request_origin? && any_authenticity_token_valid?)
+ end
+
+ # Checks if any of the authenticity tokens from the request are valid.
+ def any_authenticity_token_valid?
+ request_authenticity_tokens.any? do |token|
+ valid_authenticity_token?(session, token)
+ end
+ end
+
+ # Possible authenticity tokens sent in the request.
+ def request_authenticity_tokens
+ [form_authenticity_param, request.x_csrf_token]
end
# Sets the token value for the current session.
@@ -336,5 +351,16 @@ module ActionController #:nodoc:
def protect_against_forgery?
allow_forgery_protection
end
+
+ # Checks if the request originated from the same origin by looking at the
+ # Origin header.
+ def valid_request_origin?
+ if forgery_protection_origin_check
+ # We accept blank origin headers because some user agents don't send it.
+ request.origin.nil? || request.origin == request.base_url
+ else
+ true
+ end
+ end
end
end
diff --git a/actionpack/lib/action_controller/metal/strong_parameters.rb b/actionpack/lib/action_controller/metal/strong_parameters.rb
index 130ba61786..957aa746c0 100644
--- a/actionpack/lib/action_controller/metal/strong_parameters.rb
+++ b/actionpack/lib/action_controller/metal/strong_parameters.rb
@@ -1,8 +1,10 @@
require 'active_support/core_ext/hash/indifferent_access'
+require 'active_support/core_ext/hash/transform_values'
require 'active_support/core_ext/array/wrap'
require 'active_support/core_ext/string/filters'
require 'active_support/rescuable'
require 'action_dispatch/http/upload'
+require 'rack/test'
require 'stringio'
require 'set'
@@ -161,8 +163,8 @@ module ActionController
end
end
- # Returns a safe +Hash+ representation of this parameter with all
- # unpermitted keys removed.
+ # Returns a safe <tt>ActiveSupport::HashWithIndifferentAccess</tt>
+ # representation of this parameter with all unpermitted keys removed.
#
# params = ActionController::Parameters.new({
# name: 'Senjougahara Hitagi',
@@ -174,15 +176,17 @@ module ActionController
# safe_params.to_h # => {"name"=>"Senjougahara Hitagi"}
def to_h
if permitted?
- @parameters.to_h
+ convert_parameters_to_hashes(@parameters)
else
slice(*self.class.always_permitted_parameters).permit!.to_h
end
end
- # Returns an unsafe, unfiltered +Hash+ representation of this parameter.
+ # Returns an unsafe, unfiltered
+ # <tt>ActiveSupport::HashWithIndifferentAccess</tt> representation of this
+ # parameter.
def to_unsafe_h
- @parameters.to_h
+ convert_parameters_to_hashes(@parameters)
end
alias_method :to_unsafe_hash, :to_unsafe_h
@@ -591,6 +595,21 @@ module ActionController
end
end
+ def convert_parameters_to_hashes(value)
+ case value
+ when Array
+ value.map { |v| convert_parameters_to_hashes(v) }
+ when Hash
+ value.transform_values do |v|
+ convert_parameters_to_hashes(v)
+ end.with_indifferent_access
+ when Parameters
+ value.to_h
+ else
+ value
+ end
+ end
+
def convert_hashes_to_parameters(key, value)
converted = convert_value_to_parameters(value)
@parameters[key] = converted unless converted.equal?(value)
diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb
index 442ffd6d7c..c55720859e 100644
--- a/actionpack/lib/action_controller/test_case.rb
+++ b/actionpack/lib/action_controller/test_case.rb
@@ -7,6 +7,9 @@ require 'action_controller/template_assertions'
require 'rails-dom-testing'
module ActionController
+ # :stopdoc:
+ # ActionController::TestCase will be deprecated and moved to a gem in Rails 5.1.
+ # Please use ActionDispatch::IntegrationTest going forward.
class TestRequest < ActionDispatch::TestRequest #:nodoc:
DEFAULT_ENV = ActionDispatch::TestRequest::DEFAULT_ENV.dup
DEFAULT_ENV.delete 'PATH_INFO'
@@ -658,4 +661,5 @@ module ActionController
include Behavior
end
+ # :startdoc:
end
diff --git a/actionpack/lib/action_dispatch/http/mime_negotiation.rb b/actionpack/lib/action_dispatch/http/mime_negotiation.rb
index 7acf91902d..0152c17ed4 100644
--- a/actionpack/lib/action_dispatch/http/mime_negotiation.rb
+++ b/actionpack/lib/action_dispatch/http/mime_negotiation.rb
@@ -67,6 +67,8 @@ module ActionDispatch
v = if params_readable
Array(Mime[parameters[:format]])
+ elsif format = format_from_path_extension
+ Array(Mime[format])
elsif use_accept_header && valid_accept_header
accepts
elsif xhr?
@@ -160,6 +162,13 @@ module ActionDispatch
def use_accept_header
!self.class.ignore_accept_header
end
+
+ def format_from_path_extension
+ path = @env['action_dispatch.original_path'] || @env['PATH_INFO']
+ if match = path && path.match(/\.(\w+)\z/)
+ match.captures.first
+ end
+ end
end
end
end
diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb
index b64f660ec5..b8d395854c 100644
--- a/actionpack/lib/action_dispatch/http/mime_type.rb
+++ b/actionpack/lib/action_dispatch/http/mime_type.rb
@@ -47,15 +47,10 @@ module Mime
def const_missing(sym)
ext = sym.downcase
if Mime[ext]
- ActiveSupport::Deprecation.warn <<-eow
-Accessing mime types via constants is deprecated. Please change:
-
- `Mime::#{sym}`
-
-to:
-
- `Mime[:#{ext}]`
- eow
+ ActiveSupport::Deprecation.warn(<<-MSG.squish)
+ Accessing mime types via constants is deprecated.
+ Please change `Mime::#{sym}` to `Mime[:#{ext}]`.
+ MSG
Mime[ext]
else
super
@@ -65,15 +60,10 @@ to:
def const_defined?(sym, inherit = true)
ext = sym.downcase
if Mime[ext]
- ActiveSupport::Deprecation.warn <<-eow
-Accessing mime types via constants is deprecated. Please change:
-
- `Mime.const_defined?(#{sym})`
-
-to:
-
- `Mime[:#{ext}]`
- eow
+ ActiveSupport::Deprecation.warn(<<-MSG.squish)
+ Accessing mime types via constants is deprecated.
+ Please change `Mime.const_defined?(#{sym})` to `Mime[:#{ext}]`.
+ MSG
true
else
super
diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb
index ea61ad0c02..29cf821090 100644
--- a/actionpack/lib/action_dispatch/http/request.rb
+++ b/actionpack/lib/action_dispatch/http/request.rb
@@ -36,8 +36,8 @@ module ActionDispatch
HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_ACCEPT_ENCODING
HTTP_ACCEPT_LANGUAGE HTTP_CACHE_CONTROL HTTP_FROM
HTTP_NEGOTIATE HTTP_PRAGMA HTTP_CLIENT_IP
- HTTP_X_FORWARDED_FOR HTTP_VERSION
- HTTP_X_REQUEST_ID HTTP_X_FORWARDED_HOST
+ HTTP_X_FORWARDED_FOR HTTP_ORIGIN HTTP_VERSION
+ HTTP_X_CSRF_TOKEN HTTP_X_REQUEST_ID HTTP_X_FORWARDED_HOST
SERVER_ADDR
].freeze
@@ -49,6 +49,10 @@ module ActionDispatch
METHOD
end
+ def self.empty
+ new({})
+ end
+
def initialize(env)
super
@method = nil
@@ -59,6 +63,9 @@ module ActionDispatch
@ip = nil
end
+ def commit_cookie_jar! # :nodoc:
+ end
+
def check_path_parameters!
# If any of the path parameters has an invalid encoding then
# raise since it's likely to trigger errors further on.
@@ -306,10 +313,16 @@ module ActionDispatch
end
end
- # Returns true if the request's content MIME type is
- # +application/x-www-form-urlencoded+ or +multipart/form-data+.
+ # Determine whether the request body contains form-data by checking
+ # the request Content-Type for one of the media-types:
+ # "application/x-www-form-urlencoded" or "multipart/form-data". The
+ # list of form-data media types can be modified through the
+ # +FORM_DATA_MEDIA_TYPES+ array.
+ #
+ # A request body is not assumed to contain form-data when no
+ # Content-Type header is provided and the request_method is POST.
def form_data?
- FORM_DATA_MEDIA_TYPES.include?(content_mime_type.to_s)
+ FORM_DATA_MEDIA_TYPES.include?(media_type)
end
def body_stream #:nodoc:
diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb
index f0127aa276..9b11111a67 100644
--- a/actionpack/lib/action_dispatch/http/response.rb
+++ b/actionpack/lib/action_dispatch/http/response.rb
@@ -412,6 +412,8 @@ module ActionDispatch # :nodoc:
end
def before_sending
+ headers.freeze
+ request.commit_cookie_jar! unless committed?
end
def build_buffer(response, body)
diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb
index 92b10b6d3b..37f41ae988 100644
--- a/actionpack/lib/action_dispatch/http/url.rb
+++ b/actionpack/lib/action_dispatch/http/url.rb
@@ -81,7 +81,8 @@ module ActionDispatch
def add_params(path, params)
params = { params: params } unless params.is_a?(Hash)
params.reject! { |_,v| v.to_param.nil? }
- path << "?#{params.to_query}" unless params.empty?
+ query = params.to_query
+ path << "?#{query}" unless query.empty?
end
def add_anchor(path, anchor)
diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb
index 2889acaeb8..3477aa8b29 100644
--- a/actionpack/lib/action_dispatch/middleware/cookies.rb
+++ b/actionpack/lib/action_dispatch/middleware/cookies.rb
@@ -12,6 +12,12 @@ module ActionDispatch
end
# :stopdoc:
+ prepend Module.new {
+ def commit_cookie_jar!
+ cookie_jar.commit!
+ end
+ }
+
def have_cookie_jar?
has_header? 'action_dispatch.cookies'.freeze
end
@@ -77,6 +83,12 @@ module ActionDispatch
# # It can be read using the signed method `cookies.signed[:name]`
# cookies.signed[:user_id] = current_user.id
#
+ # # Sets an encrypted cookie value before sending it to the client which
+ # # prevent users from reading and tampering with its value.
+ # # The cookie is signed by your app's `secrets.secret_key_base` value.
+ # # It can be read using the encrypted method `cookies.encrypted[:name]`
+ # cookies.encrypted[:discount] = 45
+ #
# # Sets a "permanent" cookie (which expires in 20 years from now).
# cookies.permanent[:login] = "XJ-122"
#
@@ -89,6 +101,7 @@ module ActionDispatch
# cookies.size # => 2
# JSON.parse(cookies[:lat_lon]) # => [47.68, -122.37]
# cookies.signed[:login] # => "XJ-122"
+ # cookies.encrypted[:discount] # => 45
#
# Example for deleting:
#
diff --git a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
index 66bb74b9c5..b55c937e0c 100644
--- a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
+++ b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
@@ -38,9 +38,10 @@ module ActionDispatch
end
end
- def initialize(app, routes_app = nil)
- @app = app
- @routes_app = routes_app
+ def initialize(app, routes_app = nil, response_format = :default)
+ @app = app
+ @routes_app = routes_app
+ @response_format = response_format
end
def call(env)
@@ -66,41 +67,79 @@ module ActionDispatch
log_error(request, wrapper)
if request.get_header('action_dispatch.show_detailed_exceptions')
- traces = wrapper.traces
-
- trace_to_show = 'Application Trace'
- if traces[trace_to_show].empty? && wrapper.rescue_template != 'routing_error'
- trace_to_show = 'Full Trace'
+ case @response_format
+ when :api
+ render_for_api_application(request, wrapper)
+ when :default
+ render_for_default_application(request, wrapper)
end
+ else
+ raise exception
+ end
+ end
- if source_to_show = traces[trace_to_show].first
- source_to_show_id = source_to_show[:id]
- end
+ def render_for_default_application(request, wrapper)
+ template = create_template(request, wrapper)
+ file = "rescues/#{wrapper.rescue_template}"
- template = DebugView.new([RESCUES_TEMPLATE_PATH],
- request: request,
- exception: wrapper.exception,
- traces: traces,
- show_source_idx: source_to_show_id,
- trace_to_show: trace_to_show,
- routes_inspector: routes_inspector(exception),
- source_extracts: wrapper.source_extracts,
- line_number: wrapper.line_number,
- file: wrapper.file
- )
- file = "rescues/#{wrapper.rescue_template}"
-
- if request.xhr?
- body = template.render(template: file, layout: false, formats: [:text])
- format = "text/plain"
- else
- body = template.render(template: file, layout: 'rescues/layout')
- format = "text/html"
- end
- render(wrapper.status_code, body, format)
+ if request.xhr?
+ body = template.render(template: file, layout: false, formats: [:text])
+ format = "text/plain"
else
- raise exception
+ body = template.render(template: file, layout: 'rescues/layout')
+ format = "text/html"
end
+ render(wrapper.status_code, body, format)
+ end
+
+ def render_for_api_application(request, wrapper)
+ body = {
+ status: wrapper.status_code,
+ error: Rack::Utils::HTTP_STATUS_CODES.fetch(
+ wrapper.status_code,
+ Rack::Utils::HTTP_STATUS_CODES[500]
+ ),
+ exception: wrapper.exception.inspect,
+ traces: wrapper.traces
+ }
+
+ content_type = request.formats.first
+ to_format = "to_#{content_type.to_sym}"
+
+ if content_type && body.respond_to?(to_format)
+ formatted_body = body.public_send(to_format)
+ format = content_type
+ else
+ formatted_body = body.to_json
+ format = Mime[:json]
+ end
+
+ render(wrapper.status_code, formatted_body, format)
+ end
+
+ def create_template(request, wrapper)
+ traces = wrapper.traces
+
+ trace_to_show = 'Application Trace'
+ if traces[trace_to_show].empty? && wrapper.rescue_template != 'routing_error'
+ trace_to_show = 'Full Trace'
+ end
+
+ if source_to_show = traces[trace_to_show].first
+ source_to_show_id = source_to_show[:id]
+ end
+
+ DebugView.new([RESCUES_TEMPLATE_PATH],
+ request: request,
+ exception: wrapper.exception,
+ traces: traces,
+ show_source_idx: source_to_show_id,
+ trace_to_show: trace_to_show,
+ routes_inspector: routes_inspector(wrapper.exception),
+ source_extracts: wrapper.source_extracts,
+ line_number: wrapper.line_number,
+ file: wrapper.file
+ )
end
def render(status, body, format)
diff --git a/actionpack/lib/action_dispatch/middleware/remote_ip.rb b/actionpack/lib/action_dispatch/middleware/remote_ip.rb
index aee2334da9..31b75498b6 100644
--- a/actionpack/lib/action_dispatch/middleware/remote_ip.rb
+++ b/actionpack/lib/action_dispatch/middleware/remote_ip.rb
@@ -43,7 +43,7 @@ module ActionDispatch
# Create a new +RemoteIp+ middleware instance.
#
- # The +check_ip_spoofing+ option is on by default. When on, an exception
+ # The +ip_spoofing_check+ option is on by default. When on, an exception
# is raised if it looks like the client is trying to lie about its own IP
# address. It makes sense to turn off this check on sites aimed at non-IP
# clients (like WAP devices), or behind proxies that set headers in an
@@ -57,9 +57,9 @@ module ActionDispatch
# with your proxy servers after it. If your proxies aren't removed, pass
# them in via the +custom_proxies+ parameter. That way, the middleware will
# ignore those IP addresses, and return the one that you want.
- def initialize(app, check_ip_spoofing = true, custom_proxies = nil)
+ def initialize(app, ip_spoofing_check = true, custom_proxies = nil)
@app = app
- @check_ip = check_ip_spoofing
+ @check_ip = ip_spoofing_check
@proxies = if custom_proxies.blank?
TRUSTED_PROXIES
elsif custom_proxies.respond_to?(:any?)
@@ -116,10 +116,18 @@ module ActionDispatch
forwarded_ips = ips_from(@req.x_forwarded_for).reverse
# +Client-Ip+ and +X-Forwarded-For+ should not, generally, both be set.
- # If they are both set, it means that this request passed through two
- # proxies with incompatible IP header conventions, and there is no way
- # for us to determine which header is the right one after the fact.
- # Since we have no idea, we give up and explode.
+ # If they are both set, it means that either:
+ #
+ # 1) This request passed through two proxies with incompatible IP header
+ # conventions.
+ # 2) The client passed one of +Client-Ip+ or +X-Forwarded-For+
+ # (whichever the proxy servers weren't using) themselves.
+ #
+ # Either way, there is no way for us to determine which header is the
+ # right one after the fact. Since we have no idea, if we are concerned
+ # about IP spoofing we need to give up and explode. (If you're not
+ # concerned about IP spoofing you can turn the +ip_spoofing_check+
+ # option off.)
should_check_ip = @check_ip && client_ips.last && forwarded_ips.last
if should_check_ip && !forwarded_ips.include?(client_ips.last)
# We don't know which came from the proxy, and which from the user
diff --git a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb
index 0e636b8257..429a98f236 100644
--- a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb
+++ b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb
@@ -36,7 +36,7 @@ module ActionDispatch
# development:
# secret_key_base: 'secret key'
#
- # To generate a secret key for an existing application, run `rake secret`.
+ # To generate a secret key for an existing application, run `rails secret`.
#
# If you are upgrading an existing Rails 3 app, you should leave your
# existing secret_token in place and simply add the new secret_key_base.
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.html.erb
index e7b913bbe4..e7b913bbe4 100644
--- a/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.erb
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.html.erb
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.text.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.text.erb
new file mode 100644
index 0000000000..23a9c7ba3f
--- /dev/null
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.text.erb
@@ -0,0 +1,8 @@
+<% @source_extracts.first(3).each do |source_extract| %>
+<% if source_extract[:code] %>
+Extracted source (around line #<%= source_extract[:line_number] %>):
+
+<% source_extract[:code].each do |line, source| -%>
+<%= line == source_extract[:line_number] ? "*#{line}" : "##{line}" -%> <%= source -%><% end -%>
+<% end %>
+<% end %>
diff --git a/actionpack/lib/action_dispatch/routing.rb b/actionpack/lib/action_dispatch/routing.rb
index 59c3f9248f..d00b2c3eb5 100644
--- a/actionpack/lib/action_dispatch/routing.rb
+++ b/actionpack/lib/action_dispatch/routing.rb
@@ -237,7 +237,7 @@ module ActionDispatch
#
# == View a list of all your routes
#
- # rake routes
+ # rails routes
#
# Target specific controllers by prefixing the command with <tt>CONTROLLER=x</tt>.
#
diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb
index 7c0404ca62..18cd205bad 100644
--- a/actionpack/lib/action_dispatch/routing/mapper.rb
+++ b/actionpack/lib/action_dispatch/routing/mapper.rb
@@ -11,7 +11,7 @@ module ActionDispatch
class Mapper
URL_OPTIONS = [:protocol, :subdomain, :domain, :host, :port]
- class Constraints < Endpoint #:nodoc:
+ class Constraints < Routing::Endpoint #:nodoc:
attr_reader :app, :constraints
SERVE = ->(app, req) { app.serve req }
@@ -600,17 +600,20 @@ module ActionDispatch
def mount(app, options = nil)
if options
path = options.delete(:at)
- else
- unless Hash === app
- raise ArgumentError, "must be called with mount point"
- end
-
+ elsif Hash === app
options = app
app, path = options.find { |k, _| k.respond_to?(:call) }
options.delete(app) if app
end
- raise "A rack application must be specified" unless path
+ raise ArgumentError, "A rack application must be specified" unless app.respond_to?(:call)
+ raise ArgumentError, <<-MSG.strip_heredoc unless path
+ Must be called with mount point
+
+ mount SomeRackApp, at: "some_route"
+ or
+ mount(SomeRackApp => "some_route")
+ MSG
rails_app = rails_app? app
options[:as] ||= app_name(app, rails_app)
diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb
index 5f54ea130b..2bd2e53252 100644
--- a/actionpack/lib/action_dispatch/routing/route_set.rb
+++ b/actionpack/lib/action_dispatch/routing/route_set.rb
@@ -30,9 +30,9 @@ module ActionDispatch
controller = controller req
res = controller.make_response! req
dispatch(controller, params[:action], req, res)
- rescue NameError => e
+ rescue ActionController::RoutingError
if @raise_on_name_error
- raise ActionController::RoutingError, e.message, e.backtrace
+ raise
else
return [404, {'X-Cascade' => 'pass'}, []]
end
@@ -42,6 +42,8 @@ module ActionDispatch
def controller(req)
req.controller_class
+ rescue NameError => e
+ raise ActionController::RoutingError, e.message, e.backtrace
end
def dispatch(controller, action, req, res)
@@ -371,10 +373,6 @@ module ActionDispatch
end
def eval_block(block)
- if block.arity == 1
- raise "You are using the old router DSL which has been removed in Rails 3.1. " <<
- "Please check how to update your routes file at: http://www.engineyard.com/blog/2010/the-lowdown-on-routes-in-rails-3/"
- end
mapper = Mapper.new(self)
if default_scope
mapper.with_default_scope(default_scope, &block)
diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb
index b6c031dcf4..f91679593e 100644
--- a/actionpack/lib/action_dispatch/routing/url_for.rb
+++ b/actionpack/lib/action_dispatch/routing/url_for.rb
@@ -172,8 +172,11 @@ module ActionDispatch
_routes.url_for(options.symbolize_keys.reverse_merge!(url_options),
route_name)
when ActionController::Parameters
+ unless options.permitted?
+ raise ArgumentError.new("Generating an URL from non sanitized request parameters is insecure!")
+ end
route_name = options.delete :use_route
- _routes.url_for(options.to_unsafe_h.symbolize_keys.
+ _routes.url_for(options.to_h.symbolize_keys.
reverse_merge!(url_options), route_name)
when String
options
diff --git a/actionpack/lib/action_dispatch/testing/assertions/response.rb b/actionpack/lib/action_dispatch/testing/assertions/response.rb
index eab20b075d..c138660a21 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/response.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/response.rb
@@ -27,9 +27,11 @@ module ActionDispatch
# # Asserts that the response code was status code 401 (unauthorized)
# assert_response 401
def assert_response(type, message = nil)
+ message ||= generate_response_message(type)
+
if Symbol === type
if [:success, :missing, :redirect, :error].include?(type)
- assert_predicate @response, RESPONSE_PREDICATES[type], message
+ assert @response.send(RESPONSE_PREDICATES[type]), message
else
code = Rack::Utils::SYMBOL_TO_STATUS_CODE[type]
if code.nil?
@@ -82,6 +84,17 @@ module ActionDispatch
handle._compute_redirect_to_location(@request, fragment)
end
end
+
+ def generate_response_message(type, code = @response.response_code)
+ "Expected response to be a <#{type}>, but was a <#{code}>"
+ .concat location_if_redirected
+ end
+
+ def location_if_redirected
+ return '' unless @response.redirection? && @response.location.present?
+ location = normalize_argument_to_redirection(@response.location)
+ " redirect to <#{location}>"
+ end
end
end
end
diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb
index 790f9ea5d2..711ca10419 100644
--- a/actionpack/lib/action_dispatch/testing/integration.rb
+++ b/actionpack/lib/action_dispatch/testing/integration.rb
@@ -375,6 +375,7 @@ module ActionDispatch
@request = ActionDispatch::Request.new(session.last_request.env)
response = _mock_session.last_response
@response = ActionDispatch::TestResponse.from_response(response)
+ @response.request = @request
@html_document = nil
@url_options = nil
diff --git a/actionpack/lib/action_dispatch/testing/test_process.rb b/actionpack/lib/action_dispatch/testing/test_process.rb
index c28d701b48..eca0439909 100644
--- a/actionpack/lib/action_dispatch/testing/test_process.rb
+++ b/actionpack/lib/action_dispatch/testing/test_process.rb
@@ -26,7 +26,7 @@ module ActionDispatch
@response.redirect_url
end
- # Shortcut for <tt>Rack::Test::UploadedFile.new(File.join(ActionController::TestCase.fixture_path, path), type)</tt>:
+ # Shortcut for <tt>Rack::Test::UploadedFile.new(File.join(ActionDispatch::IntegrationTest.fixture_path, path), type)</tt>:
#
# post :change_avatar, avatar: fixture_file_upload('files/spongebob.png', 'image/png')
#
diff --git a/actionpack/lib/action_pack/gem_version.rb b/actionpack/lib/action_pack/gem_version.rb
index 255ac9f4ed..5cfb5f02d8 100644
--- a/actionpack/lib/action_pack/gem_version.rb
+++ b/actionpack/lib/action_pack/gem_version.rb
@@ -8,7 +8,7 @@ module ActionPack
MAJOR = 5
MINOR = 0
TINY = 0
- PRE = "alpha"
+ PRE = "beta1"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/actionpack/test/assertions/response_assertions_test.rb b/actionpack/test/assertions/response_assertions_test.rb
index 82c747680d..841fa6aaad 100644
--- a/actionpack/test/assertions/response_assertions_test.rb
+++ b/actionpack/test/assertions/response_assertions_test.rb
@@ -6,7 +6,12 @@ module ActionDispatch
class ResponseAssertionsTest < ActiveSupport::TestCase
include ResponseAssertions
- FakeResponse = Struct.new(:response_code) do
+ FakeResponse = Struct.new(:response_code, :location) do
+ def initialize(*)
+ super
+ self.location ||= "http://test.example.com/posts"
+ end
+
[:successful, :not_found, :redirection, :server_error].each do |sym|
define_method("#{sym}?") do
sym == response_code
@@ -14,6 +19,11 @@ module ActionDispatch
end
end
+ def setup
+ @controller = nil
+ @request = nil
+ end
+
def test_assert_response_predicate_methods
[:success, :missing, :redirect, :error].each do |sym|
@response = FakeResponse.new RESPONSE_PREDICATES[sym].to_s.sub(/\?/, '').to_sym
@@ -58,6 +68,37 @@ module ActionDispatch
assert_response :succezz
}
end
+
+ def test_error_message_shows_404_when_404_asserted_for_success
+ @response = ActionDispatch::Response.new
+ @response.status = 404
+
+ error = assert_raises(Minitest::Assertion) { assert_response :success }
+ expected = "Expected response to be a <success>, but was a <404>"
+ assert_match expected, error.message
+ end
+
+ def test_error_message_shows_302_redirect_when_302_asserted_for_success
+ @response = ActionDispatch::Response.new
+ @response.status = 302
+ @response.location = 'http://test.host/posts/redirect/1'
+
+ error = assert_raises(Minitest::Assertion) { assert_response :success }
+ expected = "Expected response to be a <success>, but was a <302>" \
+ " redirect to <http://test.host/posts/redirect/1>"
+ assert_match expected, error.message
+ end
+
+ def test_error_message_shows_302_redirect_when_302_asserted_for_301
+ @response = ActionDispatch::Response.new
+ @response.status = 302
+ @response.location = 'http://test.host/posts/redirect/2'
+
+ error = assert_raises(Minitest::Assertion) { assert_response 301 }
+ expected = "Expected response to be a <301>, but was a <302>" \
+ " redirect to <http://test.host/posts/redirect/2>"
+ assert_match expected, error.message
+ end
end
end
end
diff --git a/actionpack/test/controller/base_test.rb b/actionpack/test/controller/base_test.rb
index fb60dbd993..e3f669dbb5 100644
--- a/actionpack/test/controller/base_test.rb
+++ b/actionpack/test/controller/base_test.rb
@@ -93,7 +93,7 @@ end
class ControllerInstanceTests < ActiveSupport::TestCase
def setup
@empty = EmptyController.new
- @empty.set_request!(ActionDispatch::Request.new({}))
+ @empty.set_request!(ActionDispatch::Request.empty)
@empty.set_response!(EmptyController.make_response!(@empty.request))
@contained = Submodule::ContainedEmptyController.new
@empty_controllers = [@empty, @contained]
diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb
index bc0ffd3eaa..d19b3810c2 100644
--- a/actionpack/test/controller/caching_test.rb
+++ b/actionpack/test/controller/caching_test.rb
@@ -419,3 +419,28 @@ class AutomaticCollectionCacheTest < ActionController::TestCase
assert_equal 1, @controller.partial_rendered_times
end
end
+
+class FragmentCacheKeyTestController < CachingController
+ attr_accessor :account_id
+
+ fragment_cache_key "v1"
+ fragment_cache_key { account_id }
+end
+
+class FragmentCacheKeyTest < ActionController::TestCase
+ def setup
+ super
+ @store = ActiveSupport::Cache::MemoryStore.new
+ @controller = FragmentCacheKeyTestController.new
+ @controller.perform_caching = true
+ @controller.cache_store = @store
+ end
+
+ def test_fragment_cache_key
+ @controller.account_id = "123"
+ assert_equal 'views/v1/123/what a key', @controller.fragment_cache_key('what a key')
+
+ @controller.account_id = nil
+ assert_equal 'views/v1//what a key', @controller.fragment_cache_key('what a key')
+ end
+end
diff --git a/actionpack/test/controller/helper_test.rb b/actionpack/test/controller/helper_test.rb
index 3ecfedefd1..feb882a2b3 100644
--- a/actionpack/test/controller/helper_test.rb
+++ b/actionpack/test/controller/helper_test.rb
@@ -141,20 +141,10 @@ class HelperTest < ActiveSupport::TestCase
def test_helper_for_nested_controller
assert_equal 'hello: Iz guuut!',
call_controller(Fun::GamesController, "render_hello_world").last.body
- # request = ActionController::TestRequest.new
- #
- # resp = Fun::GamesController.action(:render_hello_world).call(request.env)
- # assert_equal 'hello: Iz guuut!', resp.last.body
end
def test_helper_for_acronym_controller
assert_equal "test: baz", call_controller(Fun::PdfController, "test").last.body
- #
- # request = ActionController::TestRequest.new
- # response = ActionDispatch::TestResponse.new
- # request.action = 'test'
- #
- # assert_equal 'test: baz', Fun::PdfController.process(request, response).body
end
def test_default_helpers_only
diff --git a/actionpack/test/controller/http_token_authentication_test.rb b/actionpack/test/controller/http_token_authentication_test.rb
index 9c5a01c318..98e3c891a7 100644
--- a/actionpack/test/controller/http_token_authentication_test.rb
+++ b/actionpack/test/controller/http_token_authentication_test.rb
@@ -94,6 +94,14 @@ class HttpTokenAuthenticationTest < ActionController::TestCase
assert_response :success
end
+ test "authentication request with tab in header" do
+ @request.env['HTTP_AUTHORIZATION'] = "Token\ttoken=\"lifo\""
+ get :index
+
+ assert_response :success
+ assert_equal 'Hello Secret', @response.body
+ end
+
test "authentication request without credential" do
get :display
diff --git a/actionpack/test/controller/live_stream_test.rb b/actionpack/test/controller/live_stream_test.rb
index 843dafac06..aab2d9545d 100644
--- a/actionpack/test/controller/live_stream_test.rb
+++ b/actionpack/test/controller/live_stream_test.rb
@@ -442,3 +442,42 @@ module ActionController
end
end
end
+
+class LiveStreamRouterTest < ActionDispatch::IntegrationTest
+ class TestController < ActionController::Base
+ include ActionController::Live
+
+ def index
+ response.headers['Content-Type'] = 'text/event-stream'
+ sse = SSE.new(response.stream)
+ sse.write("{\"name\":\"John\"}")
+ sse.write({ name: "Ryan" })
+ ensure
+ sse.close
+ end
+ end
+
+ def self.call(env)
+ routes.call(env)
+ end
+
+ def self.routes
+ @routes ||= ActionDispatch::Routing::RouteSet.new
+ end
+
+ routes.draw do
+ get '/test' => 'live_stream_router_test/test#index'
+ end
+
+ def app
+ self.class
+ end
+
+ test "streaming served through the router" do
+ get "/test"
+
+ assert_response :ok
+ assert_match(/data: {\"name\":\"John\"}/, response.body)
+ assert_match(/data: {\"name\":\"Ryan\"}/, response.body)
+ end
+end
diff --git a/actionpack/test/controller/mime/respond_to_test.rb b/actionpack/test/controller/mime/respond_to_test.rb
index c025c7fa00..76e2d3ff43 100644
--- a/actionpack/test/controller/mime/respond_to_test.rb
+++ b/actionpack/test/controller/mime/respond_to_test.rb
@@ -661,10 +661,6 @@ class RespondToControllerTest < ActionController::TestCase
end
def test_variant_inline_syntax
- get :variant_inline_syntax, format: :js
- assert_equal "text/javascript", @response.content_type
- assert_equal "js", @response.body
-
get :variant_inline_syntax
assert_equal "text/html", @response.content_type
assert_equal "none", @response.body
@@ -674,6 +670,12 @@ class RespondToControllerTest < ActionController::TestCase
assert_equal "phone", @response.body
end
+ def test_variant_inline_syntax_with_format
+ get :variant_inline_syntax, format: :js
+ assert_equal "text/javascript", @response.content_type
+ assert_equal "js", @response.body
+ end
+
def test_variant_inline_syntax_without_block
get :variant_inline_syntax_without_block, params: { v: :phone }
assert_equal "text/html", @response.content_type
diff --git a/actionpack/test/controller/new_base/bare_metal_test.rb b/actionpack/test/controller/new_base/bare_metal_test.rb
index e61f4d241b..c226fa57ee 100644
--- a/actionpack/test/controller/new_base/bare_metal_test.rb
+++ b/actionpack/test/controller/new_base/bare_metal_test.rb
@@ -26,7 +26,7 @@ module BareMetalTest
test "response_body value is wrapped in an array when the value is a String" do
controller = BareController.new
- controller.set_request!(ActionDispatch::Request.new({}))
+ controller.set_request!(ActionDispatch::Request.empty)
controller.set_response!(BareController.make_response!(controller.request))
controller.index
assert_equal ["Hello world"], controller.response_body
diff --git a/actionpack/test/controller/parameters/parameters_permit_test.rb b/actionpack/test/controller/parameters/parameters_permit_test.rb
index 9f7d14e85d..f23aa599c1 100644
--- a/actionpack/test/controller/parameters/parameters_permit_test.rb
+++ b/actionpack/test/controller/parameters/parameters_permit_test.rb
@@ -256,7 +256,7 @@ class ParametersPermitTest < ActiveSupport::TestCase
end
test "to_h returns empty hash on unpermitted params" do
- assert @params.to_h.is_a? Hash
+ assert @params.to_h.is_a? ActiveSupport::HashWithIndifferentAccess
assert_not @params.to_h.is_a? ActionController::Parameters
assert @params.to_h.empty?
end
@@ -264,7 +264,7 @@ class ParametersPermitTest < ActiveSupport::TestCase
test "to_h returns converted hash on permitted params" do
@params.permit!
- assert @params.to_h.is_a? Hash
+ assert @params.to_h.is_a? ActiveSupport::HashWithIndifferentAccess
assert_not @params.to_h.is_a? ActionController::Parameters
end
@@ -273,7 +273,7 @@ class ParametersPermitTest < ActiveSupport::TestCase
ActionController::Parameters.permit_all_parameters = true
params = ActionController::Parameters.new(crab: "Senjougahara Hitagi")
- assert params.to_h.is_a? Hash
+ assert params.to_h.is_a? ActiveSupport::HashWithIndifferentAccess
assert_not @params.to_h.is_a? ActionController::Parameters
assert_equal({ "crab" => "Senjougahara Hitagi" }, params.to_h)
ensure
@@ -294,7 +294,35 @@ class ParametersPermitTest < ActiveSupport::TestCase
end
test "to_unsafe_h returns unfiltered params" do
- assert @params.to_h.is_a? Hash
+ assert @params.to_h.is_a? ActiveSupport::HashWithIndifferentAccess
assert_not @params.to_h.is_a? ActionController::Parameters
end
+
+ test "to_h only deep dups Ruby collections" do
+ company = Class.new do
+ attr_reader :dupped
+ def dup; @dupped = true; end
+ end.new
+
+ params = ActionController::Parameters.new(prem: { likes: %i( dancing ) })
+ assert_equal({ 'prem' => { 'likes' => %i( dancing ) } }, params.permit!.to_h)
+
+ params = ActionController::Parameters.new(companies: [ company, :acme ])
+ assert_equal({ 'companies' => [ company, :acme ] }, params.permit!.to_h)
+ assert_not company.dupped
+ end
+
+ test "to_unsafe_h only deep dups Ruby collections" do
+ company = Class.new do
+ attr_reader :dupped
+ def dup; @dupped = true; end
+ end.new
+
+ params = ActionController::Parameters.new(prem: { likes: %i( dancing ) })
+ assert_equal({ 'prem' => { 'likes' => %i( dancing ) } }, params.to_unsafe_h)
+
+ params = ActionController::Parameters.new(companies: [ company, :acme ])
+ assert_equal({ 'companies' => [ company, :acme ] }, params.to_unsafe_h)
+ assert_not company.dupped
+ end
end
diff --git a/actionpack/test/controller/redirect_test.rb b/actionpack/test/controller/redirect_test.rb
index 631ff7d02a..0b184eace9 100644
--- a/actionpack/test/controller/redirect_test.rb
+++ b/actionpack/test/controller/redirect_test.rb
@@ -42,6 +42,10 @@ class RedirectController < ActionController::Base
redirect_to :back, :status => 307
end
+ def redirect_back_with_status
+ redirect_back(fallback_location: "/things/stuff", status: 307)
+ end
+
def host_redirect
redirect_to :action => "other_host", :only_path => false, :host => 'other.test.host'
end
@@ -187,7 +191,11 @@ class RedirectTest < ActionController::TestCase
def test_redirect_to_back_with_status
@request.env["HTTP_REFERER"] = "http://www.example.com/coming/from"
- get :redirect_to_back_with_status
+
+ assert_deprecated do
+ get :redirect_to_back_with_status
+ end
+
assert_response 307
assert_equal "http://www.example.com/coming/from", redirect_to_url
end
@@ -236,7 +244,11 @@ class RedirectTest < ActionController::TestCase
def test_redirect_to_back
@request.env["HTTP_REFERER"] = "http://www.example.com/coming/from"
- get :redirect_to_back
+
+ assert_deprecated do
+ get :redirect_to_back
+ end
+
assert_response :redirect
assert_equal "http://www.example.com/coming/from", redirect_to_url
end
@@ -244,10 +256,32 @@ class RedirectTest < ActionController::TestCase
def test_redirect_to_back_with_no_referer
assert_raise(ActionController::RedirectBackError) {
@request.env["HTTP_REFERER"] = nil
+
+ assert_deprecated do
+ get :redirect_to_back
+ end
+
get :redirect_to_back
}
end
+ def test_redirect_back
+ referer = "http://www.example.com/coming/from"
+ @request.env["HTTP_REFERER"] = referer
+
+ get :redirect_back_with_status
+
+ assert_response 307
+ assert_equal referer, redirect_to_url
+ end
+
+ def test_redirect_back_with_no_referer
+ get :redirect_back_with_status
+
+ assert_response 307
+ assert_equal "http://test.host/things/stuff", redirect_to_url
+ end
+
def test_redirect_to_record
with_routing do |set|
set.draw do
@@ -273,10 +307,10 @@ class RedirectTest < ActionController::TestCase
end
def test_redirect_to_params
- error = assert_raise(ActionController::ActionControllerError) do
+ error = assert_raise(ArgumentError) do
get :redirect_to_params
end
- assert_equal "Cannot redirect to a parameter hash!", error.message
+ assert_equal "Generating an URL from non sanitized request parameters is insecure!", error.message
end
def test_redirect_to_with_block
diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb
index 94ffbe3cd0..87a8ed3dc9 100644
--- a/actionpack/test/controller/request_forgery_protection_test.rb
+++ b/actionpack/test/controller/request_forgery_protection_test.rb
@@ -304,6 +304,41 @@ module RequestForgeryProtectionTests
assert_not_blocked { put :index }
end
+ def test_should_allow_post_with_origin_checking_and_correct_origin
+ forgery_protection_origin_check do
+ session[:_csrf_token] = @token
+ @controller.stub :form_authenticity_token, @token do
+ assert_not_blocked do
+ @request.set_header 'HTTP_ORIGIN', 'http://test.host'
+ post :index, params: { custom_authenticity_token: @token }
+ end
+ end
+ end
+ end
+
+ def test_should_allow_post_with_origin_checking_and_no_origin
+ forgery_protection_origin_check do
+ session[:_csrf_token] = @token
+ @controller.stub :form_authenticity_token, @token do
+ assert_not_blocked do
+ post :index, params: { custom_authenticity_token: @token }
+ end
+ end
+ end
+ end
+
+ def test_should_block_post_with_origin_checking_and_wrong_origin
+ forgery_protection_origin_check do
+ session[:_csrf_token] = @token
+ @controller.stub :form_authenticity_token, @token do
+ assert_blocked do
+ @request.set_header 'HTTP_ORIGIN', 'http://bad.host'
+ post :index, params: { custom_authenticity_token: @token }
+ end
+ end
+ end
+ end
+
def test_should_warn_on_missing_csrf_token
old_logger = ActionController::Base.logger
logger = ActiveSupport::LogSubscriber::TestHelper::MockLogger.new
@@ -405,6 +440,16 @@ module RequestForgeryProtectionTests
def assert_cross_origin_not_blocked
assert_not_blocked { yield }
end
+
+ def forgery_protection_origin_check
+ old_setting = ActionController::Base.forgery_protection_origin_check
+ ActionController::Base.forgery_protection_origin_check = true
+ begin
+ yield
+ ensure
+ ActionController::Base.forgery_protection_origin_check = old_setting
+ end
+ end
end
# OK let's get our test on
@@ -495,10 +540,10 @@ class PrependProtectForgeryBaseControllerTest < ActionController::TestCase
assert_equal(expected_callback_order, @controller.called_callbacks)
end
- def test_verify_authenticity_token_is_prepended_by_default
+ def test_verify_authenticity_token_is_not_prepended_by_default
@controller = PrependDefaultController.new
get :index
- expected_callback_order = ["verify_authenticity_token", "custom_action"]
+ expected_callback_order = ["custom_action", "verify_authenticity_token"]
assert_equal(expected_callback_order, @controller.called_callbacks)
end
end
diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb
index 4a2b02a003..a39fede5b9 100644
--- a/actionpack/test/controller/routing_test.rb
+++ b/actionpack/test/controller/routing_test.rb
@@ -289,12 +289,6 @@ class LegacyRouteSetTests < ActiveSupport::TestCase
assert_equal({:id=>"1", :filters=>"foo", :format=>"js"}, params)
end
- def test_draw_with_block_arity_one_raises
- assert_raise(RuntimeError) do
- rs.draw { |map| map.match '/:controller(/:action(/:id))' }
- end
- end
-
def test_specific_controller_action_failure
rs.draw do
mount lambda {} => "/foo"
diff --git a/actionpack/test/controller/test_case_test.rb b/actionpack/test/controller/test_case_test.rb
index e50373a0cc..b9caddcdb7 100644
--- a/actionpack/test/controller/test_case_test.rb
+++ b/actionpack/test/controller/test_case_test.rb
@@ -172,7 +172,7 @@ XML
before_action { @dynamic_opt = 'opt' }
def test_url_options_reset
- render plain: url_for(params)
+ render plain: url_for
end
def default_url_options
diff --git a/actionpack/test/controller/url_for_test.rb b/actionpack/test/controller/url_for_test.rb
index 78e883f134..67212fea38 100644
--- a/actionpack/test/controller/url_for_test.rb
+++ b/actionpack/test/controller/url_for_test.rb
@@ -375,6 +375,13 @@ module AbstractController
assert_equal({'query[person][position][]' => 'prof' }.to_query, params[3])
end
+ def test_url_action_controller_parameters
+ add_host!
+ assert_raise(ArgumentError) do
+ W.new.url_for(ActionController::Parameters.new(:controller => 'c', :action => 'a', protocol: 'javascript', f: '%0Aeval(name)'))
+ end
+ end
+
def test_path_generation_for_symbol_parameter_keys
assert_generates("/image", :controller=> :image)
end
diff --git a/actionpack/test/dispatch/cookies_test.rb b/actionpack/test/dispatch/cookies_test.rb
index 84c244c72a..dfcef14344 100644
--- a/actionpack/test/dispatch/cookies_test.rb
+++ b/actionpack/test/dispatch/cookies_test.rb
@@ -7,7 +7,7 @@ class CookieJarTest < ActiveSupport::TestCase
attr_reader :request
def setup
- @request = ActionDispatch::Request.new({})
+ @request = ActionDispatch::Request.empty
end
def test_fetch
diff --git a/actionpack/test/dispatch/debug_exceptions_test.rb b/actionpack/test/dispatch/debug_exceptions_test.rb
index 8960156d00..159bf10545 100644
--- a/actionpack/test/dispatch/debug_exceptions_test.rb
+++ b/actionpack/test/dispatch/debug_exceptions_test.rb
@@ -75,6 +75,13 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
end
end
+ class BoomerAPI < Boomer
+ def call(env)
+ env['action_dispatch.show_detailed_exceptions'] = @detailed
+ raise "puke!"
+ end
+ end
+
RoutesApp = Struct.new(:routes).new(SharedTestRoutes)
ProductionApp = ActionDispatch::DebugExceptions.new(Boomer.new(false), RoutesApp)
DevelopmentApp = ActionDispatch::DebugExceptions.new(Boomer.new(true), RoutesApp)
@@ -166,6 +173,14 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
assert_equal "text/plain", response.content_type
assert_match(/RuntimeError\npuke/, body)
+ Rails.stub :root, Pathname.new('.') do
+ get "/", headers: xhr_request_env
+
+ assert_response 500
+ assert_match 'Extracted source (around line #', body
+ assert_select 'pre', { count: 0 }, body
+ end
+
get "/not_found", headers: xhr_request_env
assert_response 404
assert_no_match(/<body>/, body)
@@ -197,6 +212,68 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest
assert_match(/ActionController::ParameterMissing/, body)
end
+ test "rescue with json error for API request" do
+ @app = ActionDispatch::DebugExceptions.new(Boomer.new(true), RoutesApp, :api)
+
+ get "/", headers: { 'action_dispatch.show_exceptions' => true }
+ assert_response 500
+ assert_no_match(/<header>/, body)
+ assert_no_match(/<body>/, body)
+ assert_equal "application/json", response.content_type
+ assert_match(/RuntimeError: puke/, body)
+
+ get "/not_found", headers: { 'action_dispatch.show_exceptions' => true }
+ assert_response 404
+ assert_no_match(/<body>/, body)
+ assert_equal "application/json", response.content_type
+ assert_match(/#{AbstractController::ActionNotFound.name}/, body)
+
+ get "/method_not_allowed", headers: { 'action_dispatch.show_exceptions' => true }
+ assert_response 405
+ assert_no_match(/<body>/, body)
+ assert_equal "application/json", response.content_type
+ assert_match(/ActionController::MethodNotAllowed/, body)
+
+ get "/unknown_http_method", headers: { 'action_dispatch.show_exceptions' => true }
+ assert_response 405
+ assert_no_match(/<body>/, body)
+ assert_equal "application/json", response.content_type
+ assert_match(/ActionController::UnknownHttpMethod/, body)
+
+ get "/bad_request", headers: { 'action_dispatch.show_exceptions' => true }
+ assert_response 400
+ assert_no_match(/<body>/, body)
+ assert_equal "application/json", response.content_type
+ assert_match(/ActionController::BadRequest/, body)
+
+ get "/parameter_missing", headers: { 'action_dispatch.show_exceptions' => true }
+ assert_response 400
+ assert_no_match(/<body>/, body)
+ assert_equal "application/json", response.content_type
+ assert_match(/ActionController::ParameterMissing/, body)
+ end
+
+ test "rescue with json on API request returns only allowed formats or json as a fallback" do
+ @app = ActionDispatch::DebugExceptions.new(Boomer.new(true), RoutesApp, :api)
+
+ get "/index.json", headers: { 'action_dispatch.show_exceptions' => true }
+ assert_response 500
+ assert_equal "application/json", response.content_type
+ assert_match(/RuntimeError: puke/, body)
+
+ get "/index.html", headers: { 'action_dispatch.show_exceptions' => true }
+ assert_response 500
+ assert_no_match(/<header>/, body)
+ assert_no_match(/<body>/, body)
+ assert_equal "application/json", response.content_type
+ assert_match(/RuntimeError: puke/, body)
+
+ get "/index.xml", headers: { 'action_dispatch.show_exceptions' => true }
+ assert_response 500
+ assert_equal "application/xml", response.content_type
+ assert_match(/RuntimeError: puke/, body)
+ end
+
test "does not show filtered parameters" do
@app = DevelopmentApp
diff --git a/actionpack/test/dispatch/live_response_test.rb b/actionpack/test/dispatch/live_response_test.rb
index 160cdc1582..e4475f4233 100644
--- a/actionpack/test/dispatch/live_response_test.rb
+++ b/actionpack/test/dispatch/live_response_test.rb
@@ -6,7 +6,7 @@ module ActionController
class ResponseTest < ActiveSupport::TestCase
def setup
@response = Live::Response.new
- @response.request = ActionDispatch::Request.new({}) #yolo
+ @response.request = ActionDispatch::Request.empty
end
def test_header_merge
diff --git a/actionpack/test/dispatch/mapper_test.rb b/actionpack/test/dispatch/mapper_test.rb
index e783df855e..df27e41997 100644
--- a/actionpack/test/dispatch/mapper_test.rb
+++ b/actionpack/test/dispatch/mapper_test.rb
@@ -158,7 +158,7 @@ module ActionDispatch
assert_equal '/*path.:format', fakeset.asts.first.to_s
end
- def test_raising_helpful_error_on_invalid_arguments
+ def test_raising_error_when_path_is_not_passed
fakeset = FakeSet.new
mapper = Mapper.new fakeset
app = lambda { |env| [200, {}, [""]] }
@@ -166,6 +166,18 @@ module ActionDispatch
mapper.mount app
end
end
+
+ def test_raising_error_when_rack_app_is_not_passed
+ fakeset = FakeSet.new
+ mapper = Mapper.new fakeset
+ assert_raises ArgumentError do
+ mapper.mount 10, as: "exciting"
+ end
+
+ assert_raises ArgumentError do
+ mapper.mount as: "exciting"
+ end
+ end
end
end
end
diff --git a/actionpack/test/dispatch/request/session_test.rb b/actionpack/test/dispatch/request/session_test.rb
index ae0e7e93ed..7dcbcc5c21 100644
--- a/actionpack/test/dispatch/request/session_test.rb
+++ b/actionpack/test/dispatch/request/session_test.rb
@@ -7,7 +7,7 @@ module ActionDispatch
attr_reader :req
def setup
- @req = ActionDispatch::Request.new({})
+ @req = ActionDispatch::Request.empty
end
def test_create_adds_itself_to_env
diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb
index 22240699d9..7dd9d05e62 100644
--- a/actionpack/test/dispatch/request_test.rb
+++ b/actionpack/test/dispatch/request_test.rb
@@ -4,9 +4,13 @@ class BaseRequestTest < ActiveSupport::TestCase
def setup
@env = {
:ip_spoofing_check => true,
- :tld_length => 1,
"rack.input" => "foo"
}
+ @original_tld_length = ActionDispatch::Http::URL.tld_length
+ end
+
+ def teardown
+ ActionDispatch::Http::URL.tld_length = @original_tld_length
end
def url_for(options = {})
@@ -19,9 +23,9 @@ class BaseRequestTest < ActiveSupport::TestCase
ip_spoofing_check = env.key?(:ip_spoofing_check) ? env.delete(:ip_spoofing_check) : true
@trusted_proxies ||= nil
ip_app = ActionDispatch::RemoteIp.new(Proc.new { }, ip_spoofing_check, @trusted_proxies)
- tld_length = env.key?(:tld_length) ? env.delete(:tld_length) : 1
+ ActionDispatch::Http::URL.tld_length = env.delete(:tld_length) if env.key?(:tld_length)
+
ip_app.call(env)
- ActionDispatch::Http::URL.tld_length = tld_length
env = @env.merge(env)
ActionDispatch::Request.new(env)
@@ -254,15 +258,6 @@ end
class RequestDomain < BaseRequestTest
test "domains" do
- request = stub_request 'HTTP_HOST' => 'www.rubyonrails.org'
- assert_equal "rubyonrails.org", request.domain
-
- request = stub_request 'HTTP_HOST' => "www.rubyonrails.co.uk"
- assert_equal "rubyonrails.co.uk", request.domain(2)
-
- request = stub_request 'HTTP_HOST' => "www.rubyonrails.co.uk", :tld_length => 2
- assert_equal "rubyonrails.co.uk", request.domain
-
request = stub_request 'HTTP_HOST' => "192.168.1.200"
assert_nil request.domain
@@ -271,25 +266,18 @@ class RequestDomain < BaseRequestTest
request = stub_request 'HTTP_HOST' => "192.168.1.200.com"
assert_equal "200.com", request.domain
- end
- test "subdomains" do
- request = stub_request 'HTTP_HOST' => "www.rubyonrails.org"
- assert_equal %w( www ), request.subdomains
- assert_equal "www", request.subdomain
+ request = stub_request 'HTTP_HOST' => 'www.rubyonrails.org'
+ assert_equal "rubyonrails.org", request.domain
request = stub_request 'HTTP_HOST' => "www.rubyonrails.co.uk"
- assert_equal %w( www ), request.subdomains(2)
- assert_equal "www", request.subdomain(2)
-
- request = stub_request 'HTTP_HOST' => "dev.www.rubyonrails.co.uk"
- assert_equal %w( dev www ), request.subdomains(2)
- assert_equal "dev.www", request.subdomain(2)
+ assert_equal "rubyonrails.co.uk", request.domain(2)
- request = stub_request 'HTTP_HOST' => "dev.www.rubyonrails.co.uk", :tld_length => 2
- assert_equal %w( dev www ), request.subdomains
- assert_equal "dev.www", request.subdomain
+ request = stub_request 'HTTP_HOST' => "www.rubyonrails.co.uk", :tld_length => 2
+ assert_equal "rubyonrails.co.uk", request.domain
+ end
+ test "subdomains" do
request = stub_request 'HTTP_HOST' => "foobar.foobar.com"
assert_equal %w( foobar ), request.subdomains
assert_equal "foobar", request.subdomain
@@ -309,6 +297,22 @@ class RequestDomain < BaseRequestTest
request = stub_request 'HTTP_HOST' => nil
assert_equal [], request.subdomains
assert_equal "", request.subdomain
+
+ request = stub_request 'HTTP_HOST' => "www.rubyonrails.org"
+ assert_equal %w( www ), request.subdomains
+ assert_equal "www", request.subdomain
+
+ request = stub_request 'HTTP_HOST' => "www.rubyonrails.co.uk"
+ assert_equal %w( www ), request.subdomains(2)
+ assert_equal "www", request.subdomain(2)
+
+ request = stub_request 'HTTP_HOST' => "dev.www.rubyonrails.co.uk"
+ assert_equal %w( dev www ), request.subdomains(2)
+ assert_equal "dev.www", request.subdomain(2)
+
+ request = stub_request 'HTTP_HOST' => "dev.www.rubyonrails.co.uk", :tld_length => 2
+ assert_equal %w( dev www ), request.subdomains
+ assert_equal "dev.www", request.subdomain
end
end
@@ -1212,3 +1216,23 @@ class RequestVariant < BaseRequestTest
end
end
end
+
+class RequestFormData < BaseRequestTest
+ test 'media_type is from the FORM_DATA_MEDIA_TYPES array' do
+ assert stub_request('CONTENT_TYPE' => 'application/x-www-form-urlencoded').form_data?
+ assert stub_request('CONTENT_TYPE' => 'multipart/form-data').form_data?
+ end
+
+ test 'media_type is not from the FORM_DATA_MEDIA_TYPES array' do
+ assert !stub_request('CONTENT_TYPE' => 'application/xml').form_data?
+ assert !stub_request('CONTENT_TYPE' => 'multipart/related').form_data?
+ end
+
+ test 'no Content-Type header is provided and the request_method is POST' do
+ request = stub_request('REQUEST_METHOD' => 'POST')
+
+ assert_equal '', request.media_type
+ assert_equal 'POST', request.request_method
+ assert !request.form_data?
+ end
+end
diff --git a/actionpack/test/dispatch/response_test.rb b/actionpack/test/dispatch/response_test.rb
index 981d820ccf..c37679bc5f 100644
--- a/actionpack/test/dispatch/response_test.rb
+++ b/actionpack/test/dispatch/response_test.rb
@@ -5,6 +5,7 @@ require 'rack/content_length'
class ResponseTest < ActiveSupport::TestCase
def setup
@response = ActionDispatch::Response.create
+ @response.request = ActionDispatch::Request.empty
end
def test_can_wait_until_commit
@@ -39,6 +40,7 @@ class ResponseTest < ActiveSupport::TestCase
def test_response_body_encoding
body = ["hello".encode(Encoding::UTF_8)]
response = ActionDispatch::Response.new 200, {}, body
+ response.request = ActionDispatch::Request.empty
assert_equal Encoding::UTF_8, response.body.encoding
end
@@ -261,6 +263,7 @@ class ResponseTest < ActiveSupport::TestCase
test "can be explicitly destructured into status, headers and an enumerable body" do
response = ActionDispatch::Response.new(404, { 'Content-Type' => 'text/plain' }, ['Not Found'])
+ response.request = ActionDispatch::Request.empty
status, headers, body = *response
assert_equal 404, status
@@ -356,6 +359,7 @@ class ResponseIntegrationTest < ActionDispatch::IntegrationTest
resp.cache_control[:public] = true
resp.etag = '123'
resp.body = 'Hello'
+ resp.request = ActionDispatch::Request.empty
}.to_a
}
@@ -392,6 +396,7 @@ class ResponseIntegrationTest < ActionDispatch::IntegrationTest
resp.charset = 'utf-16'
resp.content_type = Mime[:xml]
resp.body = 'Hello'
+ resp.request = ActionDispatch::Request.empty
}.to_a
}
diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb
index 8972f3e74d..82222a141c 100644
--- a/actionpack/test/dispatch/routing_test.rb
+++ b/actionpack/test/dispatch/routing_test.rb
@@ -4592,3 +4592,44 @@ class TestDefaultUrlOptions < ActionDispatch::IntegrationTest
assert_equal '/en/posts/2014/12/13', archived_posts_path(2014, 12, 13)
end
end
+
+class TestErrorsInController < ActionDispatch::IntegrationTest
+ class ::PostsController < ActionController::Base
+ def foo
+ nil.i_do_not_exist
+ end
+
+ def bar
+ NonExistingClass.new
+ end
+ end
+
+ Routes = ActionDispatch::Routing::RouteSet.new
+ Routes.draw do
+ get '/:controller(/:action)'
+ end
+
+ APP = build_app Routes
+
+ def app
+ APP
+ end
+
+ def test_legit_no_method_errors_are_not_caught
+ get '/posts/foo'
+ assert_equal 500, response.status
+ end
+
+ def test_legit_name_errors_are_not_caught
+ get '/posts/bar'
+ assert_equal 500, response.status
+ end
+
+ def test_legit_routing_not_found_responses
+ get '/posts/baz'
+ assert_equal 404, response.status
+
+ get '/i_do_not_exist'
+ assert_equal 404, response.status
+ end
+end
diff --git a/actionpack/test/dispatch/show_exceptions_test.rb b/actionpack/test/dispatch/show_exceptions_test.rb
index ffdf775836..14894d4b82 100644
--- a/actionpack/test/dispatch/show_exceptions_test.rb
+++ b/actionpack/test/dispatch/show_exceptions_test.rb
@@ -8,7 +8,7 @@ class ShowExceptionsTest < ActionDispatch::IntegrationTest
case req.path
when "/not_found"
raise AbstractController::ActionNotFound
- when "/bad_params"
+ when "/bad_params", "/bad_params.json"
begin
raise StandardError.new
rescue
@@ -120,4 +120,18 @@ class ShowExceptionsTest < ActionDispatch::IntegrationTest
assert_response 405
assert_equal "", body
end
+
+ test "bad params exception is returned in the correct format" do
+ @app = ProductionApp
+
+ get "/bad_params", headers: { 'action_dispatch.show_exceptions' => true }
+ assert_equal "text/html; charset=utf-8", response.headers["Content-Type"]
+ assert_response 400
+ assert_match(/400 error/, body)
+
+ get "/bad_params.json", headers: { 'action_dispatch.show_exceptions' => true }
+ assert_equal "application/json; charset=utf-8", response.headers["Content-Type"]
+ assert_response 400
+ assert_equal("{\"status\":400,\"error\":\"Bad Request\"}", body)
+ end
end
diff --git a/actionpack/test/dispatch/url_generation_test.rb b/actionpack/test/dispatch/url_generation_test.rb
index fd4ede4d1b..8c9782bb90 100644
--- a/actionpack/test/dispatch/url_generation_test.rb
+++ b/actionpack/test/dispatch/url_generation_test.rb
@@ -129,6 +129,13 @@ module TestUrlGeneration
)
end
+ test "generating URLS with empty querystring" do
+ assert_equal "/bars.json", bars_path(
+ a: {},
+ format: 'json'
+ )
+ end
+
end
end
diff --git a/actionview/CHANGELOG.md b/actionview/CHANGELOG.md
index 0981d47d7a..e26e7337e4 100644
--- a/actionview/CHANGELOG.md
+++ b/actionview/CHANGELOG.md
@@ -1,3 +1,17 @@
+## Rails 5.0.0.beta1 (December 18, 2015) ##
+
+* No changes.
+
+
+* `I18n.translate` helper will wrap the missing translation keys
+ in a <span> tag only if `debug_missing_translation` configuration
+ be true. Default value is `true`. For example in `application.rb`:
+
+ # in order to turn off missing key wrapping
+ config.action_view.debug_missing_translation = false
+
+ *Sameer Rahmani*
+
* Respect value of `:object` if `:object` is false when rendering.
Fixes #22260.
@@ -35,16 +49,16 @@
*Bernerd Schaefer*
-* `number_to_currency` and `number_with_delimiter` now accept custom `delimiter_pattern` option
- to handle placement of delimiter, to support currency formats like INR
-
- Example:
-
+* `number_to_currency` and `number_with_delimiter` now accept a custom `delimiter_pattern` option
+ to handle placement of delimiter, to support currency formats like INR.
+
+ Example:
+
number_to_currency(1230000, delimiter_pattern: /(\d+?)(?=(\d\d)+(\d)(?!\d))/, unit: '₹', format: "%u %n")
- # => '₹ 12,30,000.00'
-
+ # => '₹ 12,30,000.00'
+
*Vipul A M*
-
+
* Make `disable_with` the default behavior for submit tags. Disables the
button on submit to prevent double submits.
diff --git a/actionview/README.rdoc b/actionview/README.rdoc
index 8b1f85f748..7a3e5e31d0 100644
--- a/actionview/README.rdoc
+++ b/actionview/README.rdoc
@@ -9,7 +9,7 @@ used to inline short Ruby snippets inside HTML), and XML Builder.
The latest version of Action View can be installed with RubyGems:
- % gem install actionview
+ $ gem install actionview
Source code can be downloaded as part of the Rails project on GitHub
@@ -36,4 +36,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/actionview/lib/action_view/gem_version.rb b/actionview/lib/action_view/gem_version.rb
index 4f45f5b8c8..20d408741e 100644
--- a/actionview/lib/action_view/gem_version.rb
+++ b/actionview/lib/action_view/gem_version.rb
@@ -8,7 +8,7 @@ module ActionView
MAJOR = 5
MINOR = 0
TINY = 0
- PRE = "alpha"
+ PRE = "beta1"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/actionview/lib/action_view/helpers/asset_tag_helper.rb b/actionview/lib/action_view/helpers/asset_tag_helper.rb
index 2ffed6b395..91e934cd64 100644
--- a/actionview/lib/action_view/helpers/asset_tag_helper.rb
+++ b/actionview/lib/action_view/helpers/asset_tag_helper.rb
@@ -205,6 +205,8 @@ module ActionView
# # => <img alt="Icon" height="32" src="/icons/icon.gif" width="32" />
# image_tag("/icons/icon.gif", class: "menu_icon")
# # => <img alt="Icon" class="menu_icon" src="/icons/icon.gif" />
+ # image_tag("/icons/icon.gif", data: { title: 'Rails Application' })
+ # # => <img data-title="Rails Application" src="/icons/icon.gif" />
def image_tag(source, options={})
options = options.symbolize_keys
check_for_image_tag_errors(options)
diff --git a/actionview/lib/action_view/helpers/cache_helper.rb b/actionview/lib/action_view/helpers/cache_helper.rb
index e473aeaea9..18b2102d73 100644
--- a/actionview/lib/action_view/helpers/cache_helper.rb
+++ b/actionview/lib/action_view/helpers/cache_helper.rb
@@ -216,14 +216,6 @@ module ActionView
end
end
- # Given a key (as described in ActionController::Caching::Fragments.expire_fragment),
- # returns a key suitable for use in reading, writing, or expiring a
- # cached fragment. All keys are prefixed with <tt>views/</tt> and uses
- # ActiveSupport::Cache.expand_cache_key for the expansion.
- def fragment_cache_key(key)
- ActiveSupport::Cache.expand_cache_key(key.is_a?(Hash) ? url_for(key).split("://").last : key, :views)
- end
-
private
def fragment_name_with_digest(name, virtual_path) #:nodoc:
diff --git a/actionview/lib/action_view/helpers/translation_helper.rb b/actionview/lib/action_view/helpers/translation_helper.rb
index 4c4d2c4457..152e1b1211 100644
--- a/actionview/lib/action_view/helpers/translation_helper.rb
+++ b/actionview/lib/action_view/helpers/translation_helper.rb
@@ -6,7 +6,15 @@ module ActionView
# = Action View Translation Helpers
module Helpers
module TranslationHelper
+ extend ActiveSupport::Concern
+
include TagHelper
+
+ included do
+ mattr_accessor :debug_missing_translation
+ self.debug_missing_translation = true
+ end
+
# Delegates to <tt>I18n#translate</tt> but also performs three additional
# functions.
#
@@ -95,6 +103,8 @@ module ActionView
title << ", " << interpolations.map { |k, v| "#{k}: #{ERB::Util.html_escape(v)}" }.join(', ')
end
+ return title unless ActionView::Base.debug_missing_translation
+
content_tag('span', keys.last.to_s.titleize, class: 'translation_missing', title: title)
end
end
diff --git a/actionview/lib/action_view/railtie.rb b/actionview/lib/action_view/railtie.rb
index e829d86c99..59d869d92d 100644
--- a/actionview/lib/action_view/railtie.rb
+++ b/actionview/lib/action_view/railtie.rb
@@ -6,6 +6,7 @@ module ActionView
class Railtie < Rails::Railtie # :nodoc:
config.action_view = ActiveSupport::OrderedOptions.new
config.action_view.embed_authenticity_token_in_remote_forms = false
+ config.action_view.debug_missing_translation = true
config.eager_load_namespaces << ActionView
diff --git a/actionview/lib/action_view/testing/resolvers.rb b/actionview/lib/action_view/testing/resolvers.rb
index dfb7d463b4..63a60542d4 100644
--- a/actionview/lib/action_view/testing/resolvers.rb
+++ b/actionview/lib/action_view/testing/resolvers.rb
@@ -46,9 +46,8 @@ module ActionView #:nodoc:
class NullResolver < PathResolver
def query(path, exts, formats)
handler, format, variant = extract_handler_and_format_and_variant(path, formats)
- [ActionView::Template.new("Template generated by Null Resolver", path, handler, :virtual_path => path, :format => format, :variant => variant)]
+ [ActionView::Template.new("Template generated by Null Resolver", path.virtual, handler, :virtual_path => path.virtual, :format => format, :variant => variant)]
end
end
-
end
diff --git a/actionview/test/abstract_unit.rb b/actionview/test/abstract_unit.rb
index 2354e91822..79173f730f 100644
--- a/actionview/test/abstract_unit.rb
+++ b/actionview/test/abstract_unit.rb
@@ -280,7 +280,6 @@ def jruby_skip(message = '')
skip message if defined?(JRUBY_VERSION)
end
-require 'mocha/setup' # FIXME: stop using mocha
class ActiveSupport::TestCase
include ActiveSupport::Testing::MethodCallAssertions
end
diff --git a/actionview/test/template/asset_tag_helper_test.rb b/actionview/test/template/asset_tag_helper_test.rb
index a63ac442cd..8592a2a083 100644
--- a/actionview/test/template/asset_tag_helper_test.rb
+++ b/actionview/test/template/asset_tag_helper_test.rb
@@ -27,6 +27,8 @@ class AssetTagHelperTest < ActionView::TestCase
end
AssetPathToTag = {
+ %(asset_path("")) => %(),
+ %(asset_path(" ")) => %(),
%(asset_path("foo")) => %(/foo),
%(asset_path("style.css")) => %(/style.css),
%(asset_path("xmlhr.js")) => %(/xmlhr.js),
@@ -193,7 +195,8 @@ class AssetTagHelperTest < ActionView::TestCase
%(image_tag("//www.rubyonrails.com/images/rails.png")) => %(<img alt="Rails" src="//www.rubyonrails.com/images/rails.png" />),
%(image_tag("mouse.png", :alt => nil)) => %(<img src="/images/mouse.png" />),
%(image_tag("data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==", :alt => nil)) => %(<img src="data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" />),
- %(image_tag("")) => %(<img src="" />)
+ %(image_tag("")) => %(<img src="" />),
+ %(image_tag("gold.png", data: { title: 'Rails Application' })) => %(<img data-title="Rails Application" src="/images/gold.png" alt="Gold" />)
}
FaviconLinkToTag = {
diff --git a/actionview/test/template/date_helper_i18n_test.rb b/actionview/test/template/date_helper_i18n_test.rb
index 21fca35185..52aef56a61 100644
--- a/actionview/test/template/date_helper_i18n_test.rb
+++ b/actionview/test/template/date_helper_i18n_test.rb
@@ -46,8 +46,9 @@ class DateHelperDistanceOfTimeInWordsI18nTests < ActiveSupport::TestCase
end
def test_time_ago_in_words_passes_locale
- I18n.expects(:t).with(:less_than_x_minutes, :scope => :'datetime.distance_in_words', :count => 1, :locale => 'ru')
- time_ago_in_words(15.seconds.ago, :locale => 'ru')
+ assert_called_with(I18n, :t, [:less_than_x_minutes, :scope => :'datetime.distance_in_words', :count => 1, :locale => 'ru']) do
+ time_ago_in_words(15.seconds.ago, :locale => 'ru')
+ end
end
def test_distance_of_time_pluralizations
@@ -80,8 +81,9 @@ class DateHelperDistanceOfTimeInWordsI18nTests < ActiveSupport::TestCase
options = { locale: 'en', scope: :'datetime.distance_in_words' }.merge!(expected_options)
options[:count] = count if count
- I18n.expects(:t).with(key, options)
- distance_of_time_in_words(@from, to, passed_options.merge(locale: 'en'))
+ assert_called_with(I18n, :t, [key, options]) do
+ distance_of_time_in_words(@from, to, passed_options.merge(locale: 'en'))
+ end
end
end
@@ -89,60 +91,74 @@ class DateHelperSelectTagsI18nTests < ActiveSupport::TestCase
include ActionView::Helpers::DateHelper
attr_reader :request
- def setup
- @prompt_defaults = {:year => 'Year', :month => 'Month', :day => 'Day', :hour => 'Hour', :minute => 'Minute', :second => 'Seconds'}
-
- I18n.stubs(:translate).with(:'date.month_names', :locale => 'en').returns Date::MONTHNAMES
- end
-
# select_month
def test_select_month_given_use_month_names_option_does_not_translate_monthnames
- I18n.expects(:translate).never
- select_month(8, :locale => 'en', :use_month_names => Date::MONTHNAMES)
+ assert_not_called(I18n, :translate) do
+ select_month(8, :locale => 'en', :use_month_names => Date::MONTHNAMES)
+ end
end
def test_select_month_translates_monthnames
- I18n.expects(:translate).with(:'date.month_names', :locale => 'en').returns Date::MONTHNAMES
- select_month(8, :locale => 'en')
+ assert_called_with(I18n, :translate, [:'date.month_names', :locale => 'en'], returns: Date::MONTHNAMES) do
+ select_month(8, :locale => 'en')
+ end
end
def test_select_month_given_use_short_month_option_translates_abbr_monthnames
- I18n.expects(:translate).with(:'date.abbr_month_names', :locale => 'en').returns Date::ABBR_MONTHNAMES
- select_month(8, :locale => 'en', :use_short_month => true)
+ assert_called_with(I18n, :translate, [:'date.abbr_month_names', :locale => 'en'], returns: Date::ABBR_MONTHNAMES) do
+ select_month(8, :locale => 'en', :use_short_month => true)
+ end
end
def test_date_or_time_select_translates_prompts
- @prompt_defaults.each do |key, prompt|
- I18n.expects(:translate).with(('datetime.prompts.' + key.to_s).to_sym, :locale => 'en').returns prompt
+ prompt_defaults = {:year => 'Year', :month => 'Month', :day => 'Day', :hour => 'Hour', :minute => 'Minute', :second => 'Seconds'}
+ defaults = {[:'date.order', :locale => 'en', :default => []] => %w(year month day)}
+
+ prompt_defaults.each do |key, prompt|
+ defaults[[('datetime.prompts.' + key.to_s).to_sym, :locale => 'en']] = prompt
+ end
+
+ prompts_check = -> (prompt, x) do
+ @prompt_called ||= 0
+
+ return_value = defaults[[prompt, x]]
+ @prompt_called += 1 if return_value.present?
+
+ return_value
end
- I18n.expects(:translate).with(:'date.order', :locale => 'en', :default => []).returns %w(year month day)
- datetime_select('post', 'updated_at', :locale => 'en', :include_seconds => true, :prompt => true)
+ I18n.stub(:translate, prompts_check) do
+ datetime_select('post', 'updated_at', :locale => 'en', :include_seconds => true, :prompt => true, :use_month_names => Date::MONTHNAMES)
+ end
+ assert_equal defaults.count, @prompt_called
end
# date_or_time_select
def test_date_or_time_select_given_an_order_options_does_not_translate_order
- I18n.expects(:translate).never
- datetime_select('post', 'updated_at', :order => [:year, :month, :day], :locale => 'en')
+ assert_not_called(I18n, :translate) do
+ datetime_select('post', 'updated_at', :order => [:year, :month, :day], :locale => 'en', :use_month_names => Date::MONTHNAMES)
+ end
end
def test_date_or_time_select_given_no_order_options_translates_order
- I18n.expects(:translate).with(:'date.order', :locale => 'en', :default => []).returns %w(year month day)
- datetime_select('post', 'updated_at', :locale => 'en')
+ assert_called_with(I18n, :translate, [ [:'date.order', :locale => 'en', :default => []], [:"date.month_names", {:locale=>"en"}] ], returns: %w(year month day)) do
+ datetime_select('post', 'updated_at', :locale => 'en')
+ end
end
def test_date_or_time_select_given_invalid_order
- I18n.expects(:translate).with(:'date.order', :locale => 'en', :default => []).returns %w(invalid month day)
-
- assert_raise StandardError do
- datetime_select('post', 'updated_at', :locale => 'en')
+ assert_called_with(I18n, :translate, [:'date.order', :locale => 'en', :default => []], returns: %w(invalid month day)) do
+ assert_raise StandardError do
+ datetime_select('post', 'updated_at', :locale => 'en')
+ end
end
end
def test_date_or_time_select_given_symbol_keys
- I18n.expects(:translate).with(:'date.order', :locale => 'en', :default => []).returns [:year, :month, :day]
- datetime_select('post', 'updated_at', :locale => 'en')
+ assert_called_with(I18n, :translate, [ [:'date.order', :locale => 'en', :default => []], [:"date.month_names", {:locale=>"en"}] ], returns: [:year, :month, :day]) do
+ datetime_select('post', 'updated_at', :locale => 'en')
+ end
end
end
diff --git a/actionview/test/template/date_helper_test.rb b/actionview/test/template/date_helper_test.rb
index c4234a71c3..92e77599f4 100644
--- a/actionview/test/template/date_helper_test.rb
+++ b/actionview/test/template/date_helper_test.rb
@@ -390,11 +390,6 @@ class DateHelperTest < ActionView::TestCase
expected << "</select>\n"
assert_dom_equal expected, select_month(Time.mktime(2003, 8, 16), {}, :class => 'selector', :accesskey => 'M')
- #result = select_month(Time.mktime(2003, 8, 16), {}, :class => 'selector', :accesskey => 'M')
- #assert result.include?('<select id="date_month" name="date[month]"')
- #assert result.include?('class="selector"')
- #assert result.include?('accesskey="M"')
- #assert result.include?('<option value="1">January')
end
def test_select_month_with_default_prompt
@@ -474,11 +469,6 @@ class DateHelperTest < ActionView::TestCase
expected << "</select>\n"
assert_dom_equal expected, select_year(Time.mktime(2003, 8, 16), {:start_year => 2003, :end_year => 2005}, :class => 'selector', :accesskey => 'M')
- #result = select_year(Time.mktime(2003, 8, 16), {:start_year => 2003, :end_year => 2005}, :class => 'selector', :accesskey => 'M')
- #assert result.include?('<select id="date_year" name="date[year]"')
- #assert result.include?('class="selector"')
- #assert result.include?('accesskey="M"')
- #assert result.include?('<option value="2003"')
end
def test_select_year_with_default_prompt
@@ -639,12 +629,6 @@ class DateHelperTest < ActionView::TestCase
expected << "</select>\n"
assert_dom_equal expected, select_minute(Time.mktime(2003, 8, 16, 8, 4, 18), {}, :class => 'selector', :accesskey => 'M')
-
- #result = select_minute(Time.mktime(2003, 8, 16, 8, 4, 18), {}, :class => 'selector', :accesskey => 'M')
- #assert result.include?('<select id="date_minute" name="date[minute]"')
- #assert result.include?('class="selector"')
- #assert result.include?('accesskey="M"')
- #assert result.include?('<option value="00">00')
end
def test_select_minute_with_default_prompt
@@ -709,12 +693,6 @@ class DateHelperTest < ActionView::TestCase
expected << "</select>\n"
assert_dom_equal expected, select_second(Time.mktime(2003, 8, 16, 8, 4, 18), {}, :class => 'selector', :accesskey => 'M')
-
- #result = select_second(Time.mktime(2003, 8, 16, 8, 4, 18), {}, :class => 'selector', :accesskey => 'M')
- #assert result.include?('<select id="date_second" name="date[second]"')
- #assert result.include?('class="selector"')
- #assert result.include?('accesskey="M"')
- #assert result.include?('<option value="00">00')
end
def test_select_second_with_default_prompt
diff --git a/actionview/test/template/form_options_helper_test.rb b/actionview/test/template/form_options_helper_test.rb
index d7daba8bf3..6b97cec34c 100644
--- a/actionview/test/template/form_options_helper_test.rb
+++ b/actionview/test/template/form_options_helper_test.rb
@@ -17,13 +17,37 @@ class FormOptionsHelperTest < ActionView::TestCase
Album = Struct.new('Album', :id, :title, :genre)
end
- def setup
- @fake_timezones = %w(A B C D E).map do |id|
- tz = stub(:name => id, :to_s => id)
- ActiveSupport::TimeZone.stubs(:[]).with(id).returns(tz)
- tz
+ module FakeZones
+ FakeZone = Struct.new(:name) do
+ def to_s; name; end
end
- ActiveSupport::TimeZone.stubs(:all).returns(@fake_timezones)
+
+ module ClassMethods
+ def [](id); fake_zones ? fake_zones[id] : super; end
+ def all; fake_zones ? fake_zones.values : super; end
+ def dummy; :test; end
+ end
+
+ def self.prepended(base)
+ class << base
+ mattr_accessor(:fake_zones)
+ prepend ClassMethods
+ end
+ end
+ end
+
+ ActiveSupport::TimeZone.prepend FakeZones
+
+ setup do
+ ActiveSupport::TimeZone.fake_zones = %w(A B C D E).map do |id|
+ [ id, FakeZones::FakeZone.new(id) ]
+ end.to_h
+
+ @fake_timezones = ActiveSupport::TimeZone.all
+ end
+
+ teardown do
+ ActiveSupport::TimeZone.fake_zones = nil
end
def test_collection_options
@@ -1163,8 +1187,8 @@ class FormOptionsHelperTest < ActionView::TestCase
def test_time_zone_select_with_priority_zones_as_regexp
@firm = Firm.new("D")
- @fake_timezones.each_with_index do |tz, i|
- tz.stubs(:=~).returns(i.zero? || i == 3)
+ @fake_timezones.each do |tz|
+ def tz.=~(re); %(A D).include?(name) end
end
html = time_zone_select("firm", "time_zone", /A|D/)
@@ -1179,15 +1203,16 @@ class FormOptionsHelperTest < ActionView::TestCase
html
end
- def test_time_zone_select_with_priority_zones_as_regexp_using_grep_finds_no_zones
+ def test_time_zone_select_with_priority_zones_is_not_implemented_with_grep
@firm = Firm.new("D")
- priority_zones = /A|D/
+ # `time_zone_select` can't be written with `grep` because Active Support
+ # time zones don't support implicit string coercion with `to_str`.
@fake_timezones.each do |tz|
- priority_zones.stubs(:===).with(tz).raises(Exception)
+ def tz.===(zone); raise Exception; end
end
- html = time_zone_select("firm", "time_zone", priority_zones)
+ html = time_zone_select("firm", "time_zone", /A|D/)
assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" +
"<option value=\"\" disabled=\"disabled\">-------------</option>\n" +
"<option value=\"A\">A</option>\n" +
diff --git a/actionview/test/template/log_subscriber_test.rb b/actionview/test/template/log_subscriber_test.rb
index 7f4c84929f..4776c18b0b 100644
--- a/actionview/test/template/log_subscriber_test.rb
+++ b/actionview/test/template/log_subscriber_test.rb
@@ -12,13 +12,18 @@ class AVLogSubscriberTest < ActiveSupport::TestCase
lookup_context = ActionView::LookupContext.new(view_paths, {}, ["test"])
renderer = ActionView::Renderer.new(lookup_context)
@view = ActionView::Base.new(renderer, {})
- Rails.stubs(:root).returns(File.expand_path(FIXTURE_LOAD_PATH))
ActionView::LogSubscriber.attach_to :action_view
+ unless Rails.respond_to?(:root)
+ @defined_root = true
+ def Rails.root; :defined_root; end # Minitest `stub` expects the method to be defined.
+ end
end
def teardown
super
ActiveSupport::LogSubscriber.log_subscribers.clear
+ # We need to undef `root`, RenderTestCases don't want this to be defined
+ Rails.instance_eval { undef :root } if @defined_root
end
def set_logger(logger)
@@ -26,66 +31,82 @@ class AVLogSubscriberTest < ActiveSupport::TestCase
end
def test_render_file_template
- @view.render(:file => "test/hello_world")
- wait
+ Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do
+ @view.render(:file => "test/hello_world")
+ wait
- assert_equal 1, @logger.logged(:info).size
- assert_match(/Rendered test\/hello_world\.erb/, @logger.logged(:info).last)
+ assert_equal 1, @logger.logged(:info).size
+ assert_match(/Rendered test\/hello_world\.erb/, @logger.logged(:info).last)
+ end
end
def test_render_text_template
- @view.render(:text => "TEXT")
- wait
+ Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do
+ @view.render(:text => "TEXT")
+ wait
- assert_equal 1, @logger.logged(:info).size
- assert_match(/Rendered text template/, @logger.logged(:info).last)
+ assert_equal 1, @logger.logged(:info).size
+ assert_match(/Rendered text template/, @logger.logged(:info).last)
+ end
end
def test_render_inline_template
- @view.render(:inline => "<%= 'TEXT' %>")
- wait
+ Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do
+ @view.render(:inline => "<%= 'TEXT' %>")
+ wait
- assert_equal 1, @logger.logged(:info).size
- assert_match(/Rendered inline template/, @logger.logged(:info).last)
+ assert_equal 1, @logger.logged(:info).size
+ assert_match(/Rendered inline template/, @logger.logged(:info).last)
+ end
end
def test_render_partial_template
- @view.render(:partial => "test/customer")
- wait
+ Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do
+ @view.render(:partial => "test/customer")
+ wait
- assert_equal 1, @logger.logged(:info).size
- assert_match(/Rendered test\/_customer.erb/, @logger.logged(:info).last)
+ assert_equal 1, @logger.logged(:info).size
+ assert_match(/Rendered test\/_customer.erb/, @logger.logged(:info).last)
+ end
end
def test_render_partial_with_implicit_path
- @view.render(Customer.new("david"), :greeting => "hi")
- wait
+ Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do
+ @view.render(Customer.new("david"), :greeting => "hi")
+ wait
- assert_equal 1, @logger.logged(:info).size
- assert_match(/Rendered customers\/_customer\.html\.erb/, @logger.logged(:info).last)
+ assert_equal 1, @logger.logged(:info).size
+ assert_match(/Rendered customers\/_customer\.html\.erb/, @logger.logged(:info).last)
+ end
end
def test_render_collection_template
- @view.render(:partial => "test/customer", :collection => [ Customer.new("david"), Customer.new("mary") ])
- wait
+ Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do
+ @view.render(:partial => "test/customer", :collection => [ Customer.new("david"), Customer.new("mary") ])
+ wait
- assert_equal 1, @logger.logged(:info).size
- assert_match(/Rendered test\/_customer.erb/, @logger.logged(:info).last)
+ assert_equal 1, @logger.logged(:info).size
+ assert_match(/Rendered test\/_customer.erb/, @logger.logged(:info).last)
+ end
end
def test_render_collection_with_implicit_path
- @view.render([ Customer.new("david"), Customer.new("mary") ], :greeting => "hi")
- wait
+ Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do
+ @view.render([ Customer.new("david"), Customer.new("mary") ], :greeting => "hi")
+ wait
- assert_equal 1, @logger.logged(:info).size
- assert_match(/Rendered customers\/_customer\.html\.erb/, @logger.logged(:info).last)
+ assert_equal 1, @logger.logged(:info).size
+ assert_match(/Rendered customers\/_customer\.html\.erb/, @logger.logged(:info).last)
+ end
end
def test_render_collection_template_without_path
- @view.render([ GoodCustomer.new("david"), Customer.new("mary") ], :greeting => "hi")
- wait
+ Rails.stub(:root, File.expand_path(FIXTURE_LOAD_PATH)) do
+ @view.render([ GoodCustomer.new("david"), Customer.new("mary") ], :greeting => "hi")
+ wait
- assert_equal 1, @logger.logged(:info).size
- assert_match(/Rendered collection/, @logger.logged(:info).last)
+ assert_equal 1, @logger.logged(:info).size
+ assert_match(/Rendered collection/, @logger.logged(:info).last)
+ end
end
end
diff --git a/actionview/test/template/render_test.rb b/actionview/test/template/render_test.rb
index 84aca222b2..994fd44c52 100644
--- a/actionview/test/template/render_test.rb
+++ b/actionview/test/template/render_test.rb
@@ -9,6 +9,10 @@ module RenderTestCases
@assigns = { :secret => 'in the sauce' }
@view = Class.new(ActionView::Base) do
def view_cache_dependencies; end
+
+ def fragment_cache_key(key)
+ ActiveSupport::Cache.expand_cache_key(key, :views)
+ end
end.new(paths, @assigns)
@controller_view = TestController.new.view_context
diff --git a/actionview/test/template/test_test.rb b/actionview/test/template/test_test.rb
index 88bac85039..e1ff639979 100644
--- a/actionview/test/template/test_test.rb
+++ b/actionview/test/template/test_test.rb
@@ -41,12 +41,12 @@ class PeopleHelperTest < ActionView::TestCase
extend ActiveModel::Naming
def to_model; self; end
def persisted?; true; end
- def self.name; 'Mocha::Mock'; end
+ def self.name; 'Minitest::Mock'; end
}.new "David"
the_model = nil
extend Module.new {
- define_method(:mocha_mock_path) { |model, *args|
+ define_method(:minitest_mock_path) { |model, *args|
the_model = model
"/people/1"
}
diff --git a/actionview/test/template/translation_helper_test.rb b/actionview/test/template/translation_helper_test.rb
index 631bceadd8..597936d7ae 100644
--- a/actionview/test/template/translation_helper_test.rb
+++ b/actionview/test/template/translation_helper_test.rb
@@ -54,6 +54,16 @@ class TranslationHelperTest < ActiveSupport::TestCase
end
end
+ def test_returns_missing_tranlation_message_without_span_wrap
+ old_value = ActionView::Base.debug_missing_translation
+ ActionView::Base.debug_missing_translation = false
+
+ expected = 'translation missing: en.translations.missing'
+ assert_equal expected, translate(:"translations.missing")
+ ensure
+ ActionView::Base.debug_missing_translation = old_value
+ end
+
def test_returns_missing_translation_message_wrapped_into_span
expected = '<span class="translation_missing" title="translation missing: en.translations.missing">Missing</span>'
assert_equal expected, translate(:"translations.missing")
diff --git a/actionview/test/template/url_helper_test.rb b/actionview/test/template/url_helper_test.rb
index 48d0a9a47a..784a48ed8d 100644
--- a/actionview/test/template/url_helper_test.rb
+++ b/actionview/test/template/url_helper_test.rb
@@ -38,6 +38,10 @@ class UrlHelperTest < ActiveSupport::TestCase
assert_equal "/?a=b&c=d", url_for(hash_for(a: :b, c: :d))
end
+ def test_url_for_does_not_include_empty_hashes
+ assert_equal "/", url_for(hash_for(a: {}))
+ end
+
def test_url_for_with_back
referer = 'http://www.example.com/referer'
@controller = Struct.new(:request).new(Struct.new(:env).new("HTTP_REFERER" => referer))
@@ -632,10 +636,6 @@ class UrlHelperControllerTest < ActionController::TestCase
render inline: "<%= url_for controller: 'url_helper_controller_test/url_helper', action: 'show_url_for' %>"
end
- def show_overridden_url_for
- render inline: "<%= url_for params.merge(controller: 'url_helper_controller_test/url_helper', action: 'show_url_for') %>"
- end
-
def show_named_route
render inline: "<%= show_named_route_#{params[:kind]} %>"
end
@@ -669,11 +669,6 @@ class UrlHelperControllerTest < ActionController::TestCase
assert_equal '/url_helper_controller_test/url_helper/show_url_for', @response.body
end
- def test_overridden_url_for_shows_only_path
- get :show_overridden_url_for
- assert_equal '/url_helper_controller_test/url_helper/show_url_for', @response.body
- end
-
def test_named_route_url_shows_host_and_path
get :show_named_route, params: { kind: 'url' }
assert_equal 'http://test.host/url_helper_controller_test/url_helper/show_named_route',
diff --git a/activejob/CHANGELOG.md b/activejob/CHANGELOG.md
index 79235019fe..2caa073f68 100644
--- a/activejob/CHANGELOG.md
+++ b/activejob/CHANGELOG.md
@@ -1,3 +1,8 @@
+## Rails 5.0.0.beta1 (December 18, 2015) ##
+
+* No changes.
+
+
* Fixed serializing `:at` option for `assert_enqueued_with`
and `assert_performed_with`.
diff --git a/activejob/README.md b/activejob/README.md
index d9ff561695..7268186c00 100644
--- a/activejob/README.md
+++ b/activejob/README.md
@@ -102,7 +102,7 @@ see the API Documentation for [ActiveJob::QueueAdapters](http://api.rubyonrails.
The latest version of Active Job can be installed with RubyGems:
```
- % gem install activejob
+ $ gem install activejob
```
Source code can be downloaded as part of the Rails project on GitHub
diff --git a/activejob/activejob.gemspec b/activejob/activejob.gemspec
index 24e38e495f..bc1671b508 100644
--- a/activejob/activejob.gemspec
+++ b/activejob/activejob.gemspec
@@ -19,5 +19,5 @@ Gem::Specification.new do |s|
s.require_path = 'lib'
s.add_dependency 'activesupport', version
- s.add_dependency 'globalid', '>= 0.3.0'
+ s.add_dependency 'globalid', '>= 0.3.6'
end
diff --git a/activejob/lib/active_job/gem_version.rb b/activejob/lib/active_job/gem_version.rb
index 27a5de93f4..35356405b5 100644
--- a/activejob/lib/active_job/gem_version.rb
+++ b/activejob/lib/active_job/gem_version.rb
@@ -8,7 +8,7 @@ module ActiveJob
MAJOR = 5
MINOR = 0
TINY = 0
- PRE = "alpha"
+ PRE = "beta1"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/activejob/test/integration/queuing_test.rb b/activejob/test/integration/queuing_test.rb
index e435ed4aa6..d8425c9706 100644
--- a/activejob/test/integration/queuing_test.rb
+++ b/activejob/test/integration/queuing_test.rb
@@ -78,7 +78,7 @@ class QueuingTest < ActiveSupport::TestCase
TestJob.perform_later @id
wait_for_jobs_to_finish_for(5.seconds)
assert job_executed
- assert_equal 'de', job_output
+ assert_equal 'de', job_executed_in_locale
ensure
I18n.available_locales = [:en]
I18n.locale = :en
diff --git a/activejob/test/support/integration/dummy_app_template.rb b/activejob/test/support/integration/dummy_app_template.rb
index 0c062a025e..262ca72327 100644
--- a/activejob/test/support/integration/dummy_app_template.rb
+++ b/activejob/test/support/integration/dummy_app_template.rb
@@ -18,8 +18,11 @@ class TestJob < ActiveJob::Base
queue_as :integration_tests
def perform(x)
- File.open(Rails.root.join("tmp/\#{x}"), "w+") do |f|
- f.write I18n.locale
+ File.open(Rails.root.join("tmp/\#{x}"), "wb+") do |f|
+ f.write Marshal.dump({
+ "locale" => I18n.locale.to_s || "en",
+ "executed_at" => Time.now.to_r
+ })
end
end
end
diff --git a/activejob/test/support/integration/test_case_helpers.rb b/activejob/test/support/integration/test_case_helpers.rb
index 8319d09520..9897f76fd0 100644
--- a/activejob/test/support/integration/test_case_helpers.rb
+++ b/activejob/test/support/integration/test_case_helpers.rb
@@ -42,15 +42,23 @@ module TestCaseHelpers
end
end
+ def job_file(id)
+ Dummy::Application.root.join("tmp/#{id}")
+ end
+
def job_executed(id=@id)
- Dummy::Application.root.join("tmp/#{id}").exist?
+ job_file(id).exist?
+ end
+
+ def job_data(id)
+ Marshal.load(File.binread(job_file(id)))
end
def job_executed_at(id=@id)
- File.new(Dummy::Application.root.join("tmp/#{id}")).ctime
+ job_data(id)["executed_at"]
end
- def job_output
- File.read Dummy::Application.root.join("tmp/#{@id}")
+ def job_executed_in_locale(id=@id)
+ job_data(id)["locale"]
end
end
diff --git a/activemodel/CHANGELOG.md b/activemodel/CHANGELOG.md
index a3368cd197..3d722488e2 100644
--- a/activemodel/CHANGELOG.md
+++ b/activemodel/CHANGELOG.md
@@ -1,3 +1,8 @@
+## Rails 5.0.0.beta1 (December 18, 2015) ##
+
+* No changes.
+
+
* Validate multiple contexts on `valid?` and `invalid?` at once.
Example:
diff --git a/activemodel/README.rdoc b/activemodel/README.rdoc
index 20414c1d61..77f5761993 100644
--- a/activemodel/README.rdoc
+++ b/activemodel/README.rdoc
@@ -235,7 +235,7 @@ behavior out of the box:
The latest version of Active Model can be installed with RubyGems:
- % gem install activemodel
+ $ gem install activemodel
Source code can be downloaded as part of the Rails project on GitHub
@@ -262,4 +262,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/activemodel/lib/active_model/attribute_assignment.rb b/activemodel/lib/active_model/attribute_assignment.rb
index 087d11f708..62014cd1cd 100644
--- a/activemodel/lib/active_model/attribute_assignment.rb
+++ b/activemodel/lib/active_model/attribute_assignment.rb
@@ -27,7 +27,7 @@ module ActiveModel
if !new_attributes.respond_to?(:stringify_keys)
raise ArgumentError, "When assigning attributes, you must pass a hash as an argument."
end
- return if new_attributes.blank?
+ return if new_attributes.nil? || new_attributes.empty?
attributes = new_attributes.stringify_keys
_assign_attributes(sanitize_for_mass_assignment(attributes))
diff --git a/activemodel/lib/active_model/dirty.rb b/activemodel/lib/active_model/dirty.rb
index 0ab8df42f5..6e2e5afd1b 100644
--- a/activemodel/lib/active_model/dirty.rb
+++ b/activemodel/lib/active_model/dirty.rb
@@ -26,6 +26,10 @@ module ActiveModel
#
# define_attribute_methods :name
#
+ # def initialize(name)
+ # @name = name
+ # end
+ #
# def name
# @name
# end
@@ -54,7 +58,7 @@ module ActiveModel
#
# A newly instantiated +Person+ object is unchanged:
#
- # person = Person.new
+ # person = Person.new("Uncle Bob")
# person.changed? # => false
#
# Change the name:
diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb
index 4726a68f69..ef6141a51d 100644
--- a/activemodel/lib/active_model/errors.rb
+++ b/activemodel/lib/active_model/errors.rb
@@ -81,6 +81,18 @@ module ActiveModel
super
end
+ # Copies the errors from <tt>other</tt>.
+ #
+ # other - The ActiveModel::Errors instance.
+ #
+ # Examples
+ #
+ # person.errors.copy!(other)
+ def copy!(other) # :nodoc:
+ @messages = other.messages.dup
+ @details = other.details.dup
+ end
+
# Clear the error messages.
#
# person.errors.full_messages # => ["name cannot be nil"]
diff --git a/activemodel/lib/active_model/gem_version.rb b/activemodel/lib/active_model/gem_version.rb
index 762f4fe939..d74a3912d6 100644
--- a/activemodel/lib/active_model/gem_version.rb
+++ b/activemodel/lib/active_model/gem_version.rb
@@ -8,7 +8,7 @@ module ActiveModel
MAJOR = 5
MINOR = 0
TINY = 0
- PRE = "alpha"
+ PRE = "beta1"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/activemodel/lib/active_model/type/time.rb b/activemodel/lib/active_model/type/time.rb
index 7101bad566..fe09f63a87 100644
--- a/activemodel/lib/active_model/type/time.rb
+++ b/activemodel/lib/active_model/type/time.rb
@@ -29,7 +29,11 @@ module ActiveModel
return value unless value.is_a?(::String)
return if value.empty?
- dummy_time_value = "2000-01-01 #{value}"
+ if value =~ /^2000-01-01/
+ dummy_time_value = value
+ else
+ dummy_time_value = "2000-01-01 #{value}"
+ end
fast_string_to_time(dummy_time_value) || begin
time_hash = ::Date._parse(dummy_time_value)
diff --git a/activemodel/lib/active_model/type/value.rb b/activemodel/lib/active_model/type/value.rb
index 5fea0561a6..9d1f267b41 100644
--- a/activemodel/lib/active_model/type/value.rb
+++ b/activemodel/lib/active_model/type/value.rb
@@ -90,6 +90,11 @@ module ActiveModel
scale == other.scale &&
limit == other.limit
end
+ alias eql? ==
+
+ def hash
+ [self.class, precision, scale, limit].hash
+ end
def assert_valid_value(*)
end
diff --git a/activemodel/test/cases/attribute_assignment_test.rb b/activemodel/test/cases/attribute_assignment_test.rb
index 3336691841..287bea719c 100644
--- a/activemodel/test/cases/attribute_assignment_test.rb
+++ b/activemodel/test/cases/attribute_assignment_test.rb
@@ -1,4 +1,5 @@
require "cases/helper"
+require "active_support/core_ext/hash/indifferent_access"
require "active_support/hash_with_indifferent_access"
class AttributeAssignmentTest < ActiveModel::TestCase
@@ -23,13 +24,32 @@ class AttributeAssignmentTest < ActiveModel::TestCase
class ErrorFromAttributeWriter < StandardError
end
- class ProtectedParams < ActiveSupport::HashWithIndifferentAccess
+ class ProtectedParams
+ attr_accessor :permitted
+ alias :permitted? :permitted
+
+ delegate :keys, :key?, :has_key?, :empty?, to: :@parameters
+
+ def initialize(attributes)
+ @parameters = attributes.with_indifferent_access
+ @permitted = false
+ end
+
def permit!
@permitted = true
+ self
+ end
+
+ def [](key)
+ @parameters[key]
+ end
+
+ def to_h
+ @parameters
end
- def permitted?
- @permitted ||= false
+ def stringify_keys
+ dup
end
def dup
diff --git a/activemodel/test/cases/callbacks_test.rb b/activemodel/test/cases/callbacks_test.rb
index 85455c112c..e4ecc0adb4 100644
--- a/activemodel/test/cases/callbacks_test.rb
+++ b/activemodel/test/cases/callbacks_test.rb
@@ -28,7 +28,7 @@ class CallbacksTest < ActiveModel::TestCase
false
end
- after_create "@callbacks << :final_callback"
+ ActiveSupport::Deprecation.silence { after_create "@callbacks << :final_callback" }
def initialize(options = {})
@callbacks = []
diff --git a/activemodel/test/cases/errors_test.rb b/activemodel/test/cases/errors_test.rb
index f6d171bec6..a5ac055033 100644
--- a/activemodel/test/cases/errors_test.rb
+++ b/activemodel/test/cases/errors_test.rb
@@ -410,4 +410,14 @@ class ErrorsTest < ActiveModel::TestCase
person.errors.clear
assert person.errors.details.empty?
end
+
+ test "copy errors" do
+ errors = ActiveModel::Errors.new(Person.new)
+ errors.add(:name, :invalid)
+ person = Person.new
+ person.errors.copy!(errors)
+
+ assert_equal [:name], person.errors.messages.keys
+ assert_equal [:name], person.errors.details.keys
+ end
end
diff --git a/activemodel/test/cases/forbidden_attributes_protection_test.rb b/activemodel/test/cases/forbidden_attributes_protection_test.rb
index 3cb204a2c5..d8d757f52a 100644
--- a/activemodel/test/cases/forbidden_attributes_protection_test.rb
+++ b/activemodel/test/cases/forbidden_attributes_protection_test.rb
@@ -2,12 +2,14 @@ require 'cases/helper'
require 'active_support/core_ext/hash/indifferent_access'
require 'models/account'
-class ProtectedParams < ActiveSupport::HashWithIndifferentAccess
+class ProtectedParams
attr_accessor :permitted
alias :permitted? :permitted
+ delegate :keys, :key?, :has_key?, :empty?, to: :@parameters
+
def initialize(attributes)
- super(attributes)
+ @parameters = attributes
@permitted = false
end
@@ -15,6 +17,10 @@ class ProtectedParams < ActiveSupport::HashWithIndifferentAccess
@permitted = true
self
end
+
+ def to_h
+ @parameters
+ end
end
class ActiveModelMassUpdateProtectionTest < ActiveSupport::TestCase
diff --git a/activemodel/test/cases/translation_test.rb b/activemodel/test/cases/translation_test.rb
index cedc812ec7..2c89388f14 100644
--- a/activemodel/test/cases/translation_test.rb
+++ b/activemodel/test/cases/translation_test.rb
@@ -88,6 +88,11 @@ class ActiveModelI18nTests < ActiveModel::TestCase
assert_equal 'child model', Child.model_name.human
end
+ def test_translated_model_with_namespace
+ I18n.backend.store_translations 'en', activemodel: { models: { 'person/gender': 'gender model' } }
+ assert_equal 'gender model', Person::Gender.model_name.human
+ end
+
def test_translated_model_names_with_ancestors_fallback
I18n.backend.store_translations 'en', activemodel: { models: { person: 'person model' } }
assert_equal 'person model', Child.model_name.human
diff --git a/activemodel/test/cases/validations/with_validation_test.rb b/activemodel/test/cases/validations/with_validation_test.rb
index 03c7943308..c73580138d 100644
--- a/activemodel/test/cases/validations/with_validation_test.rb
+++ b/activemodel/test/cases/validations/with_validation_test.rb
@@ -101,6 +101,7 @@ class ValidatesWithTest < ActiveModel::TestCase
validator.expect(:new, validator, [{foo: :bar, if: "1 == 1", class: Topic}])
validator.expect(:validate, nil, [topic])
validator.expect(:is_a?, false, [Symbol])
+ validator.expect(:is_a?, false, [String])
Topic.validates_with(validator, if: "1 == 1", foo: :bar)
assert topic.valid?
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md
index 98c6384402..9819b85205 100644
--- a/activerecord/CHANGELOG.md
+++ b/activerecord/CHANGELOG.md
@@ -1,3 +1,109 @@
+## Rails 5.0.0.beta1 (December 18, 2015) ##
+
+* No changes.
+
+
+* Order the result of `find(ids)` to match the passed array, if the relation
+ has no explicit order defined.
+
+ Fixes #20338.
+
+ *Miguel Grazziotin*, *Matthew Draper*
+
+* Omit default limit values in dumped schema. It's tidier, and if the defaults
+ change in the future, we can address that via Migration API Versioning.
+
+ *Jean Boussier*
+
+* Support passing the schema name as a prefix to table name in
+ `ConnectionAdapters::SchemaStatements#indexes`. Previously the prefix would
+ be considered a full part of the index name, and only the schema in the
+ current search path would be considered.
+
+ *Grey Baker*
+
+* Ignore index name in `index_exists?` and `remove_index` when not passed a
+ name to check for.
+
+ *Grey Baker*
+
+* Extract support for the legacy `mysql` database adapter from core. It will
+ live on in a separate gem for now, but most users should just use `mysql2`.
+
+ *Abdelkader Boudih*
+
+* ApplicationRecord is a new superclass for all app models, analogous to app
+ controllers subclassing ApplicationController instead of
+ ActionController::Base. This gives apps a single spot to configure app-wide
+ model behavior.
+
+ Newly generated applications have `app/models/application_record.rb`
+ present by default.
+
+ *Genadi Samokovarov*
+
+* Version the API presented to migration classes, so we can change parameter
+ defaults without breaking existing migrations, or forcing them to be
+ rewritten through a deprecation cycle.
+
+ *Matthew Draper*, *Ravil Bayramgalin*
+
+* Use bind params for `limit` and `offset`. This will generate significantly
+ fewer prepared statements for common tasks like pagination. To support this
+ change, passing a string containing a comma to `limit` has been deprecated,
+ and passing an Arel node to `limit` is no longer supported.
+
+ Fixes #22250
+
+ *Sean Griffin*
+
+* Introduce after_{create,update,delete}_commit callbacks.
+
+ Before:
+
+ after_commit :add_to_index_later, on: :create
+ after_commit :update_in_index_later, on: :update
+ after_commit :remove_from_index_later, on: :destroy
+
+ After:
+
+ after_create_commit :add_to_index_later
+ after_update_commit :update_in_index_later
+ after_destroy_commit :remove_from_index_later
+
+ Fixes #22515.
+
+ *Genadi Samokovarov*
+
+* Respect the column default values for `inheritance_column` when
+ instantiating records through the base class.
+
+ Fixes #17121.
+
+ Example:
+
+ # The schema of BaseModel has `t.string :type, default: 'SubType'`
+ subtype = BaseModel.new
+ assert_equals SubType, subtype.class
+
+ *Kuldeep Aggarwal*
+
+* Fix `rake db:structure:dump` on Postgres when multiple schemas are used.
+
+ Fixes #22346.
+
+ *Nick Muerdter*, *ckoenig*
+
+* Add schema dumping support for PostgreSQL geometric data types.
+
+ *Ryuta Kamizono*
+
+* Except keys of `build_record`'s argument from `create_scope` in `initialize_attributes`.
+
+ Fixes #21893.
+
+ *Yuichiro Kaneko*
+
* Deprecate `connection.tables` on the SQLite3 and MySQL adapters.
Also deprecate passing arguments to `#tables`.
And deprecate `table_exists?`.
@@ -201,9 +307,9 @@
Example:
- config.generators do |g|
- g.orm :active_record, primary_key_type: :uuid
- end
+ config.generators do |g|
+ g.orm :active_record, primary_key_type: :uuid
+ end
*Jon McCartie*
@@ -242,7 +348,7 @@
*Sean Griffin*
-* Give `AcriveRecord::Relation#update` its own deprecation warning when
+* Give `ActiveRecord::Relation#update` its own deprecation warning when
passed an `ActiveRecord::Base` instance.
Fixes #21945.
@@ -279,10 +385,10 @@
To load the fixtures file `accounts.yml` as the `User` model, use:
- _fixture:
- model_class: User
- david:
- name: David
+ _fixture:
+ model_class: User
+ david:
+ name: David
Fixes #9516.
@@ -403,6 +509,13 @@
*Wojciech Wnętrzak*
+* Instantiating an AR model with `ActionController::Parameters` now raises
+ an `ActiveModel::ForbiddenAttributesError` if the parameters include a
+ `type` field that has not been explicitly permitted. Previously, the
+ `type` field was simply ignored in the same situation.
+
+ *Prem Sichanugrist*
+
* PostgreSQL, `create_schema`, `drop_schema` and `rename_table` now quote
schema names.
diff --git a/activerecord/README.rdoc b/activerecord/README.rdoc
index 3eac8cc422..20ce1e8dd2 100644
--- a/activerecord/README.rdoc
+++ b/activerecord/README.rdoc
@@ -138,7 +138,7 @@ This would also define the following accessors: <tt>Product#name</tt> and
* Database agnostic schema management with Migrations.
- class AddSystemSettings < ActiveRecord::Migration
+ class AddSystemSettings < ActiveRecord::Migration[5.0]
def up
create_table :system_settings do |t|
t.string :name
@@ -188,7 +188,7 @@ Admit the Database:
The latest version of Active Record can be installed with RubyGems:
- % gem install activerecord
+ $ gem install activerecord
Source code can be downloaded as part of the Rails project on GitHub:
@@ -215,4 +215,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/activerecord/RUNNING_UNIT_TESTS.rdoc b/activerecord/RUNNING_UNIT_TESTS.rdoc
index bae40604b1..a74fcf2df7 100644
--- a/activerecord/RUNNING_UNIT_TESTS.rdoc
+++ b/activerecord/RUNNING_UNIT_TESTS.rdoc
@@ -20,7 +20,6 @@ example:
Simply executing <tt>bundle exec rake test</tt> is equivalent to the following:
- $ bundle exec rake test:mysql
$ bundle exec rake test:mysql2
$ bundle exec rake test:postgresql
$ bundle exec rake test:sqlite3
diff --git a/activerecord/Rakefile b/activerecord/Rakefile
index c93099a921..0564dca94a 100644
--- a/activerecord/Rakefile
+++ b/activerecord/Rakefile
@@ -17,14 +17,14 @@ def run_without_aborting(*tasks)
abort "Errors running #{errors.join(', ')}" if errors.any?
end
-desc 'Run mysql, mysql2, sqlite, and postgresql tests by default'
+desc 'Run mysql2, sqlite, and postgresql tests by default'
task :default => :test
-desc 'Run mysql, mysql2, sqlite, and postgresql tests'
+desc 'Run mysql2, sqlite, and postgresql tests'
task :test do
tasks = defined?(JRUBY_VERSION) ?
%w(test_jdbcmysql test_jdbcsqlite3 test_jdbcpostgresql) :
- %w(test_mysql test_mysql2 test_sqlite3 test_postgresql)
+ %w(test_mysql2 test_sqlite3 test_postgresql)
run_without_aborting(*tasks)
end
@@ -32,7 +32,7 @@ namespace :test do
task :isolated do
tasks = defined?(JRUBY_VERSION) ?
%w(isolated_test_jdbcmysql isolated_test_jdbcsqlite3 isolated_test_jdbcpostgresql) :
- %w(isolated_test_mysql isolated_test_mysql2 isolated_test_sqlite3 isolated_test_postgresql)
+ %w(isolated_test_mysql2 isolated_test_sqlite3 isolated_test_postgresql)
run_without_aborting(*tasks)
end
end
@@ -43,7 +43,7 @@ namespace :db do
task :drop => ['db:mysql:drop', 'db:postgresql:drop']
end
-%w( mysql mysql2 postgresql sqlite3 sqlite3_mem db2 oracle jdbcmysql jdbcpostgresql jdbcsqlite3 jdbcderby jdbch2 jdbchsqldb ).each do |adapter|
+%w( mysql2 postgresql sqlite3 sqlite3_mem db2 oracle jdbcmysql jdbcpostgresql jdbcsqlite3 jdbcderby jdbch2 jdbchsqldb ).each do |adapter|
namespace :test do
Rake::TestTask.new(adapter => "#{adapter}:env") { |t|
adapter_short = adapter == 'db2' ? adapter : adapter[/^[a-z0-9]+/]
@@ -87,14 +87,14 @@ namespace :db do
namespace :mysql do
desc 'Build the MySQL test databases'
task :build do
- config = ARTest.config['connections']['mysql']
+ config = ARTest.config['connections']['mysql2']
%x( mysql --user=#{config['arunit']['username']} --password=#{config['arunit']['password']} -e "create DATABASE #{config['arunit']['database']} DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_unicode_ci ")
%x( mysql --user=#{config['arunit2']['username']} --password=#{config['arunit2']['password']} -e "create DATABASE #{config['arunit2']['database']} DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_unicode_ci ")
end
desc 'Drop the MySQL test databases'
task :drop do
- config = ARTest.config['connections']['mysql']
+ config = ARTest.config['connections']['mysql2']
%x( mysqladmin --user=#{config['arunit']['username']} --password=#{config['arunit']['password']} -f drop #{config['arunit']['database']} )
%x( mysqladmin --user=#{config['arunit2']['username']} --password=#{config['arunit2']['password']} -f drop #{config['arunit2']['database']} )
end
diff --git a/activerecord/activerecord.gemspec b/activerecord/activerecord.gemspec
index bd95b57303..4405da2812 100644
--- a/activerecord/activerecord.gemspec
+++ b/activerecord/activerecord.gemspec
@@ -24,5 +24,5 @@ Gem::Specification.new do |s|
s.add_dependency 'activesupport', version
s.add_dependency 'activemodel', version
- s.add_dependency 'arel', '7.0.0.alpha'
+ s.add_dependency 'arel', '~> 7.0'
end
diff --git a/activerecord/bin/test b/activerecord/bin/test
index f8adf2aabc..7417b068bf 100755
--- a/activerecord/bin/test
+++ b/activerecord/bin/test
@@ -6,7 +6,7 @@ module Minitest
opts.separator ""
opts.separator "Active Record options:"
opts.on("-a", "--adapter [ADAPTER]",
- "Run tests using a specific adapter (sqlite3, sqlite3_mem, mysql, mysql2, postgresql)") do |adapter|
+ "Run tests using a specific adapter (sqlite3, sqlite3_mem, mysql2, postgresql)") do |adapter|
ENV["ARCONN"] = adapter.strip
end
diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb
index b806a2f832..462b3066ab 100644
--- a/activerecord/lib/active_record/associations.rb
+++ b/activerecord/lib/active_record/associations.rb
@@ -1181,7 +1181,8 @@ module ActiveRecord
# [collection=objects]
# Replaces the collections content by deleting and adding objects as appropriate. If the <tt>:through</tt>
# option is true callbacks in the join models are triggered except destroy callbacks, since deletion is
- # direct.
+ # direct by default. You can specify <tt>dependent: :destroy</tt> or
+ # <tt>dependent: :nullify</tt> to override this.
# [collection_singular_ids]
# Returns an array of the associated objects' ids
# [collection_singular_ids=ids]
@@ -1639,7 +1640,7 @@ module ActiveRecord
# The join table should not have a primary key or a model associated with it. You must manually generate the
# join table with a migration such as this:
#
- # class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration
+ # class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration[5.0]
# def change
# create_join_table :developers, :projects
# end
diff --git a/activerecord/lib/active_record/associations/association.rb b/activerecord/lib/active_record/associations/association.rb
index c7b396f3d4..d64ab64c99 100644
--- a/activerecord/lib/active_record/associations/association.rb
+++ b/activerecord/lib/active_record/associations/association.rb
@@ -163,9 +163,12 @@ module ActiveRecord
@reflection = @owner.class._reflect_on_association(reflection_name)
end
- def initialize_attributes(record) #:nodoc:
+ def initialize_attributes(record, except_from_scope_attributes = nil) #:nodoc:
+ except_from_scope_attributes ||= {}
skip_assign = [reflection.foreign_key, reflection.type].compact
- attributes = create_scope.except(*(record.changed - skip_assign))
+ assigned_keys = record.changed
+ assigned_keys += except_from_scope_attributes.keys.map(&:to_s)
+ attributes = create_scope.except(*(assigned_keys - skip_assign))
record.assign_attributes(attributes)
set_inverse_instance(record)
end
@@ -248,7 +251,7 @@ module ActiveRecord
def build_record(attributes)
reflection.build_association(attributes) do |record|
- initialize_attributes(record)
+ initialize_attributes(record, attributes)
end
end
diff --git a/activerecord/lib/active_record/associations/builder/belongs_to.rb b/activerecord/lib/active_record/associations/builder/belongs_to.rb
index 81c535d962..f02d146e89 100644
--- a/activerecord/lib/active_record/associations/builder/belongs_to.rb
+++ b/activerecord/lib/active_record/associations/builder/belongs_to.rb
@@ -106,8 +106,7 @@ module ActiveRecord::Associations::Builder # :nodoc:
touch = reflection.options[:touch]
callback = lambda { |record|
- touch_method = touching_delayed_records? ? :touch : :touch_later
- BelongsTo.touch_record(record, foreign_key, n, touch, touch_method)
+ BelongsTo.touch_record(record, foreign_key, n, touch, belongs_to_touch_method)
}
model.after_save callback, if: :changed?
diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb
index f32dddb8f0..473b80a658 100644
--- a/activerecord/lib/active_record/associations/collection_association.rb
+++ b/activerecord/lib/active_record/associations/collection_association.rb
@@ -414,12 +414,16 @@ module ActiveRecord
def replace_on_target(record, index, skip_callbacks)
callback(:before_add, record) unless skip_callbacks
+
+ was_loaded = loaded?
yield(record) if block_given?
- if index
- @target[index] = record
- else
- @target << record
+ unless !was_loaded && loaded?
+ if index
+ @target[index] = record
+ else
+ @target << record
+ end
end
callback(:after_add, record) unless skip_callbacks
diff --git a/activerecord/lib/active_record/associations/preloader/through_association.rb b/activerecord/lib/active_record/associations/preloader/through_association.rb
index 24aa47bb51..6c83058202 100644
--- a/activerecord/lib/active_record/associations/preloader/through_association.rb
+++ b/activerecord/lib/active_record/associations/preloader/through_association.rb
@@ -18,7 +18,8 @@ module ActiveRecord
through_records = owners.map do |owner|
association = owner.association through_reflection.name
- [owner, Array(association.reader)]
+ center = target_records_from_association(association)
+ [owner, Array(center)]
end
reset_association owners, through_reflection.name
@@ -49,7 +50,7 @@ module ActiveRecord
rhs_records = middles.flat_map { |r|
association = r.association source_reflection.name
- association.reader
+ target_records_from_association(association)
}.compact
rhs_records.sort_by { |rhs| record_offset[rhs] }
@@ -91,6 +92,10 @@ module ActiveRecord
scope
end
+
+ def target_records_from_association(association)
+ association.loaded? ? association.target : association.reader
+ end
end
end
end
diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb
index 4ae585d3f5..423a93964e 100644
--- a/activerecord/lib/active_record/attribute_methods.rb
+++ b/activerecord/lib/active_record/attribute_methods.rb
@@ -191,6 +191,18 @@ module ActiveRecord
end
end
+ # Returns true if the given attribute exists, otherwise false.
+ #
+ # class Person < ActiveRecord::Base
+ # end
+ #
+ # Person.has_attribute?('name') # => true
+ # Person.has_attribute?(:age) # => true
+ # Person.has_attribute?(:nothing) # => false
+ def has_attribute?(attr_name)
+ attribute_types.key?(attr_name.to_s)
+ end
+
# Returns the column object for the named attribute.
# Returns a +ActiveRecord::ConnectionAdapters::NullColumn+ if the
# named attribute does not exist.
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 9e693b6aee..45d2c855a5 100644
--- a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
+++ b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
@@ -1,3 +1,5 @@
+require 'active_support/core_ext/string/strip'
+
module ActiveRecord
module AttributeMethods
module TimeZoneConversion
@@ -77,7 +79,7 @@ module ActiveRecord
!result &&
cast_type.type == :time &&
time_zone_aware_types.include?(:not_explicitly_configured)
- ActiveSupport::Deprecation.warn(<<-MESSAGE)
+ ActiveSupport::Deprecation.warn(<<-MESSAGE.strip_heredoc)
Time columns will become time zone aware in Rails 5.1. This
still causes `String`s to be parsed as if they were in `Time.zone`,
and `Time`s to be converted to `Time.zone`.
diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb
index 9782e58299..4a31a1aa84 100644
--- a/activerecord/lib/active_record/base.rb
+++ b/activerecord/lib/active_record/base.rb
@@ -261,7 +261,7 @@ module ActiveRecord #:nodoc:
# The +errors+ property of this exception contains an array of
# AttributeAssignmentError
# objects that should be inspected to determine which attributes triggered the errors.
- # * RecordInvalid - raised by {ActiveRecord::Base#save}[rdoc-ref:Persistence#save] and
+ # * RecordInvalid - raised by {ActiveRecord::Base#save!}[rdoc-ref:Persistence#save!] and
# {ActiveRecord::Base.create!}[rdoc-ref:Persistence::ClassMethods#create!]
# when the record is invalid.
# * RecordNotFound - No record responded to the {ActiveRecord::Base.find}[rdoc-ref:FinderMethods#find] method.
diff --git a/activerecord/lib/active_record/callbacks.rb b/activerecord/lib/active_record/callbacks.rb
index cfd8cbda67..854f9776a3 100644
--- a/activerecord/lib/active_record/callbacks.rb
+++ b/activerecord/lib/active_record/callbacks.rb
@@ -175,21 +175,6 @@ module ActiveRecord
# end
# end
#
- # The callback macros usually accept a symbol for the method they're supposed to run, but you can also
- # pass a "method string", which will then be evaluated within the binding of the callback. Example:
- #
- # class Topic < ActiveRecord::Base
- # before_destroy 'self.class.delete_all "parent_id = #{id}"'
- # end
- #
- # Notice that single quotes (') are used so the <tt>#{id}</tt> part isn't evaluated until the callback
- # is triggered. Also note that these inline callbacks can be stacked just like the regular ones:
- #
- # class Topic < ActiveRecord::Base
- # before_destroy 'self.class.delete_all "parent_id = #{id}"',
- # 'puts "Evaluated after parents are destroyed"'
- # end
- #
# == <tt>before_validation*</tt> returning statements
#
# If the +before_validation+ callback throws +:abort+, the process will be
@@ -208,12 +193,12 @@ module ActiveRecord
#
# Sometimes the code needs that the callbacks execute in a specific order. For example, a +before_destroy+
# callback (+log_children+ in this case) should be executed before the children get destroyed by the
- # <tt>dependent: destroy</tt> option.
+ # <tt>dependent: :destroy</tt> option.
#
# Let's look at the code below:
#
# class Topic < ActiveRecord::Base
- # has_many :children, dependent: destroy
+ # has_many :children, dependent: :destroy
#
# before_destroy :log_children
#
@@ -228,7 +213,7 @@ module ActiveRecord
# You can use the +prepend+ option on the +before_destroy+ callback to avoid this.
#
# class Topic < ActiveRecord::Base
- # has_many :children, dependent: destroy
+ # has_many :children, dependent: :destroy
#
# before_destroy :log_children, prepend: true
#
@@ -238,7 +223,7 @@ module ActiveRecord
# end
# end
#
- # This way, the +before_destroy+ gets executed before the <tt>dependent: destroy</tt> is called, and the data is still available.
+ # This way, the +before_destroy+ gets executed before the <tt>dependent: :destroy</tt> is called, and the data is still available.
#
# == \Transactions
#
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 486b7b6d25..ccd2899489 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
@@ -197,7 +197,7 @@ module ActiveRecord
elapsed = Time.now - t0
if elapsed >= timeout
- msg = 'could not obtain a database connection within %0.3f seconds (waited %0.3f seconds)' %
+ msg = 'could not obtain a connection from the pool within %0.3f seconds (waited %0.3f seconds); all pooled connections were in use' %
[timeout, elapsed]
raise ConnectionTimeoutError, msg
end
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 abf0124562..1cda23dc1d 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
@@ -190,7 +190,7 @@ module ActiveRecord
# Inside migration files, the +t+ object in {create_table}[rdoc-ref:SchemaStatements#create_table]
# is actually of this type:
#
- # class SomeMigration < ActiveRecord::Migration
+ # class SomeMigration < ActiveRecord::Migration[5.0]
# def up
# create_table :foo do |t|
# puts t.class # => "ActiveRecord::ConnectionAdapters::TableDefinition"
@@ -206,14 +206,13 @@ module ActiveRecord
include ColumnMethods
attr_accessor :indexes
- attr_reader :name, :temporary, :options, :as, :foreign_keys, :native
+ attr_reader :name, :temporary, :options, :as, :foreign_keys
- def initialize(types, name, temporary, options, as = nil)
+ def initialize(name, temporary, options, as = nil)
@columns_hash = {}
@indexes = {}
@foreign_keys = {}
@primary_keys = nil
- @native = types
@temporary = temporary
@options = options
@as = as
@@ -362,11 +361,8 @@ module ActiveRecord
def new_column_definition(name, type, options) # :nodoc:
type = aliased_types(type.to_s, type)
column = create_column_definition name, type
- limit = options.fetch(:limit) do
- native[type][:limit] if native[type].is_a?(Hash)
- end
- column.limit = limit
+ column.limit = options[:limit]
column.precision = options[:precision]
column.scale = options[:scale]
column.default = options[:default]
@@ -627,11 +623,6 @@ module ActiveRecord
def foreign_key_exists?(*args) # :nodoc:
@base.foreign_key_exists?(name, *args)
end
-
- private
- def native
- @base.native_database_types
- end
end
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb
index e252ddb4cf..797662d07c 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb
@@ -61,8 +61,8 @@ module ActiveRecord
end
def schema_limit(column)
- limit = column.limit || native_database_types[column.type][:limit]
- limit.inspect if limit
+ limit = column.limit
+ limit.inspect if limit && limit != native_database_types[column.type][:limit]
end
def schema_precision(column)
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 5cacf6eddc..7bf548fcba 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
@@ -82,11 +82,10 @@ module ActiveRecord
#
def index_exists?(table_name, column_name, options = {})
column_names = Array(column_name).map(&:to_s)
- index_name = options.key?(:name) ? options[:name].to_s : index_name(table_name, column: column_names)
checks = []
- checks << lambda { |i| i.name == index_name }
checks << lambda { |i| i.columns == column_names }
checks << lambda { |i| i.unique } if options[:unique]
+ checks << lambda { |i| i.name == options[:name].to_s } if options[:name]
indexes(table_name).any? { |i| checks.all? { |check| check[i] } }
end
@@ -700,15 +699,15 @@ module ActiveRecord
# Removes the given index from the table.
#
- # Removes the +index_accounts_on_column+ in the +accounts+ table.
+ # Removes the index on +branch_id+ in the +accounts+ table if exactly one such index exists.
#
# remove_index :accounts, :branch_id
#
- # Removes the index named +index_accounts_on_branch_id+ in the +accounts+ table.
+ # Removes the index on +branch_id+ in the +accounts+ table if exactly one such index exists.
#
# remove_index :accounts, column: :branch_id
#
- # Removes the index named +index_accounts_on_branch_id_and_party_id+ in the +accounts+ table.
+ # Removes the index on +branch_id+ and +party_id+ in the +accounts+ table if exactly one such index exists.
#
# remove_index :accounts, column: [:branch_id, :party_id]
#
@@ -1127,21 +1126,35 @@ module ActiveRecord
end
def index_name_for_remove(table_name, options = {})
- index_name = index_name(table_name, options)
+ # if the adapter doesn't support the indexes call the best we can do
+ # is return the default index name for the options provided
+ return index_name(table_name, options) unless respond_to?(:indexes)
- unless index_name_exists?(table_name, index_name, true)
- if options.is_a?(Hash) && options.has_key?(:name)
- options_without_column = options.dup
- options_without_column.delete :column
- index_name_without_column = index_name(table_name, options_without_column)
+ checks = []
- return index_name_without_column if index_name_exists?(table_name, index_name_without_column, false)
- end
+ if options.is_a?(Hash)
+ checks << lambda { |i| i.name == options[:name].to_s } if options.has_key?(:name)
+ column_names = Array(options[:column]).map(&:to_s)
+ else
+ column_names = Array(options).map(&:to_s)
+ end
- raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' does not exist"
+ if column_names.any?
+ checks << lambda { |i| i.columns.join('_and_') == column_names.join('_and_') }
end
- index_name
+ raise ArgumentError "No name or columns specified" if checks.none?
+
+ matching_indexes = indexes(table_name).select { |i| checks.all? { |check| check[i] } }
+
+ if matching_indexes.count > 1
+ raise ArgumentError, "Multiple indexes found on #{table_name} columns #{column_names}. " \
+ "Specify an index name from #{matching_indexes.map(&:name).join(', ')}"
+ elsif matching_indexes.none?
+ raise ArgumentError, "No indexes found on #{table_name} with the options provided."
+ else
+ matching_indexes.first.name
+ end
end
def rename_table_indexes(table_name, new_name)
@@ -1168,7 +1181,7 @@ module ActiveRecord
private
def create_table_definition(name, temporary = false, options = nil, as = nil)
- TableDefinition.new native_database_types, name, temporary, options, as
+ TableDefinition.new(name, temporary, options, as)
end
def create_alter_table(name)
diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
index 55910865e5..4b6912c616 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
@@ -95,14 +95,15 @@ module ActiveRecord
attr_reader :prepared_statements
- def initialize(connection, logger = nil, pool = nil) #:nodoc:
+ def initialize(connection, logger = nil, config = {}) # :nodoc:
super()
@connection = connection
@owner = nil
@instrumenter = ActiveSupport::Notifications.instrumenter
@logger = logger
- @pool = pool
+ @config = config
+ @pool = nil
@schema_cache = SchemaCache.new self
@visitor = nil
@prepared_statements = false
@@ -289,14 +290,14 @@ module ActiveRecord
# locks
#
# Return true if we got the lock, otherwise false
- def get_advisory_lock(key) # :nodoc:
+ def get_advisory_lock(lock_id) # :nodoc:
end
# This is meant to be implemented by the adapters that support advisory
# locks.
#
# Return true if we released the lock, otherwise false
- def release_advisory_lock(key) # :nodoc:
+ def release_advisory_lock(lock_id) # :nodoc:
end
# A list of extensions, to be filled in by adapters that support them.
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 b6e17ad4ef..f8c9e13392 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
@@ -134,9 +134,7 @@ module ActiveRecord
time: { name: "time" },
date: { name: "date" },
binary: { name: "blob" },
- blob: { name: "blob" },
boolean: { name: "tinyint", limit: 1 },
- bigint: { name: "bigint" },
json: { name: "json" },
}
@@ -145,8 +143,7 @@ module ActiveRecord
# FIXME: Make the first parameter more similar for the two adapters
def initialize(connection, logger, connection_options, config)
- super(connection, logger)
- @connection_options, @config = connection_options, config
+ super(connection, logger, config)
@quoted_column_names, @quoted_table_names = {}, {}
@visitor = Arel::Visitors::MySQL.new self
@@ -226,12 +223,12 @@ module ActiveRecord
version >= '5.0.0'
end
- def get_advisory_lock(key, timeout = 0) # :nodoc:
- select_value("SELECT GET_LOCK('#{key}', #{timeout});").to_s == '1'
+ def get_advisory_lock(lock_name, timeout = 0) # :nodoc:
+ select_value("SELECT GET_LOCK('#{lock_name}', #{timeout});").to_s == '1'
end
- def release_advisory_lock(key) # :nodoc:
- select_value("SELECT RELEASE_LOCK('#{key}')").to_s == '1'
+ def release_advisory_lock(lock_name) # :nodoc:
+ select_value("SELECT RELEASE_LOCK('#{lock_name}')").to_s == '1'
end
def native_database_types
@@ -590,10 +587,8 @@ module ActiveRecord
sql = "SHOW FULL FIELDS FROM #{quote_table_name(table_name)}"
execute_and_free(sql, 'SCHEMA') do |result|
each_hash(result).map do |field|
- field_name = set_field_encoding(field[:Field])
- sql_type = field[:Type]
- type_metadata = fetch_type_metadata(sql_type, field[:Extra])
- new_column(field_name, field[:Default], type_metadata, field[:Null] == "YES", nil, field[:Collation])
+ type_metadata = fetch_type_metadata(field[:Type], field[:Extra])
+ new_column(field[:Field], field[:Default], type_metadata, field[:Null] == "YES", nil, field[:Collation])
end
end
end
@@ -1043,7 +1038,7 @@ module ActiveRecord
end
def create_table_definition(name, temporary = false, options = nil, as = nil) # :nodoc:
- MySQL::TableDefinition.new(native_database_types, name, temporary, options, as)
+ MySQL::TableDefinition.new(name, temporary, options, as)
end
def integer_to_sql(limit) # :nodoc:
@@ -1106,11 +1101,8 @@ module ActiveRecord
end
end
- ActiveRecord::Type.register(:json, MysqlJson, adapter: :mysql)
ActiveRecord::Type.register(:json, MysqlJson, adapter: :mysql2)
- ActiveRecord::Type.register(:string, MysqlString, adapter: :mysql)
ActiveRecord::Type.register(:string, MysqlString, adapter: :mysql2)
- ActiveRecord::Type.register(:unsigned_integer, Type::UnsignedInteger, adapter: :mysql)
ActiveRecord::Type.register(:unsigned_integer, Type::UnsignedInteger, adapter: :mysql2)
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 08d46fca96..f633892dee 100644
--- a/activerecord/lib/active_record/connection_adapters/connection_specification.rb
+++ b/activerecord/lib/active_record/connection_adapters/connection_specification.rb
@@ -175,7 +175,7 @@ module ActiveRecord
rescue Gem::LoadError => e
raise Gem::LoadError, "Specified '#{spec[:adapter]}' for database adapter, but the gem is not loaded. Add `gem '#{e.name}'` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord)."
rescue LoadError => e
- raise LoadError, "Could not load '#{path_to_adapter}'. Make sure that the adapter in config/database.yml is valid. If you use an adapter other than 'mysql', 'mysql2', 'postgresql' or 'sqlite3' add the necessary adapter gem to the Gemfile.", e.backtrace
+ raise LoadError, "Could not load '#{path_to_adapter}'. Make sure that the adapter in config/database.yml is valid. If you use an adapter other than 'mysql2', 'postgresql' or 'sqlite3' add the necessary adapter gem to the Gemfile.", e.backtrace
end
adapter_method = "#{spec[:adapter]}_connection"
diff --git a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
index 773ecbe126..6590e0140d 100644
--- a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
@@ -10,14 +10,13 @@ module ActiveRecord
config = config.symbolize_keys
config[:username] = 'root' if config[:username].nil?
-
+ config[:flags] ||= 0
if Mysql2::Client.const_defined? :FOUND_ROWS
- config[:flags] = Mysql2::Client::FOUND_ROWS
+ config[:flags] |= Mysql2::Client::FOUND_ROWS
end
client = Mysql2::Client.new(config)
- options = [config[:host], config[:username], config[:password], config[:database], config[:port], config[:socket], 0]
- ConnectionAdapters::Mysql2Adapter.new(client, logger, options, config)
+ ConnectionAdapters::Mysql2Adapter.new(client, logger, nil, config)
rescue Mysql2::Error => error
if error.message.include?("Unknown database")
raise ActiveRecord::NoDatabaseError
@@ -185,10 +184,6 @@ module ActiveRecord
def full_version
@full_version ||= @connection.server_info[:version]
end
-
- def set_field_encoding field_name
- field_name
- end
end
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
deleted file mode 100644
index 89d18ee14e..0000000000
--- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
+++ /dev/null
@@ -1,475 +0,0 @@
-require 'active_record/connection_adapters/abstract_mysql_adapter'
-require 'active_record/connection_adapters/statement_pool'
-require 'active_support/core_ext/hash/keys'
-
-gem 'mysql', '~> 2.9'
-require 'mysql'
-
-class Mysql # :nodoc: all
- class Time
- # Used for casting DateTime fields to a MySQL friendly Time.
- # This was documented in 48498da0dfed5239ea1eafb243ce47d7e3ce9e8e
- def to_date
- Date.new(year, month, day)
- end
- end
- class Stmt; include Enumerable end
- class Result; include Enumerable end
-end
-
-module ActiveRecord
- module ConnectionHandling # :nodoc:
- # Establishes a connection to the database that's used by all Active Record objects.
- def mysql_connection(config)
- config = config.symbolize_keys
- host = config[:host]
- port = config[:port]
- socket = config[:socket]
- username = config[:username] ? config[:username].to_s : 'root'
- password = config[:password].to_s
- database = config[:database]
-
- mysql = Mysql.init
- mysql.ssl_set(config[:sslkey], config[:sslcert], config[:sslca], config[:sslcapath], config[:sslcipher]) if config[:sslca] || config[:sslkey]
-
- default_flags = Mysql.const_defined?(:CLIENT_MULTI_RESULTS) ? Mysql::CLIENT_MULTI_RESULTS : 0
- default_flags |= Mysql::CLIENT_FOUND_ROWS if Mysql.const_defined?(:CLIENT_FOUND_ROWS)
- options = [host, username, password, database, port, socket, default_flags]
- ConnectionAdapters::MysqlAdapter.new(mysql, logger, options, config)
- rescue Mysql::Error => error
- if error.message.include?("Unknown database")
- raise ActiveRecord::NoDatabaseError
- else
- raise
- end
- end
- end
-
- module ConnectionAdapters
- # The MySQL adapter will work with both Ruby/MySQL, which is a Ruby-based MySQL adapter that comes bundled with Active Record, and with
- # the faster C-based MySQL/Ruby adapter (available both as a gem and from http://www.tmtm.org/en/mysql/ruby/).
- #
- # Options:
- #
- # * <tt>:host</tt> - Defaults to "localhost".
- # * <tt>:port</tt> - Defaults to 3306.
- # * <tt>:socket</tt> - Defaults to "/tmp/mysql.sock".
- # * <tt>:username</tt> - Defaults to "root"
- # * <tt>:password</tt> - Defaults to nothing.
- # * <tt>:database</tt> - The name of the database. No default, must be provided.
- # * <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.7/en/auto-reconnect.html).
- # * <tt>:strict</tt> - Defaults to true. Enable STRICT_ALL_TABLES. (See MySQL documentation: http://dev.mysql.com/doc/refman/5.7/en/sql-mode.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.7/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.
- # * <tt>:sslcapath</tt> - Necessary to use MySQL with an SSL connection.
- # * <tt>:sslcipher</tt> - Necessary to use MySQL with an SSL connection.
- #
- class MysqlAdapter < AbstractMysqlAdapter
- ADAPTER_NAME = 'MySQL'.freeze
-
- class StatementPool < ConnectionAdapters::StatementPool
- private
-
- def dealloc(stmt)
- stmt[:stmt].close
- end
- end
-
- def initialize(connection, logger, connection_options, config)
- super
- @statements = StatementPool.new(self.class.type_cast_config_to_integer(config.fetch(:statement_limit) { 1000 }))
- @client_encoding = nil
- connect
- end
-
- # Returns true, since this connection adapter supports prepared statement
- # caching.
- def supports_statement_cache?
- true
- end
-
- # HELPER METHODS ===========================================
-
- def each_hash(result) # :nodoc:
- if block_given?
- result.each_hash do |row|
- row.symbolize_keys!
- yield row
- end
- else
- to_enum(:each_hash, result)
- end
- end
-
- def error_number(exception) # :nodoc:
- exception.errno if exception.respond_to?(:errno)
- end
-
- # QUOTING ==================================================
-
- def quote_string(string) #:nodoc:
- @connection.quote(string)
- end
-
- #--
- # CONNECTION MANAGEMENT ====================================
- #++
-
- def active?
- if @connection.respond_to?(:stat)
- @connection.stat
- else
- @connection.query 'select 1'
- end
-
- # mysql-ruby doesn't raise an exception when stat fails.
- if @connection.respond_to?(:errno)
- @connection.errno.zero?
- else
- true
- end
- rescue Mysql::Error
- false
- end
-
- def reconnect!
- super
- disconnect!
- connect
- end
-
- # Disconnects from the database if already connected. Otherwise, this
- # method does nothing.
- def disconnect!
- super
- @connection.close rescue nil
- end
-
- def reset!
- if @connection.respond_to?(:change_user)
- # See http://bugs.mysql.com/bug.php?id=33540 -- the workaround way to
- # reset the connection is to change the user to the same user.
- @connection.change_user(@config[:username], @config[:password], @config[:database])
- configure_connection
- end
- end
-
- #--
- # DATABASE STATEMENTS ======================================
- #++
-
- def select_all(arel, name = nil, binds = [])
- if ExplainRegistry.collect? && prepared_statements
- unprepared_statement { super }
- else
- super
- end
- end
-
- def select_rows(sql, name = nil, binds = [])
- @connection.query_with_result = true
- rows = exec_query(sql, name, binds).rows
- @connection.more_results && @connection.next_result # invoking stored procedures with CLIENT_MULTI_RESULTS requires this to tidy up else connection will be dropped
- rows
- end
-
- # Clears the prepared statements cache.
- def clear_cache!
- super
- @statements.clear
- end
-
- # Taken from here:
- # https://github.com/tmtm/ruby-mysql/blob/master/lib/mysql/charset.rb
- # Author: TOMITA Masahiro <tommy@tmtm.org>
- ENCODINGS = {
- "armscii8" => nil,
- "ascii" => Encoding::US_ASCII,
- "big5" => Encoding::Big5,
- "binary" => Encoding::ASCII_8BIT,
- "cp1250" => Encoding::Windows_1250,
- "cp1251" => Encoding::Windows_1251,
- "cp1256" => Encoding::Windows_1256,
- "cp1257" => Encoding::Windows_1257,
- "cp850" => Encoding::CP850,
- "cp852" => Encoding::CP852,
- "cp866" => Encoding::IBM866,
- "cp932" => Encoding::Windows_31J,
- "dec8" => nil,
- "eucjpms" => Encoding::EucJP_ms,
- "euckr" => Encoding::EUC_KR,
- "gb2312" => Encoding::EUC_CN,
- "gbk" => Encoding::GBK,
- "geostd8" => nil,
- "greek" => Encoding::ISO_8859_7,
- "hebrew" => Encoding::ISO_8859_8,
- "hp8" => nil,
- "keybcs2" => nil,
- "koi8r" => Encoding::KOI8_R,
- "koi8u" => Encoding::KOI8_U,
- "latin1" => Encoding::ISO_8859_1,
- "latin2" => Encoding::ISO_8859_2,
- "latin5" => Encoding::ISO_8859_9,
- "latin7" => Encoding::ISO_8859_13,
- "macce" => Encoding::MacCentEuro,
- "macroman" => Encoding::MacRoman,
- "sjis" => Encoding::SHIFT_JIS,
- "swe7" => nil,
- "tis620" => Encoding::TIS_620,
- "ucs2" => Encoding::UTF_16BE,
- "ujis" => Encoding::EucJP_ms,
- "utf8" => Encoding::UTF_8,
- "utf8mb4" => Encoding::UTF_8,
- }
-
- # Get the client encoding for this database
- def client_encoding
- return @client_encoding if @client_encoding
-
- result = exec_query(
- "select @@character_set_client",
- 'SCHEMA')
- @client_encoding = ENCODINGS[result.rows.last.last]
- end
-
- def exec_query(sql, name = 'SQL', binds = [], prepare: false)
- if without_prepared_statement?(binds)
- result_set, affected_rows = exec_without_stmt(sql, name)
- else
- result_set, affected_rows = exec_stmt(sql, name, binds, cache_stmt: prepare)
- end
-
- yield affected_rows if block_given?
-
- result_set
- end
-
- def last_inserted_id(result)
- @connection.insert_id
- end
-
- module Fields # :nodoc:
- class DateTime < Type::DateTime # :nodoc:
- def cast_value(value)
- if Mysql::Time === value
- new_time(
- value.year,
- value.month,
- value.day,
- value.hour,
- value.minute,
- value.second,
- value.second_part)
- else
- super
- end
- end
- end
-
- class Time < Type::Time # :nodoc:
- def cast_value(value)
- if Mysql::Time === value
- new_time(
- 2000,
- 01,
- 01,
- value.hour,
- value.minute,
- value.second,
- value.second_part)
- else
- super
- end
- end
- end
-
- class << self
- TYPES = Type::HashLookupTypeMap.new # :nodoc:
-
- delegate :register_type, :alias_type, to: :TYPES
-
- def find_type(field)
- if field.type == Mysql::Field::TYPE_TINY && field.length > 1
- TYPES.lookup(Mysql::Field::TYPE_LONG)
- else
- TYPES.lookup(field.type)
- end
- end
- end
-
- register_type Mysql::Field::TYPE_TINY, Type::Boolean.new
- register_type Mysql::Field::TYPE_LONG, Type::Integer.new
- alias_type Mysql::Field::TYPE_LONGLONG, Mysql::Field::TYPE_LONG
- alias_type Mysql::Field::TYPE_NEWDECIMAL, Mysql::Field::TYPE_LONG
-
- register_type Mysql::Field::TYPE_DATE, Type::Date.new
- register_type Mysql::Field::TYPE_DATETIME, Fields::DateTime.new
- register_type Mysql::Field::TYPE_TIME, Fields::Time.new
- register_type Mysql::Field::TYPE_FLOAT, Type::Float.new
- end
-
- def initialize_type_map(m) # :nodoc:
- super
- register_class_with_precision m, %r(datetime)i, Fields::DateTime
- register_class_with_precision m, %r(time)i, Fields::Time
- end
-
- def exec_without_stmt(sql, name = 'SQL') # :nodoc:
- # Some queries, like SHOW CREATE TABLE don't work through the prepared
- # statement API. For those queries, we need to use this method. :'(
- log(sql, name) do
- result = @connection.query(sql)
- affected_rows = @connection.affected_rows
-
- if result
- types = {}
- fields = []
- result.fetch_fields.each { |field|
- field_name = field.name
- fields << field_name
-
- if field.decimals > 0
- types[field_name] = Type::Decimal.new
- else
- types[field_name] = Fields.find_type field
- end
- }
-
- result_set = ActiveRecord::Result.new(fields, result.to_a, types)
- result.free
- else
- result_set = ActiveRecord::Result.new([], [])
- end
-
- [result_set, affected_rows]
- end
- end
-
- def execute_and_free(sql, name = nil) # :nodoc:
- result = execute(sql, name)
- ret = yield result
- result.free
- ret
- end
-
- def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) #:nodoc:
- super sql, name
- id_value || @connection.insert_id
- end
- alias :create :insert_sql
-
- def exec_delete(sql, name, binds) # :nodoc:
- affected_rows = 0
-
- exec_query(sql, name, binds) do |n|
- affected_rows = n
- end
-
- affected_rows
- end
- alias :exec_update :exec_delete
-
- def begin_db_transaction #:nodoc:
- exec_query "BEGIN"
- end
-
- private
-
- def exec_stmt(sql, name, binds, cache_stmt: false)
- cache = {}
- type_casted_binds = binds.map { |attr| type_cast(attr.value_for_database) }
-
- log(sql, name, binds) do
- if !cache_stmt
- stmt = @connection.prepare(sql)
- else
- cache = @statements[sql] ||= {
- :stmt => @connection.prepare(sql)
- }
- stmt = cache[:stmt]
- end
-
- begin
- stmt.execute(*type_casted_binds)
- rescue Mysql::Error => e
- # Older versions of MySQL leave the prepared statement in a bad
- # place when an error occurs. To support older MySQL versions, we
- # need to close the statement and delete the statement from the
- # cache.
- if !cache_stmt
- stmt.close
- else
- @statements.delete sql
- end
- raise e
- end
-
- cols = nil
- if metadata = stmt.result_metadata
- cols = cache[:cols] ||= metadata.fetch_fields.map(&:name)
- metadata.free
- end
-
- result_set = ActiveRecord::Result.new(cols, stmt.to_a) if cols
- affected_rows = stmt.affected_rows
-
- stmt.free_result
- stmt.close if !cache_stmt
-
- [result_set, affected_rows]
- end
- end
-
- def connect
- encoding = @config[:encoding]
- if encoding
- @connection.options(Mysql::SET_CHARSET_NAME, encoding) rescue nil
- end
-
- if @config[:sslca] || @config[:sslkey]
- @connection.ssl_set(@config[:sslkey], @config[:sslcert], @config[:sslca], @config[:sslcapath], @config[:sslcipher])
- end
-
- @connection.options(Mysql::OPT_CONNECT_TIMEOUT, @config[:connect_timeout]) if @config[:connect_timeout]
- @connection.options(Mysql::OPT_READ_TIMEOUT, @config[:read_timeout]) if @config[:read_timeout]
- @connection.options(Mysql::OPT_WRITE_TIMEOUT, @config[:write_timeout]) if @config[:write_timeout]
-
- @connection.real_connect(*@connection_options)
-
- # reconnect must be set after real_connect is called, because real_connect sets it to false internally
- @connection.reconnect = !!@config[:reconnect] if @connection.respond_to?(:reconnect=)
-
- configure_connection
- end
-
- # Many Rails applications monkey-patch a replacement of the configure_connection method
- # and don't call 'super', so leave this here even though it looks superfluous.
- def configure_connection
- super
- end
-
- def select(sql, name = nil, binds = [])
- @connection.query_with_result = true
- rows = super
- @connection.more_results && @connection.next_result # invoking stored procedures with CLIENT_MULTI_RESULTS requires this to tidy up else connection will be dropped
- rows
- end
-
- # Returns the full version of the connected MySQL server.
- def full_version
- @full_version ||= @connection.server_info
- end
-
- def set_field_encoding field_name
- field_name.force_encoding(client_encoding)
- if internal_enc = Encoding.default_internal
- field_name = field_name.encode!(internal_enc)
- end
- field_name
- end
- end
- end
-end
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
index a48d64f7bd..67e727d8ed 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
@@ -169,15 +169,18 @@ module ActiveRecord
# Returns an array of indexes for the given table.
def indexes(table_name, name = nil)
- result = query(<<-SQL, 'SCHEMA')
- SELECT distinct i.relname, d.indisunique, d.indkey, pg_get_indexdef(d.indexrelid), t.oid
- FROM pg_class t
- INNER JOIN pg_index d ON t.oid = d.indrelid
- INNER JOIN pg_class i ON d.indexrelid = i.oid
- WHERE i.relkind = 'i'
- AND d.indisprimary = 'f'
- AND t.relname = '#{table_name}'
- AND i.relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname = ANY (current_schemas(false)) )
+ table = Utils.extract_schema_qualified_name(table_name.to_s)
+
+ result = query(<<-SQL, 'SCHEMA')
+ SELECT distinct i.relname, d.indisunique, d.indkey, pg_get_indexdef(d.indexrelid), t.oid
+ FROM pg_class t
+ INNER JOIN pg_index d ON t.oid = d.indrelid
+ INNER JOIN pg_class i ON d.indexrelid = i.oid
+ LEFT JOIN pg_namespace n ON n.oid = i.relnamespace
+ WHERE i.relkind = 'i'
+ AND d.indisprimary = 'f'
+ AND t.relname = '#{table.identifier}'
+ AND n.nspname = #{table.schema ? "'#{table.schema}'" : 'ANY (current_schemas(false))'}
ORDER BY i.relname
SQL
@@ -504,14 +507,27 @@ module ActiveRecord
end
def remove_index(table_name, options = {}) #:nodoc:
- index_name = index_name_for_remove(table_name, options)
+ table = Utils.extract_schema_qualified_name(table_name.to_s)
+
+ if options.is_a?(Hash) && options.key?(:name)
+ provided_index = Utils.extract_schema_qualified_name(options[:name].to_s)
+
+ options[:name] = provided_index.identifier
+ table = PostgreSQL::Name.new(provided_index.schema, table.identifier) unless table.schema.present?
+
+ if provided_index.schema.present? && table.schema != provided_index.schema
+ raise ArgumentError.new("Index schema '#{provided_index.schema}' does not match table schema '#{table.schema}'")
+ end
+ end
+
+ index_to_remove = PostgreSQL::Name.new(table.schema, index_name_for_remove(table.to_s, options))
algorithm =
- if Hash === options && options.key?(:algorithm)
+ if options.is_a?(Hash) && options.key?(:algorithm)
index_algorithms.fetch(options[:algorithm]) do
raise ArgumentError.new("Algorithm must be one of the following: #{index_algorithms.keys.map(&:inspect).join(', ')}")
end
end
- execute "DROP INDEX #{algorithm} #{quote_table_name(index_name)}"
+ execute "DROP INDEX #{algorithm} #{quote_table_name(index_to_remove)}"
end
# Renames an index of a table. Raises error if length of new
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
index ed6ab8235f..a1ec570042 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
@@ -72,7 +72,6 @@ module ActiveRecord
NATIVE_DATABASE_TYPES = {
primary_key: "serial primary key",
- bigserial: "bigserial",
string: { name: "character varying" },
text: { name: "text" },
integer: { name: "integer" },
@@ -89,7 +88,6 @@ module ActiveRecord
int8range: { name: "int8range" },
binary: { name: "bytea" },
boolean: { name: "boolean" },
- bigint: { name: "bigint" },
xml: { name: "xml" },
tsvector: { name: "tsvector" },
hstore: { name: "hstore" },
@@ -102,6 +100,12 @@ module ActiveRecord
ltree: { name: "ltree" },
citext: { name: "citext" },
point: { name: "point" },
+ line: { name: "line" },
+ lseg: { name: "lseg" },
+ box: { name: "box" },
+ path: { name: "path" },
+ polygon: { name: "polygon" },
+ circle: { name: "circle" },
bit: { name: "bit" },
bit_varying: { name: "bit varying" },
money: { name: "money" },
@@ -188,7 +192,7 @@ module ActiveRecord
# Initializes and connects a PostgreSQL adapter.
def initialize(connection, logger, connection_parameters, config)
- super(connection, logger)
+ super(connection, logger, config)
@visitor = Arel::Visitors::PostgreSQL.new self
if self.class.type_cast_config_to_boolean(config.fetch(:prepared_statements) { true })
@@ -198,7 +202,7 @@ module ActiveRecord
@prepared_statements = false
end
- @connection_parameters, @config = connection_parameters, config
+ @connection_parameters = connection_parameters
# @local_tz is initialized as nil to avoid warnings when connect tries to use it
@local_tz = nil
@@ -306,18 +310,18 @@ module ActiveRecord
postgresql_version >= 90300
end
- def get_advisory_lock(key) # :nodoc:
- unless key.is_a?(Integer) && key.bit_length <= 63
- raise(ArgumentError, "Postgres requires advisory lock keys to be a signed 64 bit integer")
+ def get_advisory_lock(lock_id) # :nodoc:
+ unless lock_id.is_a?(Integer) && lock_id.bit_length <= 63
+ raise(ArgumentError, "Postgres requires advisory lock ids to be a signed 64 bit integer")
end
- select_value("SELECT pg_try_advisory_lock(#{key});")
+ select_value("SELECT pg_try_advisory_lock(#{lock_id});")
end
- def release_advisory_lock(key) # :nodoc:
- unless key.is_a?(Integer) && key.bit_length <= 63
- raise(ArgumentError, "Postgres requires advisory lock keys to be a signed 64 bit integer")
+ def release_advisory_lock(lock_id) # :nodoc:
+ unless lock_id.is_a?(Integer) && lock_id.bit_length <= 63
+ raise(ArgumentError, "Postgres requires advisory lock ids to be a signed 64 bit integer")
end
- select_value("SELECT pg_advisory_unlock(#{key})")
+ select_value("SELECT pg_advisory_unlock(#{lock_id})")
end
def enable_extension(name)
@@ -457,15 +461,15 @@ module ActiveRecord
m.register_type 'macaddr', OID::SpecializedString.new(:macaddr)
m.register_type 'citext', OID::SpecializedString.new(:citext)
m.register_type 'ltree', OID::SpecializedString.new(:ltree)
+ m.register_type 'line', OID::SpecializedString.new(:line)
+ m.register_type 'lseg', OID::SpecializedString.new(:lseg)
+ m.register_type 'box', OID::SpecializedString.new(:box)
+ m.register_type 'path', OID::SpecializedString.new(:path)
+ m.register_type 'polygon', OID::SpecializedString.new(:polygon)
+ m.register_type 'circle', OID::SpecializedString.new(:circle)
# FIXME: why are we keeping these types as strings?
m.alias_type 'interval', 'varchar'
- m.alias_type 'path', 'varchar'
- m.alias_type 'line', 'varchar'
- m.alias_type 'polygon', 'varchar'
- m.alias_type 'circle', 'varchar'
- m.alias_type 'lseg', 'varchar'
- m.alias_type 'box', 'varchar'
register_class_with_precision m, 'time', Type::Time
register_class_with_precision m, 'timestamp', OID::DateTime
@@ -736,7 +740,7 @@ module ActiveRecord
end
def create_table_definition(name, temporary = false, options = nil, as = nil) # :nodoc:
- PostgreSQL::TableDefinition.new native_database_types, name, temporary, options, as
+ PostgreSQL::TableDefinition.new(name, temporary, options, as)
end
def can_perform_case_insensitive_comparison_for?(column)
@@ -812,9 +816,8 @@ module ActiveRecord
ActiveRecord::Type.register(:json, OID::Json, adapter: :postgresql)
ActiveRecord::Type.register(:jsonb, OID::Jsonb, adapter: :postgresql)
ActiveRecord::Type.register(:money, OID::Money, adapter: :postgresql)
- ActiveRecord::Type.register(:point, OID::Point, adapter: :postgresql)
+ ActiveRecord::Type.register(:point, OID::Rails51Point, adapter: :postgresql)
ActiveRecord::Type.register(:legacy_point, OID::Point, adapter: :postgresql)
- ActiveRecord::Type.register(:rails_5_1_point, OID::Rails51Point, adapter: :postgresql)
ActiveRecord::Type.register(:uuid, OID::Uuid, adapter: :postgresql)
ActiveRecord::Type.register(:vector, OID::Vector, adapter: :postgresql)
ActiveRecord::Type.register(:xml, OID::Xml, adapter: :postgresql)
diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
index 90df9b8825..163cbb875f 100644
--- a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
@@ -78,11 +78,10 @@ module ActiveRecord
end
def initialize(connection, logger, connection_options, config)
- super(connection, logger)
+ super(connection, logger, config)
@active = nil
@statements = StatementPool.new(self.class.type_cast_config_to_integer(config.fetch(:statement_limit) { 1000 }))
- @config = config
@visitor = Arel::Visitors::SQLite.new self
@quoted_column_names = {}
@@ -130,6 +129,10 @@ module ActiveRecord
true
end
+ def supports_datetime_with_precision?
+ true
+ end
+
def active?
@active != false
end
diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb
index deb7d7d06d..ed1bbf5dcd 100644
--- a/activerecord/lib/active_record/fixtures.rb
+++ b/activerecord/lib/active_record/fixtures.rb
@@ -401,7 +401,7 @@ module ActiveRecord
# It's possible to set the fixture's model class directly in the YAML file.
# This is helpful when fixtures are loaded outside tests and
# +set_fixture_class+ is not available (e.g.
- # when running <tt>rake db:fixtures:load</tt>).
+ # when running <tt>rails db:fixtures:load</tt>).
#
# _fixture:
# model_class: User
diff --git a/activerecord/lib/active_record/gem_version.rb b/activerecord/lib/active_record/gem_version.rb
index a388b529c9..ecf4046bff 100644
--- a/activerecord/lib/active_record/gem_version.rb
+++ b/activerecord/lib/active_record/gem_version.rb
@@ -8,7 +8,7 @@ module ActiveRecord
MAJOR = 5
MINOR = 0
TINY = 0
- PRE = "alpha"
+ PRE = "beta1"
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 589c70db0d..6259c4cd33 100644
--- a/activerecord/lib/active_record/inheritance.rb
+++ b/activerecord/lib/active_record/inheritance.rb
@@ -51,8 +51,8 @@ module ActiveRecord
end
attrs = args.first
- if subclass_from_attributes?(attrs)
- subclass = subclass_from_attributes(attrs)
+ if has_attribute?(inheritance_column)
+ subclass = subclass_from_attributes(attrs) || subclass_from_attributes(column_defaults)
end
if subclass && subclass != self
@@ -163,7 +163,7 @@ module ActiveRecord
end
def using_single_table_inheritance?(record)
- record[inheritance_column].present? && columns_hash.include?(inheritance_column)
+ record[inheritance_column].present? && has_attribute?(inheritance_column)
end
def find_sti_class(type_name)
@@ -195,17 +195,14 @@ module ActiveRecord
# Detect the subclass from the inheritance column of attrs. If the inheritance column value
# is not self or a valid subclass, raises ActiveRecord::SubclassNotFound
- # If this is a StrongParameters hash, and access to inheritance_column is not permitted,
- # this will ignore the inheritance column and return nil
- def subclass_from_attributes?(attrs)
- attribute_names.include?(inheritance_column) && attrs.is_a?(Hash)
- end
-
def subclass_from_attributes(attrs)
- subclass_name = attrs.with_indifferent_access[inheritance_column]
+ attrs = attrs.to_h if attrs.respond_to?(:permitted?)
+ if attrs.is_a?(Hash)
+ subclass_name = attrs.with_indifferent_access[inheritance_column]
- if subclass_name.present?
- find_sti_class(subclass_name)
+ if subclass_name.present?
+ find_sti_class(subclass_name)
+ end
end
end
end
diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb
index ffd243a517..ba238ea142 100644
--- a/activerecord/lib/active_record/migration.rb
+++ b/activerecord/lib/active_record/migration.rb
@@ -13,7 +13,7 @@ module ActiveRecord
# For example the following migration is not reversible.
# Rolling back this migration will raise an ActiveRecord::IrreversibleMigration error.
#
- # class IrreversibleMigrationExample < ActiveRecord::Migration
+ # class IrreversibleMigrationExample < ActiveRecord::Migration[5.0]
# def change
# create_table :distributors do |t|
# t.string :zipcode
@@ -31,7 +31,7 @@ module ActiveRecord
#
# 1. Define <tt>#up</tt> and <tt>#down</tt> methods instead of <tt>#change</tt>:
#
- # class ReversibleMigrationExample < ActiveRecord::Migration
+ # class ReversibleMigrationExample < ActiveRecord::Migration[5.0]
# def up
# create_table :distributors do |t|
# t.string :zipcode
@@ -56,7 +56,7 @@ module ActiveRecord
#
# 2. Use the #reversible method in <tt>#change</tt> method:
#
- # class ReversibleMigrationExample < ActiveRecord::Migration
+ # class ReversibleMigrationExample < ActiveRecord::Migration[5.0]
# def change
# create_table :distributors do |t|
# t.string :zipcode
@@ -126,9 +126,9 @@ module ActiveRecord
class PendingMigrationError < MigrationError#:nodoc:
def initialize(message = nil)
if !message && defined?(Rails.env)
- super("Migrations are pending. To resolve this issue, run:\n\n\tbin/rake db:migrate RAILS_ENV=#{::Rails.env}.")
+ super("Migrations are pending. To resolve this issue, run:\n\n\tbin/rails db:migrate RAILS_ENV=#{::Rails.env}.")
elsif !message
- super("Migrations are pending. To resolve this issue, run:\n\n\tbin/rake db:migrate.")
+ super("Migrations are pending. To resolve this issue, run:\n\n\tbin/rails db:migrate.")
else
super
end
@@ -155,7 +155,7 @@ module ActiveRecord
#
# Example of a simple migration:
#
- # class AddSsl < ActiveRecord::Migration
+ # class AddSsl < ActiveRecord::Migration[5.0]
# def up
# add_column :accounts, :ssl_enabled, :boolean, default: true
# end
@@ -175,7 +175,7 @@ module ActiveRecord
#
# Example of a more complex migration that also needs to initialize data:
#
- # class AddSystemSettings < ActiveRecord::Migration
+ # class AddSystemSettings < ActiveRecord::Migration[5.0]
# def up
# create_table :system_settings do |t|
# t.string :name
@@ -301,23 +301,23 @@ module ActiveRecord
# rails generate migration add_fieldname_to_tablename fieldname:string
#
# This will generate the file <tt>timestamp_add_fieldname_to_tablename.rb</tt>, which will look like this:
- # class AddFieldnameToTablename < ActiveRecord::Migration
+ # class AddFieldnameToTablename < ActiveRecord::Migration[5.0]
# def change
# add_column :tablenames, :fieldname, :string
# end
# end
#
# To run migrations against the currently configured database, use
- # <tt>rake db:migrate</tt>. This will update the database by running all of the
+ # <tt>rails db:migrate</tt>. This will update the database by running all of the
# pending migrations, creating the <tt>schema_migrations</tt> table
# (see "About the schema_migrations table" section below) if missing. It will also
# invoke the db:schema:dump task, which will update your db/schema.rb file
# to match the structure of your database.
#
# To roll the database back to a previous migration version, use
- # <tt>rake db:migrate VERSION=X</tt> where <tt>X</tt> is the version to which
+ # <tt>rails db:migrate VERSION=X</tt> where <tt>X</tt> is the version to which
# 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
+ # wish to rollback last few migrations. <tt>rails db:migrate STEP=2</tt> will rollback
# the latest two migrations.
#
# If any of the migrations throw an <tt>ActiveRecord::IrreversibleMigration</tt> exception,
@@ -332,7 +332,7 @@ module ActiveRecord
#
# Not all migrations change the schema. Some just fix the data:
#
- # class RemoveEmptyTags < ActiveRecord::Migration
+ # class RemoveEmptyTags < ActiveRecord::Migration[5.0]
# def up
# Tag.all.each { |tag| tag.destroy if tag.pages.empty? }
# end
@@ -345,7 +345,7 @@ module ActiveRecord
#
# Others remove columns when they migrate up instead of down:
#
- # class RemoveUnnecessaryItemAttributes < ActiveRecord::Migration
+ # class RemoveUnnecessaryItemAttributes < ActiveRecord::Migration[5.0]
# def up
# remove_column :items, :incomplete_items_count
# remove_column :items, :completed_items_count
@@ -359,7 +359,7 @@ module ActiveRecord
#
# And sometimes you need to do something in SQL not abstracted directly by migrations:
#
- # class MakeJoinUnique < ActiveRecord::Migration
+ # class MakeJoinUnique < ActiveRecord::Migration[5.0]
# def up
# execute "ALTER TABLE `pages_linked_pages` ADD UNIQUE `page_id_linked_page_id` (`page_id`,`linked_page_id`)"
# end
@@ -376,7 +376,7 @@ module ActiveRecord
# <tt>Base#reset_column_information</tt> in order to ensure that the model has the
# latest column data from after the new column was added. Example:
#
- # class AddPeopleSalary < ActiveRecord::Migration
+ # class AddPeopleSalary < ActiveRecord::Migration[5.0]
# def up
# add_column :people, :salary, :integer
# Person.reset_column_information
@@ -434,7 +434,7 @@ module ActiveRecord
# To define a reversible migration, define the +change+ method in your
# migration like this:
#
- # class TenderloveMigration < ActiveRecord::Migration
+ # class TenderloveMigration < ActiveRecord::Migration[5.0]
# def change
# create_table(:horses) do |t|
# t.column :content, :text
@@ -464,7 +464,7 @@ module ActiveRecord
# can't execute inside a transaction though, and for these situations
# you can turn the automatic transactions off.
#
- # class ChangeEnum < ActiveRecord::Migration
+ # class ChangeEnum < ActiveRecord::Migration[5.0]
# disable_ddl_transaction!
#
# def up
@@ -476,6 +476,32 @@ module ActiveRecord
# are in a Migration with <tt>self.disable_ddl_transaction!</tt>.
class Migration
autoload :CommandRecorder, 'active_record/migration/command_recorder'
+ autoload :Compatibility, 'active_record/migration/compatibility'
+
+ # This must be defined before the inherited hook, below
+ class Current < Migration # :nodoc:
+ end
+
+ def self.inherited(subclass) # :nodoc:
+ super
+ if subclass.superclass == Migration
+ subclass.include Compatibility::Legacy
+ end
+ end
+
+ def self.[](version)
+ version = version.to_s
+ name = "V#{version.tr('.', '_')}"
+ unless Compatibility.const_defined?(name)
+ versions = Compatibility.constants.grep(/\AV[0-9_]+\z/).map { |s| s.to_s.delete('V').tr('_', '.').inspect }
+ raise "Unknown migration version #{version.inspect}; expected one of #{versions.sort.join(', ')}"
+ end
+ Compatibility.const_get(name)
+ end
+
+ def self.current_version
+ Rails.version.to_f
+ end
MigrationFilenameRegexp = /\A([0-9]+)_([_a-z0-9]*)\.?([_a-z0-9]*)?\.rb\z/ # :nodoc:
@@ -509,6 +535,10 @@ module ActiveRecord
attr_accessor :delegate # :nodoc:
attr_accessor :disable_ddl_transaction # :nodoc:
+ def nearest_delegate # :nodoc:
+ delegate || superclass.nearest_delegate
+ end
+
# Raises <tt>ActiveRecord::PendingMigrationError</tt> error if any migrations are pending.
def check_pending!(connection = Base.connection)
raise ActiveRecord::PendingMigrationError if ActiveRecord::Migrator.needs_migration?(connection)
@@ -520,7 +550,7 @@ module ActiveRecord
FileUtils.cd Rails.root do
current_config = Base.connection_config
Base.clear_all_connections!
- system("bin/rake db:test:prepare")
+ system("bin/rails db:test:prepare")
# Establish a new connection, the old database may be gone (db:test:prepare uses purge)
Base.establish_connection(current_config)
end
@@ -535,7 +565,7 @@ module ActiveRecord
end
def method_missing(name, *args, &block) # :nodoc:
- (delegate || superclass.delegate).send(name, *args, &block)
+ nearest_delegate.send(name, *args, &block)
end
def migrate(direction)
@@ -575,7 +605,7 @@ module ActiveRecord
# and create the table 'apples' on the way up, and the reverse
# on the way down.
#
- # class FixTLMigration < ActiveRecord::Migration
+ # class FixTLMigration < ActiveRecord::Migration[5.0]
# def change
# revert do
# create_table(:horses) do |t|
@@ -594,7 +624,7 @@ module ActiveRecord
#
# require_relative '20121212123456_tenderlove_migration'
#
- # class FixupTLMigration < ActiveRecord::Migration
+ # class FixupTLMigration < ActiveRecord::Migration[5.0]
# def change
# revert TenderloveMigration
#
@@ -647,7 +677,7 @@ module ActiveRecord
# when the three columns 'first_name', 'last_name' and 'full_name' exist,
# even when migrating down:
#
- # class SplitNameMigration < ActiveRecord::Migration
+ # class SplitNameMigration < ActiveRecord::Migration[5.0]
# def change
# add_column :users, :first_name, :string
# add_column :users, :last_name, :string
@@ -1202,17 +1232,17 @@ module ActiveRecord
end
def with_advisory_lock
- key = generate_migrator_advisory_lock_key
- got_lock = Base.connection.get_advisory_lock(key)
+ lock_id = generate_migrator_advisory_lock_id
+ got_lock = Base.connection.get_advisory_lock(lock_id)
raise ConcurrentMigrationError unless got_lock
load_migrated # reload schema_migrations to be sure it wasn't changed by another process before we got the lock
yield
ensure
- Base.connection.release_advisory_lock(key) if got_lock
+ Base.connection.release_advisory_lock(lock_id) if got_lock
end
MIGRATOR_SALT = 2053462845
- def generate_migrator_advisory_lock_key
+ def generate_migrator_advisory_lock_id
db_name_hash = Zlib.crc32(Base.connection.current_database)
MIGRATOR_SALT * db_name_hash
end
diff --git a/activerecord/lib/active_record/migration/compatibility.rb b/activerecord/lib/active_record/migration/compatibility.rb
new file mode 100644
index 0000000000..831bfa2df3
--- /dev/null
+++ b/activerecord/lib/active_record/migration/compatibility.rb
@@ -0,0 +1,90 @@
+module ActiveRecord
+ class Migration
+ module Compatibility # :nodoc: all
+ V5_0 = Current
+
+ module FourTwoShared
+ module TableDefinition
+ def timestamps(*, **options)
+ options[:null] = true if options[:null].nil?
+ super
+ end
+ end
+
+ def create_table(table_name, options = {})
+ if block_given?
+ super(table_name, options) do |t|
+ class << t
+ prepend TableDefinition
+ end
+ yield t
+ end
+ else
+ super
+ end
+ end
+
+ def add_timestamps(*, **options)
+ options[:null] = true if options[:null].nil?
+ super
+ end
+
+ def index_exists?(table_name, column_name, options = {})
+ column_names = Array(column_name).map(&:to_s)
+ options[:name] =
+ if options.key?(:name).present?
+ options[:name].to_s
+ else
+ index_name(table_name, column: column_names)
+ end
+ super
+ end
+
+ def remove_index(table_name, options = {})
+ index_name = index_name_for_remove(table_name, options)
+ execute "DROP INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)}"
+ end
+
+ private
+
+ def index_name_for_remove(table_name, options = {})
+ index_name = index_name(table_name, options)
+
+ unless index_name_exists?(table_name, index_name, true)
+ if options.is_a?(Hash) && options.has_key?(:name)
+ options_without_column = options.dup
+ options_without_column.delete :column
+ index_name_without_column = index_name(table_name, options_without_column)
+
+ return index_name_without_column if index_name_exists?(table_name, index_name_without_column, false)
+ end
+
+ raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' does not exist"
+ end
+
+ index_name
+ end
+ end
+
+ class V4_2 < V5_0
+ # 4.2 is defined as a module because it needs to be shared with
+ # Legacy. When the time comes, V5_0 should be defined straight
+ # in its class.
+ include FourTwoShared
+ end
+
+ module Legacy
+ include FourTwoShared
+
+ def run(*)
+ ActiveSupport::Deprecation.warn \
+ "Directly inheriting from ActiveRecord::Migration is deprecated. " \
+ "Please specify the Rails release the migration was written for:\n" \
+ "\n" \
+ " class #{self.class.name} < ActiveRecord::Migration[4.2]"
+ super
+ end
+ end
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/model_schema.rb b/activerecord/lib/active_record/model_schema.rb
index e3f304b0af..a6a68f3d4b 100644
--- a/activerecord/lib/active_record/model_schema.rb
+++ b/activerecord/lib/active_record/model_schema.rb
@@ -275,7 +275,7 @@ module ActiveRecord
# when just after creating a table you want to populate it with some default
# values, eg:
#
- # class CreateJobLevels < ActiveRecord::Migration
+ # class CreateJobLevels < ActiveRecord::Migration[5.0]
# def up
# create_table :job_levels do |t|
# t.integer :id
@@ -385,7 +385,7 @@ module ActiveRecord
If you'd like the new behavior today, you can add this line:
- attribute :#{column.name}, :rails_5_1_point#{array_arguments}
+ attribute :#{column.name}, :point#{array_arguments}
WARNING
end
end
diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb
index 94316d5249..522c35252f 100644
--- a/activerecord/lib/active_record/persistence.rb
+++ b/activerecord/lib/active_record/persistence.rb
@@ -215,7 +215,7 @@ module ActiveRecord
became.instance_variable_set("@changed_attributes", attributes_changed_by_setter)
became.instance_variable_set("@new_record", new_record?)
became.instance_variable_set("@destroyed", destroyed?)
- became.instance_variable_set("@errors", errors)
+ became.errors.copy!(errors)
became
end
@@ -298,6 +298,7 @@ module ActiveRecord
# * \Validations are skipped.
# * \Callbacks are skipped.
# * +updated_at+/+updated_on+ are not updated.
+ # * However, attributes are serialized with the same rules as ActiveRecord::Relation#update_all
#
# This method raises an ActiveRecord::ActiveRecordError when called on new
# objects, or when at least one of the attributes is marked as readonly.
@@ -358,6 +359,14 @@ module ActiveRecord
# if the predicate returns +true+ the attribute will become +false+. This
# method toggles directly the underlying value without calling any setter.
# Returns +self+.
+ #
+ # Example:
+ #
+ # user = User.first
+ # user.banned? # => false
+ # user.toggle(:banned)
+ # user.banned? # => true
+ #
def toggle(attribute)
self[attribute] = !public_send("#{attribute}?")
self
@@ -558,5 +567,9 @@ module ActiveRecord
ensure
@_association_destroy_exception = nil
end
+
+ def belongs_to_touch_method
+ :touch
+ end
end
end
diff --git a/activerecord/lib/active_record/railtie.rb b/activerecord/lib/active_record/railtie.rb
index 2744673c12..f5e69ec4fb 100644
--- a/activerecord/lib/active_record/railtie.rb
+++ b/activerecord/lib/active_record/railtie.rb
@@ -134,8 +134,8 @@ Oops - You have a database configured, but it doesn't exist yet!
Here's how to get started:
1. Configure your database in config/database.yml.
- 2. Run `bin/rake db:create` to create the database.
- 3. Run `bin/rake db:setup` to load your database schema.
+ 2. Run `bin/rails db:create` to create the database.
+ 3. Run `bin/rails db:setup` to load your database schema.
end_warning
raise
end
diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake
index 5b1ea16f0b..9b59ee995a 100644
--- a/activerecord/lib/active_record/railties/databases.rake
+++ b/activerecord/lib/active_record/railties/databases.rake
@@ -169,7 +169,7 @@ db_namespace = namespace :db do
pending_migrations.each do |pending_migration|
puts ' %4d %s' % [pending_migration.version, pending_migration.name]
end
- abort %{Run `rake db:migrate` to update your database then try again.}
+ abort %{Run `rails db:migrate` to update your database then try again.}
end
end
diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb
index 5b9d45d871..a549b28f16 100644
--- a/activerecord/lib/active_record/reflection.rb
+++ b/activerecord/lib/active_record/reflection.rb
@@ -371,7 +371,7 @@ module ActiveRecord
end
def foreign_key
- @foreign_key ||= options[:foreign_key] || derive_foreign_key
+ @foreign_key ||= options[:foreign_key] || derive_foreign_key.freeze
end
def association_foreign_key
diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb
index f100476374..2cf19c76c5 100644
--- a/activerecord/lib/active_record/relation.rb
+++ b/activerecord/lib/active_record/relation.rb
@@ -347,9 +347,8 @@ module ActiveRecord
# 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
- # Active Record's type-casting behavior. It should receive only values that can be passed as-is to the SQL
- # database.
+ # trigger Active Record callbacks or validations. However, values passed to #update_all will still go through
+ # Active Record's normal type casting and serialization.
#
# ==== Parameters
#
diff --git a/activerecord/lib/active_record/relation/delegation.rb b/activerecord/lib/active_record/relation/delegation.rb
index 27de313d05..e4e5d63006 100644
--- a/activerecord/lib/active_record/relation/delegation.rb
+++ b/activerecord/lib/active_record/relation/delegation.rb
@@ -36,13 +36,8 @@ module ActiveRecord
# may vary depending on the klass of a relation, so we create a subclass of Relation
# for each different klass, and the delegations are compiled into that subclass only.
- BLACKLISTED_ARRAY_METHODS = [
- :compact!, :flatten!, :reject!, :reverse!, :rotate!, :map!,
- :shuffle!, :slice!, :sort!, :sort_by!, :delete_if,
- :keep_if, :pop, :shift, :delete_at, :select!
- ].to_set # :nodoc:
-
- delegate :to_xml, :to_yaml, :length, :collect, :map, :each, :all?, :include?, :to_ary, :join, to: :to_a
+ delegate :to_xml, :to_yaml, :length, :collect, :map, :each, :all?, :include?, :to_ary, :join,
+ :[], :&, :|, :+, :-, :sample, :shuffle, :reverse, :compact, to: :to_a
delegate :table_name, :quoted_table_name, :primary_key, :quoted_primary_key,
:connection, :columns_hash, :to => :klass
@@ -114,21 +109,14 @@ module ActiveRecord
def respond_to?(method, include_private = false)
super || @klass.respond_to?(method, include_private) ||
- array_delegable?(method) ||
arel.respond_to?(method, include_private)
end
protected
- def array_delegable?(method)
- Array.method_defined?(method) && BLACKLISTED_ARRAY_METHODS.exclude?(method)
- end
-
def method_missing(method, *args, &block)
if @klass.respond_to?(method)
scoping { @klass.public_send(method, *args, &block) }
- elsif array_delegable?(method)
- to_a.public_send(method, *args, &block)
elsif arel.respond_to?(method)
arel.public_send(method, *args, &block)
else
diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb
index 435cef901b..19244bcf95 100644
--- a/activerecord/lib/active_record/relation/finder_methods.rb
+++ b/activerecord/lib/active_record/relation/finder_methods.rb
@@ -442,6 +442,8 @@ module ActiveRecord
end
def find_some(ids)
+ return find_some_ordered(ids) unless order_values.present?
+
result = where(primary_key => ids).to_a
expected_size =
@@ -463,6 +465,21 @@ module ActiveRecord
end
end
+ def find_some_ordered(ids)
+ ids = ids.slice(offset_value || 0, limit_value || ids.size) || []
+
+ result = except(:limit, :offset).where(primary_key => ids).to_a
+
+ if result.size == ids.size
+ pk_type = @klass.type_for_attribute(primary_key)
+
+ records_by_id = result.index_by(&:id)
+ ids.map { |id| records_by_id.fetch(pk_type.cast(id)) }
+ else
+ raise_record_not_found_exception!(ids, result.size, ids.size)
+ end
+ end
+
def find_take
if loaded?
@records.first
diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb
index 2dc52982c9..983bf019bc 100644
--- a/activerecord/lib/active_record/relation/query_methods.rb
+++ b/activerecord/lib/active_record/relation/query_methods.rb
@@ -3,6 +3,7 @@ require "active_record/relation/query_attribute"
require "active_record/relation/where_clause"
require "active_record/relation/where_clause_factory"
require 'active_model/forbidden_attributes_protection'
+require 'active_support/core_ext/string/filters'
module ActiveRecord
module QueryMethods
@@ -13,6 +14,8 @@ module ActiveRecord
# WhereChain objects act as placeholder for queries in which #where does not have any parameter.
# In this case, #where must be chained with #not to return a new relation.
class WhereChain
+ include ActiveModel::ForbiddenAttributesProtection
+
def initialize(scope)
@scope = scope
end
@@ -41,6 +44,8 @@ module ActiveRecord
# User.where.not(name: "Jon", role: "admin")
# # SELECT * FROM users WHERE name != 'Jon' AND role != 'admin'
def not(opts, *rest)
+ opts = sanitize_forbidden_attributes(opts)
+
where_clause = @scope.send(:where_clause_factory).build(opts, rest)
@scope.references!(PredicateBuilder.references(opts)) if Hash === opts
@@ -93,7 +98,22 @@ module ActiveRecord
end
def bound_attributes
- from_clause.binds + arel.bind_values + where_clause.binds + having_clause.binds
+ result = from_clause.binds + arel.bind_values + where_clause.binds + having_clause.binds
+ if limit_value && !string_containing_comma?(limit_value)
+ result << Attribute.with_cast_value(
+ "LIMIT".freeze,
+ connection.sanitize_limit(limit_value),
+ Type::Value.new,
+ )
+ end
+ if offset_value
+ result << Attribute.with_cast_value(
+ "OFFSET".freeze,
+ offset_value.to_i,
+ Type::Value.new,
+ )
+ end
+ result
end
def create_with_value # :nodoc:
@@ -407,10 +427,30 @@ module ActiveRecord
self
end
- # Performs a joins on +args+:
+ # Performs a joins on +args+. The given symbol(s) should match the name of
+ # the association(s).
#
# User.joins(:posts)
- # # SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
+ # # SELECT "users".*
+ # # FROM "users"
+ # # INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
+ #
+ # Multiple joins:
+ #
+ # User.joins(:posts, :account)
+ # # SELECT "users".*
+ # # FROM "users"
+ # # INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
+ # # INNER JOIN "accounts" ON "accounts"."id" = "users"."account_id"
+ #
+ # Nested joins:
+ #
+ # User.joins(posts: [:comments])
+ # # SELECT "users".*
+ # # FROM "users"
+ # # INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
+ # # INNER JOIN "comments" "comments_posts"
+ # # ON "comments_posts"."post_id" = "posts"."id"
#
# You can use strings in order to customize your joins:
#
@@ -653,6 +693,13 @@ module ActiveRecord
end
def limit!(value) # :nodoc:
+ if string_containing_comma?(value)
+ # Remove `string_containing_comma?` when removing this deprecation
+ ActiveSupport::Deprecation.warn(<<-WARNING.squish)
+ Passing a string to limit in the form "1,2" is deprecated and will be
+ removed in Rails 5.1. Please call `offset` explicitly instead.
+ WARNING
+ end
self.limit_value = value
self
end
@@ -903,8 +950,14 @@ module ActiveRecord
arel.where(where_clause.ast) unless where_clause.empty?
arel.having(having_clause.ast) unless having_clause.empty?
- arel.take(connection.sanitize_limit(limit_value)) if limit_value
- arel.skip(offset_value.to_i) if offset_value
+ if limit_value
+ if string_containing_comma?(limit_value)
+ arel.take(connection.sanitize_limit(limit_value))
+ else
+ arel.take(Arel::Nodes::BindParam.new)
+ end
+ end
+ arel.skip(Arel::Nodes::BindParam.new) if offset_value
arel.group(*arel_columns(group_values.uniq.reject(&:blank?))) unless group_values.empty?
build_order(arel)
@@ -1153,5 +1206,9 @@ module ActiveRecord
def new_from_clause
Relation::FromClause.empty
end
+
+ def string_containing_comma?(value)
+ ::String === value && value.include?(",")
+ end
end
end
diff --git a/activerecord/lib/active_record/relation/spawn_methods.rb b/activerecord/lib/active_record/relation/spawn_methods.rb
index 5c3318651a..67d7f83cb4 100644
--- a/activerecord/lib/active_record/relation/spawn_methods.rb
+++ b/activerecord/lib/active_record/relation/spawn_methods.rb
@@ -12,6 +12,7 @@ module ActiveRecord
# Merges in the conditions from <tt>other</tt>, if <tt>other</tt> is an ActiveRecord::Relation.
# Returns an array representing the intersection of the resulting records with <tt>other</tt>, if <tt>other</tt> is an array.
+ #
# Post.where(published: true).joins(:comments).merge( Comment.where(spam: false) )
# # Performs a single join query with both where conditions.
#
@@ -37,11 +38,14 @@ module ActiveRecord
end
def merge!(other) # :nodoc:
- if !other.is_a?(Relation) && other.respond_to?(:to_proc)
+ if other.is_a?(Hash)
+ Relation::HashMerger.new(self, other).merge
+ elsif other.is_a?(Relation)
+ Relation::Merger.new(self, other).merge
+ elsif other.respond_to?(:to_proc)
instance_exec(&other)
else
- klass = other.is_a?(Hash) ? Relation::HashMerger : Relation::Merger
- klass.new(self, other).merge
+ raise ArgumentError, "#{other.inspect} is not an ActiveRecord::Relation"
end
end
diff --git a/activerecord/lib/active_record/sanitization.rb b/activerecord/lib/active_record/sanitization.rb
index 0c15f45db9..4e89ba4dd1 100644
--- a/activerecord/lib/active_record/sanitization.rb
+++ b/activerecord/lib/active_record/sanitization.rb
@@ -18,6 +18,9 @@ module ActiveRecord
# sanitize_sql_for_conditions(["name=? and group_id=?", "foo'bar", 4])
# # => "name='foo''bar' and group_id=4"
#
+ # sanitize_sql_for_conditions(["name=:name and group_id=:group_id", name: "foo'bar", group_id: 4])
+ # # => "name='foo''bar' and group_id='4'"
+ #
# sanitize_sql_for_conditions(["name='%s' and group_id='%s'", "foo'bar", 4])
# # => "name='foo''bar' and group_id='4'"
#
@@ -40,6 +43,9 @@ module ActiveRecord
# sanitize_sql_for_assignment(["name=? and group_id=?", nil, 4])
# # => "name=NULL and group_id=4"
#
+ # sanitize_sql_for_assignment(["name=:name and group_id=:group_id", name: nil, group_id: 4])
+ # # => "name=NULL and group_id=4"
+ #
# Post.send(:sanitize_sql_for_assignment, { name: nil, group_id: 4 })
# # => "`posts`.`name` = NULL, `posts`.`group_id` = 4"
#
@@ -140,6 +146,9 @@ module ActiveRecord
# sanitize_sql_array(["name=? and group_id=?", "foo'bar", 4])
# # => "name='foo''bar' and group_id=4"
#
+ # sanitize_sql_array(["name=:name and group_id=:group_id", name: "foo'bar", group_id: 4])
+ # # => "name='foo''bar' and group_id=4"
+ #
# sanitize_sql_array(["name='%s' and group_id='%s'", "foo'bar", 4])
# # => "name='foo''bar' and group_id='4'"
def sanitize_sql_array(ary)
diff --git a/activerecord/lib/active_record/schema.rb b/activerecord/lib/active_record/schema.rb
index 31dd584538..fdf9965a82 100644
--- a/activerecord/lib/active_record/schema.rb
+++ b/activerecord/lib/active_record/schema.rb
@@ -27,7 +27,7 @@ module ActiveRecord
#
# ActiveRecord::Schema is only supported by database adapters that also
# support migrations, the two features being very similar.
- class Schema < Migration
+ class Schema < Migration::Current
# Eval the given block. All methods available to the current connection
# adapter are available within the block, so you can easily use the
# database definition DSL to build up your schema (
diff --git a/activerecord/lib/active_record/tasks/database_tasks.rb b/activerecord/lib/active_record/tasks/database_tasks.rb
index c0c29a618c..b6fba0cf79 100644
--- a/activerecord/lib/active_record/tasks/database_tasks.rb
+++ b/activerecord/lib/active_record/tasks/database_tasks.rb
@@ -232,7 +232,7 @@ module ActiveRecord
def check_schema_file(filename)
unless File.exist?(filename)
- message = %{#{filename} doesn't exist yet. Run `rake db:migrate` to create it, then try again.}
+ message = %{#{filename} doesn't exist yet. Run `rails db:migrate` to create it, then try again.}
message << %{ If you do not intend to use a database, you should instead alter #{Rails.root}/config/application.rb to limit the frameworks that will be loaded.} if defined?(::Rails)
Kernel.abort message
end
diff --git a/activerecord/lib/active_record/tasks/mysql_database_tasks.rb b/activerecord/lib/active_record/tasks/mysql_database_tasks.rb
index 100df9c6c6..7a49322e06 100644
--- a/activerecord/lib/active_record/tasks/mysql_database_tasks.rb
+++ b/activerecord/lib/active_record/tasks/mysql_database_tasks.rb
@@ -94,8 +94,6 @@ module ActiveRecord
ArJdbcMySQL::Error
elsif defined?(Mysql2)
Mysql2::Error
- elsif defined?(Mysql)
- Mysql::Error
else
StandardError
end
diff --git a/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb b/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb
index cd7d949239..8b4874044c 100644
--- a/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb
+++ b/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb
@@ -56,9 +56,9 @@ module ActiveRecord
args = ['-s', '-x', '-O', '-f', filename]
unless search_path.blank?
- args << search_path.split(',').map do |part|
+ args += search_path.split(',').map do |part|
"--schema=#{part.strip}"
- end.join(' ')
+ end
end
args << configuration['database']
run_cmd('pg_dump', args, 'dumping')
diff --git a/activerecord/lib/active_record/touch_later.rb b/activerecord/lib/active_record/touch_later.rb
index 4352a0ffea..9a80a63e28 100644
--- a/activerecord/lib/active_record/touch_later.rb
+++ b/activerecord/lib/active_record/touch_later.rb
@@ -16,6 +16,13 @@ module ActiveRecord
surreptitiously_touch @_defer_touch_attrs
self.class.connection.add_transaction_record self
+
+ # touch the parents as we are not calling the after_save callbacks
+ self.class.reflect_on_all_associations(:belongs_to).each do |r|
+ if touch = r.options[:touch]
+ ActiveRecord::Associations::Builder::BelongsTo.touch_record(self, r.foreign_key, r.name, touch, :touch_later)
+ end
+ end
end
def touch(*names, time: nil) # :nodoc:
@@ -26,6 +33,7 @@ module ActiveRecord
end
private
+
def surreptitiously_touch(attrs)
attrs.each { |attr| write_attribute attr, @_touch_time }
clear_attribute_changes attrs
@@ -33,9 +41,8 @@ module ActiveRecord
def touch_deferred_attributes
if has_defer_touch_attrs? && persisted?
- @_touching_delayed_records = true
touch(*@_defer_touch_attrs, time: @_touch_time)
- @_touching_delayed_records, @_defer_touch_attrs, @_touch_time = nil, nil, nil
+ @_defer_touch_attrs, @_touch_time = nil, nil
end
end
@@ -43,8 +50,9 @@ module ActiveRecord
defined?(@_defer_touch_attrs) && @_defer_touch_attrs.present?
end
- def touching_delayed_records?
- defined?(@_touching_delayed_records) && @_touching_delayed_records
+ def belongs_to_touch_method
+ :touch_later
end
+
end
end
diff --git a/activerecord/lib/active_record/transactions.rb b/activerecord/lib/active_record/transactions.rb
index 8de82feae3..38ab1f3fc6 100644
--- a/activerecord/lib/active_record/transactions.rb
+++ b/activerecord/lib/active_record/transactions.rb
@@ -233,6 +233,24 @@ module ActiveRecord
set_callback(:commit, :after, *args, &block)
end
+ # Shortcut for +after_commit :hook, on: :create+.
+ def after_create_commit(*args, &block)
+ set_options_for_callbacks!(args, on: :create)
+ set_callback(:commit, :after, *args, &block)
+ end
+
+ # Shortcut for +after_commit :hook, on: :update+.
+ def after_update_commit(*args, &block)
+ set_options_for_callbacks!(args, on: :update)
+ set_callback(:commit, :after, *args, &block)
+ end
+
+ # Shortcut for +after_commit :hook, on: :destroy+.
+ def after_destroy_commit(*args, &block)
+ set_options_for_callbacks!(args, on: :destroy)
+ set_callback(:commit, :after, *args, &block)
+ end
+
# This callback is called after a create, update, or destroy are rolled back.
#
# Please check the documentation of #after_commit for options.
@@ -268,9 +286,11 @@ module ActiveRecord
private
- def set_options_for_callbacks!(args)
- options = args.last
- if options.is_a?(Hash) && options[:on]
+ def set_options_for_callbacks!(args, enforced_options = {})
+ options = args.extract_options!.merge!(enforced_options)
+ args << options
+
+ if options[:on]
fire_on = Array(options[:on])
assert_valid_transaction_action(fire_on)
options[:if] = Array(options[:if])
diff --git a/activerecord/lib/active_record/validations/uniqueness.rb b/activerecord/lib/active_record/validations/uniqueness.rb
index aa2794f120..edc1325b25 100644
--- a/activerecord/lib/active_record/validations/uniqueness.rb
+++ b/activerecord/lib/active_record/validations/uniqueness.rb
@@ -231,7 +231,6 @@ module ActiveRecord
#
# The following bundled adapters throw the ActiveRecord::RecordNotUnique exception:
#
- # * ActiveRecord::ConnectionAdapters::MysqlAdapter.
# * ActiveRecord::ConnectionAdapters::Mysql2Adapter.
# * ActiveRecord::ConnectionAdapters::SQLite3Adapter.
# * ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.
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 fadab2a1e6..5f7201cfe1 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
@@ -1,4 +1,4 @@
-class <%= migration_class_name %> < ActiveRecord::Migration
+class <%= migration_class_name %> < ActiveRecord::Migration[<%= ActiveRecord::Migration.current_version %>]
def change
create_table :<%= table_name %><%= primary_key_type %> do |t|
<% attributes.each do |attribute| -%>
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 23a377db6a..107f107dc4 100644
--- a/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb
+++ b/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb
@@ -1,4 +1,4 @@
-class <%= migration_class_name %> < ActiveRecord::Migration
+class <%= migration_class_name %> < ActiveRecord::Migration[<%= ActiveRecord::Migration.current_version %>]
<%- if migration_action == 'add' -%>
def change
<% attributes.each do |attribute| -%>
diff --git a/activerecord/lib/rails/generators/active_record/model/model_generator.rb b/activerecord/lib/rails/generators/active_record/model/model_generator.rb
index 395951ac9d..15aecf28ca 100644
--- a/activerecord/lib/rails/generators/active_record/model/model_generator.rb
+++ b/activerecord/lib/rails/generators/active_record/model/model_generator.rb
@@ -29,23 +29,30 @@ module ActiveRecord
template 'module.rb', File.join('app/models', "#{class_path.join('/')}.rb") if behavior == :invoke
end
- def attributes_with_index
- attributes.select { |a| !a.reference? && a.has_index? }
- end
-
- def accessible_attributes
- attributes.reject(&:reference?)
- end
-
hook_for :test_framework
protected
+ def attributes_with_index
+ attributes.select { |a| !a.reference? && a.has_index? }
+ end
+
# Used by the migration template to determine the parent name of the model
def parent_class_name
- options[:parent] || "ActiveRecord::Base"
+ options[:parent] || determine_default_parent_class
end
+ def determine_default_parent_class
+ application_record = nil
+
+ in_root { application_record = File.exist?('app/models/application_record.rb') }
+
+ if application_record
+ "ApplicationRecord"
+ else
+ "ActiveRecord::Base"
+ end
+ end
end
end
end
diff --git a/activerecord/test/cases/adapter_test.rb b/activerecord/test/cases/adapter_test.rb
index abe1ea7c90..0ee147cdba 100644
--- a/activerecord/test/cases/adapter_test.rb
+++ b/activerecord/test/cases/adapter_test.rb
@@ -85,7 +85,7 @@ module ActiveRecord
end
end
- if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ if current_adapter?(:Mysql2Adapter)
def test_charset
assert_not_nil @connection.charset
assert_not_equal 'character_set_database', @connection.charset
@@ -254,7 +254,7 @@ module ActiveRecord
end
end
- if current_adapter?(:MysqlAdapter, :Mysql2Adapter, :SQLite3Adapter)
+ if current_adapter?(:Mysql2Adapter, :SQLite3Adapter)
def test_tables_returning_both_tables_and_views_is_deprecated
assert_deprecated { @connection.tables }
end
diff --git a/activerecord/test/cases/adapters/mysql/active_schema_test.rb b/activerecord/test/cases/adapters/mysql/active_schema_test.rb
deleted file mode 100644
index 0b5c9e1798..0000000000
--- a/activerecord/test/cases/adapters/mysql/active_schema_test.rb
+++ /dev/null
@@ -1,190 +0,0 @@
-require "cases/helper"
-require 'support/connection_helper'
-
-class MysqlActiveSchemaTest < ActiveRecord::MysqlTestCase
- include ConnectionHelper
-
- def setup
- ActiveRecord::Base.connection.singleton_class.class_eval do
- alias_method :execute_without_stub, :execute
- def execute(sql, name = nil) return sql end
- end
- end
-
- teardown do
- reset_connection
- end
-
- def test_add_index
- # add_index calls table_exists? and index_name_exists? which can't work since execute is stubbed
- def (ActiveRecord::Base.connection).table_exists?(*); true; end
- def (ActiveRecord::Base.connection).index_name_exists?(*); false; end
-
- expected = "CREATE INDEX `index_people_on_last_name` ON `people` (`last_name`) "
- assert_equal expected, add_index(:people, :last_name, :length => nil)
-
- expected = "CREATE INDEX `index_people_on_last_name` ON `people` (`last_name`(10)) "
- assert_equal expected, add_index(:people, :last_name, :length => 10)
-
- expected = "CREATE INDEX `index_people_on_last_name_and_first_name` ON `people` (`last_name`(15), `first_name`(15)) "
- assert_equal expected, add_index(:people, [:last_name, :first_name], :length => 15)
-
- expected = "CREATE INDEX `index_people_on_last_name_and_first_name` ON `people` (`last_name`(15), `first_name`) "
- assert_equal expected, add_index(:people, [:last_name, :first_name], :length => {:last_name => 15})
-
- expected = "CREATE INDEX `index_people_on_last_name_and_first_name` ON `people` (`last_name`(15), `first_name`(10)) "
- assert_equal expected, add_index(:people, [:last_name, :first_name], :length => {:last_name => 15, :first_name => 10})
-
- %w(SPATIAL FULLTEXT UNIQUE).each do |type|
- expected = "CREATE #{type} INDEX `index_people_on_last_name` ON `people` (`last_name`) "
- assert_equal expected, add_index(:people, :last_name, :type => type)
- end
-
- %w(btree hash).each do |using|
- expected = "CREATE INDEX `index_people_on_last_name` USING #{using} ON `people` (`last_name`) "
- assert_equal expected, add_index(:people, :last_name, :using => using)
- end
-
- expected = "CREATE INDEX `index_people_on_last_name` USING btree ON `people` (`last_name`(10)) "
- assert_equal expected, add_index(:people, :last_name, :length => 10, :using => :btree)
-
- expected = "CREATE INDEX `index_people_on_last_name` USING btree ON `people` (`last_name`(10)) ALGORITHM = COPY"
- assert_equal expected, add_index(:people, :last_name, :length => 10, using: :btree, algorithm: :copy)
-
- assert_raise ArgumentError do
- add_index(:people, :last_name, algorithm: :coyp)
- end
-
- expected = "CREATE INDEX `index_people_on_last_name_and_first_name` USING btree ON `people` (`last_name`(15), `first_name`(15)) "
- assert_equal expected, add_index(:people, [:last_name, :first_name], :length => 15, :using => :btree)
- end
-
- def test_index_in_create
- def (ActiveRecord::Base.connection).table_exists?(*); false; end
-
- %w(SPATIAL FULLTEXT UNIQUE).each do |type|
- expected = "CREATE TABLE `people` (#{type} INDEX `index_people_on_last_name` (`last_name`) ) ENGINE=InnoDB"
- actual = ActiveRecord::Base.connection.create_table(:people, id: false) do |t|
- t.index :last_name, type: type
- end
- assert_equal expected, actual
- end
-
- expected = "CREATE TABLE `people` ( INDEX `index_people_on_last_name` USING btree (`last_name`(10)) ) ENGINE=InnoDB"
- actual = ActiveRecord::Base.connection.create_table(:people, id: false) do |t|
- t.index :last_name, length: 10, using: :btree
- end
- assert_equal expected, actual
- end
-
- def test_index_in_bulk_change
- def (ActiveRecord::Base.connection).table_exists?(*); true; end
- def (ActiveRecord::Base.connection).index_name_exists?(*); false; end
-
- %w(SPATIAL FULLTEXT UNIQUE).each do |type|
- expected = "ALTER TABLE `people` ADD #{type} INDEX `index_people_on_last_name` (`last_name`)"
- actual = ActiveRecord::Base.connection.change_table(:people, bulk: true) do |t|
- t.index :last_name, type: type
- end
- assert_equal expected, actual
- end
-
- expected = "ALTER TABLE `peaple` ADD INDEX `index_peaple_on_last_name` USING btree (`last_name`(10)), ALGORITHM = COPY"
- actual = ActiveRecord::Base.connection.change_table(:peaple, bulk: true) do |t|
- t.index :last_name, length: 10, using: :btree, algorithm: :copy
- end
- assert_equal expected, actual
- end
-
- def test_drop_table
- assert_equal "DROP TABLE `people`", drop_table(:people)
- end
-
- def test_create_mysql_database_with_encoding
- assert_equal "CREATE DATABASE `matt` DEFAULT CHARACTER SET `utf8`", create_database(:matt)
- assert_equal "CREATE DATABASE `aimonetti` DEFAULT CHARACTER SET `latin1`", create_database(:aimonetti, {:charset => 'latin1'})
- assert_equal "CREATE DATABASE `matt_aimonetti` DEFAULT CHARACTER SET `big5` COLLATE `big5_chinese_ci`", create_database(:matt_aimonetti, {:charset => :big5, :collation => :big5_chinese_ci})
- end
-
- def test_recreate_mysql_database_with_encoding
- create_database(:luca, {:charset => 'latin1'})
- assert_equal "CREATE DATABASE `luca` DEFAULT CHARACTER SET `latin1`", recreate_database(:luca, {:charset => 'latin1'})
- end
-
- def test_add_column
- assert_equal "ALTER TABLE `people` ADD `last_name` varchar(255)", add_column(:people, :last_name, :string)
- end
-
- def test_add_column_with_limit
- assert_equal "ALTER TABLE `people` ADD `key` varchar(32)", add_column(:people, :key, :string, :limit => 32)
- end
-
- def test_drop_table_with_specific_database
- assert_equal "DROP TABLE `otherdb`.`people`", drop_table('otherdb.people')
- end
-
- def test_add_timestamps
- with_real_execute do
- begin
- ActiveRecord::Base.connection.create_table :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
- ActiveRecord::Base.connection.drop_table :delete_me rescue nil
- end
- end
- end
-
- def test_remove_timestamps
- with_real_execute do
- begin
- ActiveRecord::Base.connection.create_table :delete_me do |t|
- t.timestamps null: true
- end
- ActiveRecord::Base.connection.remove_timestamps :delete_me, { null: true }
- assert !column_present?('delete_me', 'updated_at', 'datetime')
- assert !column_present?('delete_me', 'created_at', 'datetime')
- ensure
- ActiveRecord::Base.connection.drop_table :delete_me rescue nil
- end
- end
- end
-
- def test_indexes_in_create
- ActiveRecord::Base.connection.stubs(:table_exists?).with(:temp).returns(false)
- ActiveRecord::Base.connection.stubs(:index_name_exists?).with(:index_temp_on_zip).returns(false)
-
- expected = "CREATE TEMPORARY TABLE `temp` ( INDEX `index_temp_on_zip` (`zip`) ) ENGINE=InnoDB AS SELECT id, name, zip FROM a_really_complicated_query"
- actual = ActiveRecord::Base.connection.create_table(:temp, temporary: true, as: "SELECT id, name, zip FROM a_really_complicated_query") do |t|
- t.index :zip
- end
-
- assert_equal expected, actual
- end
-
- private
- def with_real_execute
- ActiveRecord::Base.connection.singleton_class.class_eval do
- alias_method :execute_with_stub, :execute
- remove_method :execute
- alias_method :execute, :execute_without_stub
- end
-
- yield
- ensure
- ActiveRecord::Base.connection.singleton_class.class_eval do
- remove_method :execute
- alias_method :execute, :execute_with_stub
- end
- end
-
- def method_missing(method_symbol, *arguments)
- ActiveRecord::Base.connection.send(method_symbol, *arguments)
- end
-
- def column_present?(table_name, column_name, type)
- results = ActiveRecord::Base.connection.select_all("SHOW FIELDS FROM #{table_name} LIKE '#{column_name}'")
- results.first && results.first['Type'] == type
- end
-end
diff --git a/activerecord/test/cases/adapters/mysql/case_sensitivity_test.rb b/activerecord/test/cases/adapters/mysql/case_sensitivity_test.rb
deleted file mode 100644
index 98d44315dd..0000000000
--- a/activerecord/test/cases/adapters/mysql/case_sensitivity_test.rb
+++ /dev/null
@@ -1,54 +0,0 @@
-require "cases/helper"
-
-class MysqlCaseSensitivityTest < ActiveRecord::MysqlTestCase
- class CollationTest < ActiveRecord::Base
- end
-
- repair_validations(CollationTest)
-
- def test_columns_include_collation_different_from_table
- assert_equal 'utf8_bin', CollationTest.columns_hash['string_cs_column'].collation
- assert_equal 'utf8_general_ci', CollationTest.columns_hash['string_ci_column'].collation
- end
-
- def test_case_sensitive
- assert !CollationTest.columns_hash['string_ci_column'].case_sensitive?
- assert CollationTest.columns_hash['string_cs_column'].case_sensitive?
- end
-
- def test_case_insensitive_comparison_for_ci_column
- CollationTest.validates_uniqueness_of(:string_ci_column, :case_sensitive => false)
- CollationTest.create!(:string_ci_column => 'A')
- invalid = CollationTest.new(:string_ci_column => 'a')
- queries = assert_sql { invalid.save }
- ci_uniqueness_query = queries.detect { |q| q.match(/string_ci_column/) }
- assert_no_match(/lower/i, ci_uniqueness_query)
- end
-
- def test_case_insensitive_comparison_for_cs_column
- CollationTest.validates_uniqueness_of(:string_cs_column, :case_sensitive => false)
- CollationTest.create!(:string_cs_column => 'A')
- invalid = CollationTest.new(:string_cs_column => 'a')
- queries = assert_sql { invalid.save }
- cs_uniqueness_query = queries.detect { |q| q.match(/string_cs_column/) }
- assert_match(/lower/i, cs_uniqueness_query)
- end
-
- def test_case_sensitive_comparison_for_ci_column
- CollationTest.validates_uniqueness_of(:string_ci_column, :case_sensitive => true)
- CollationTest.create!(:string_ci_column => 'A')
- invalid = CollationTest.new(:string_ci_column => 'A')
- queries = assert_sql { invalid.save }
- ci_uniqueness_query = queries.detect { |q| q.match(/string_ci_column/) }
- assert_match(/binary/i, ci_uniqueness_query)
- end
-
- def test_case_sensitive_comparison_for_cs_column
- CollationTest.validates_uniqueness_of(:string_cs_column, :case_sensitive => true)
- CollationTest.create!(:string_cs_column => 'A')
- invalid = CollationTest.new(:string_cs_column => 'A')
- queries = assert_sql { invalid.save }
- cs_uniqueness_query = queries.detect { |q| q.match(/string_cs_column/) }
- assert_no_match(/binary/i, cs_uniqueness_query)
- end
-end
diff --git a/activerecord/test/cases/adapters/mysql/charset_collation_test.rb b/activerecord/test/cases/adapters/mysql/charset_collation_test.rb
deleted file mode 100644
index f2117a97e6..0000000000
--- a/activerecord/test/cases/adapters/mysql/charset_collation_test.rb
+++ /dev/null
@@ -1,54 +0,0 @@
-require "cases/helper"
-require 'support/schema_dumping_helper'
-
-class MysqlCharsetCollationTest < ActiveRecord::MysqlTestCase
- include SchemaDumpingHelper
- self.use_transactional_tests = false
-
- setup do
- @connection = ActiveRecord::Base.connection
- @connection.create_table :charset_collations, force: true do |t|
- t.string :string_ascii_bin, charset: 'ascii', collation: 'ascii_bin'
- t.text :text_ucs2_unicode_ci, charset: 'ucs2', collation: 'ucs2_unicode_ci'
- end
- end
-
- teardown do
- @connection.drop_table :charset_collations, if_exists: true
- end
-
- test "string column with charset and collation" do
- column = @connection.columns(:charset_collations).find { |c| c.name == 'string_ascii_bin' }
- assert_equal :string, column.type
- assert_equal 'ascii_bin', column.collation
- end
-
- test "text column with charset and collation" do
- column = @connection.columns(:charset_collations).find { |c| c.name == 'text_ucs2_unicode_ci' }
- assert_equal :text, column.type
- assert_equal 'ucs2_unicode_ci', column.collation
- end
-
- test "add column with charset and collation" do
- @connection.add_column :charset_collations, :title, :string, charset: 'utf8', collation: 'utf8_bin'
-
- column = @connection.columns(:charset_collations).find { |c| c.name == 'title' }
- assert_equal :string, column.type
- assert_equal 'utf8_bin', column.collation
- end
-
- test "change column with charset and collation" do
- @connection.add_column :charset_collations, :description, :string, charset: 'utf8', collation: 'utf8_unicode_ci'
- @connection.change_column :charset_collations, :description, :text, charset: 'utf8', collation: 'utf8_general_ci'
-
- column = @connection.columns(:charset_collations).find { |c| c.name == 'description' }
- assert_equal :text, column.type
- assert_equal 'utf8_general_ci', column.collation
- end
-
- test "schema dump includes collation" do
- output = dump_table_schema("charset_collations")
- assert_match %r{t.string\s+"string_ascii_bin",\s+limit: 255,\s+collation: "ascii_bin"$}, output
- assert_match %r{t.text\s+"text_ucs2_unicode_ci",\s+limit: 65535,\s+collation: "ucs2_unicode_ci"$}, output
- end
-end
diff --git a/activerecord/test/cases/adapters/mysql/connection_test.rb b/activerecord/test/cases/adapters/mysql/connection_test.rb
deleted file mode 100644
index 75653ee9af..0000000000
--- a/activerecord/test/cases/adapters/mysql/connection_test.rb
+++ /dev/null
@@ -1,210 +0,0 @@
-require "cases/helper"
-require 'support/connection_helper'
-require 'support/ddl_helper'
-
-class MysqlConnectionTest < ActiveRecord::MysqlTestCase
- include ConnectionHelper
- include DdlHelper
-
- class Klass < ActiveRecord::Base
- end
-
- def setup
- super
- @connection = ActiveRecord::Base.connection
- end
-
- def test_mysql_reconnect_attribute_after_connection_with_reconnect_true
- run_without_connection do |orig_connection|
- ActiveRecord::Base.establish_connection(orig_connection.merge({:reconnect => true}))
- assert ActiveRecord::Base.connection.raw_connection.reconnect
- end
- end
-
- unless ARTest.connection_config['arunit']['socket']
- def test_connect_with_url
- run_without_connection do
- ar_config = ARTest.connection_config['arunit']
-
- url = "mysql://#{ar_config["username"]}:#{ar_config["password"]}@localhost/#{ar_config["database"]}"
- Klass.establish_connection(url)
- assert_equal ar_config['database'], Klass.connection.current_database
- end
- end
- end
-
- def test_mysql_reconnect_attribute_after_connection_with_reconnect_false
- run_without_connection do |orig_connection|
- ActiveRecord::Base.establish_connection(orig_connection.merge({:reconnect => false}))
- assert !ActiveRecord::Base.connection.raw_connection.reconnect
- end
- end
-
- def test_no_automatic_reconnection_after_timeout
- assert @connection.active?
- @connection.update('set @@wait_timeout=1')
- sleep 2
- assert !@connection.active?
-
- # Repair all fixture connections so other tests won't break.
- @fixture_connections.each(&:verify!)
- end
-
- def test_successful_reconnection_after_timeout_with_manual_reconnect
- assert @connection.active?
- @connection.update('set @@wait_timeout=1')
- sleep 2
- @connection.reconnect!
- assert @connection.active?
- end
-
- def test_successful_reconnection_after_timeout_with_verify
- assert @connection.active?
- @connection.update('set @@wait_timeout=1')
- sleep 2
- @connection.verify!
- assert @connection.active?
- end
-
- def test_bind_value_substitute
- bind_param = @connection.substitute_at('foo')
- assert_equal Arel.sql('?'), bind_param.to_sql
- end
-
- def test_exec_no_binds
- with_example_table do
- result = @connection.exec_query('SELECT id, data FROM ex')
- assert_equal 0, result.rows.length
- assert_equal 2, result.columns.length
- assert_equal %w{ id data }, result.columns
-
- @connection.exec_query('INSERT INTO ex (id, data) VALUES (1, "foo")')
-
- # if there are no bind parameters, it will return a string (due to
- # the libmysql api)
- result = @connection.exec_query('SELECT id, data FROM ex')
- assert_equal 1, result.rows.length
- assert_equal 2, result.columns.length
-
- assert_equal [['1', 'foo']], result.rows
- end
- end
-
- def test_exec_with_binds
- with_example_table do
- @connection.exec_query('INSERT INTO ex (id, data) VALUES (1, "foo")')
- result = @connection.exec_query(
- 'SELECT id, data FROM ex WHERE id = ?', nil, [ActiveRecord::Relation::QueryAttribute.new("id", 1, ActiveRecord::Type::Value.new)])
-
- assert_equal 1, result.rows.length
- assert_equal 2, result.columns.length
-
- assert_equal [[1, 'foo']], result.rows
- end
- end
-
- def test_exec_typecasts_bind_vals
- with_example_table do
- @connection.exec_query('INSERT INTO ex (id, data) VALUES (1, "foo")')
- bind = ActiveRecord::Relation::QueryAttribute.new("id", "1-fuu", ActiveRecord::Type::Integer.new)
-
- result = @connection.exec_query(
- 'SELECT id, data FROM ex WHERE id = ?', nil, [bind])
-
- assert_equal 1, result.rows.length
- assert_equal 2, result.columns.length
-
- assert_equal [[1, 'foo']], result.rows
- end
- end
-
- def test_mysql_connection_collation_is_configured
- assert_equal 'utf8_unicode_ci', @connection.show_variable('collation_connection')
- assert_equal 'utf8_general_ci', ARUnit2Model.connection.show_variable('collation_connection')
- end
-
- def test_mysql_default_in_strict_mode
- result = @connection.exec_query "SELECT @@SESSION.sql_mode"
- assert_equal [["STRICT_ALL_TABLES"]], result.rows
- end
-
- def test_mysql_strict_mode_disabled
- run_without_connection do |orig_connection|
- ActiveRecord::Base.establish_connection(orig_connection.merge({:strict => false}))
- result = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.sql_mode"
- assert_equal [['']], result.rows
- end
- end
-
- def test_mysql_strict_mode_specified_default
- run_without_connection do |orig_connection|
- ActiveRecord::Base.establish_connection(orig_connection.merge({strict: :default}))
- global_sql_mode = ActiveRecord::Base.connection.exec_query "SELECT @@GLOBAL.sql_mode"
- session_sql_mode = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.sql_mode"
- assert_equal global_sql_mode.rows, session_sql_mode.rows
- end
- end
-
- def test_mysql_set_session_variable
- run_without_connection do |orig_connection|
- ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:default_week_format => 3}}))
- session_mode = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.DEFAULT_WEEK_FORMAT"
- assert_equal 3, session_mode.rows.first.first.to_i
- end
- end
-
- def test_mysql_sql_mode_variable_overrides_strict_mode
- run_without_connection do |orig_connection|
- ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { 'sql_mode' => 'ansi' }))
- result = ActiveRecord::Base.connection.exec_query 'SELECT @@SESSION.sql_mode'
- assert_not_equal [['STRICT_ALL_TABLES']], result.rows
- end
- end
-
- def test_mysql_set_session_variable_to_default
- run_without_connection do |orig_connection|
- ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:default_week_format => :default}}))
- global_mode = ActiveRecord::Base.connection.exec_query "SELECT @@GLOBAL.DEFAULT_WEEK_FORMAT"
- session_mode = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.DEFAULT_WEEK_FORMAT"
- assert_equal global_mode.rows, session_mode.rows
- end
- end
-
- def test_get_and_release_advisory_lock
- key = "test_key"
-
- got_lock = @connection.get_advisory_lock(key)
- assert got_lock, "get_advisory_lock should have returned true but it didn't"
-
- assert_equal test_lock_free(key), false,
- "expected the test advisory lock to be held but it wasn't"
-
- released_lock = @connection.release_advisory_lock(key)
- assert released_lock, "expected release_advisory_lock to return true but it didn't"
-
- assert test_lock_free(key), 'expected the test key to be available after releasing'
- end
-
- def test_release_non_existent_advisory_lock
- fake_key = "fake_key"
- released_non_existent_lock = @connection.release_advisory_lock(fake_key)
- assert_equal released_non_existent_lock, false,
- 'expected release_advisory_lock to return false when there was no lock to release'
- end
-
- protected
-
- def test_lock_free(key)
- @connection.select_value("SELECT IS_FREE_LOCK('#{key}');") == '1'
- end
-
- private
-
- def with_example_table(&block)
- definition ||= <<-SQL
- `id` int auto_increment PRIMARY KEY,
- `data` varchar(255)
- SQL
- super(@connection, 'ex', definition, &block)
- end
-end
diff --git a/activerecord/test/cases/adapters/mysql/consistency_test.rb b/activerecord/test/cases/adapters/mysql/consistency_test.rb
deleted file mode 100644
index 743f6436e4..0000000000
--- a/activerecord/test/cases/adapters/mysql/consistency_test.rb
+++ /dev/null
@@ -1,49 +0,0 @@
-require "cases/helper"
-
-class MysqlConsistencyTest < ActiveRecord::MysqlTestCase
- self.use_transactional_tests = false
-
- class Consistency < ActiveRecord::Base
- self.table_name = "mysql_consistency"
- end
-
- setup do
- @old_emulate_booleans = ActiveRecord::ConnectionAdapters::MysqlAdapter.emulate_booleans
- ActiveRecord::ConnectionAdapters::MysqlAdapter.emulate_booleans = false
-
- @connection = ActiveRecord::Base.connection
- @connection.clear_cache!
- @connection.create_table("mysql_consistency") do |t|
- t.boolean "a_bool"
- t.string "a_string"
- end
- Consistency.reset_column_information
- Consistency.create!
- end
-
- teardown do
- ActiveRecord::ConnectionAdapters::MysqlAdapter.emulate_booleans = @old_emulate_booleans
- @connection.drop_table "mysql_consistency"
- end
-
- test "boolean columns with random value type cast to 0 when emulate_booleans is false" do
- with_new = Consistency.new
- with_last = Consistency.last
- with_new.a_bool = 'wibble'
- with_last.a_bool = 'wibble'
-
- assert_equal 0, with_new.a_bool
- assert_equal 0, with_last.a_bool
- end
-
- test "string columns call #to_s" do
- with_new = Consistency.new
- with_last = Consistency.last
- thing = Object.new
- with_new.a_string = thing
- with_last.a_string = thing
-
- assert_equal thing.to_s, with_new.a_string
- assert_equal thing.to_s, with_last.a_string
- end
-end
diff --git a/activerecord/test/cases/adapters/mysql/enum_test.rb b/activerecord/test/cases/adapters/mysql/enum_test.rb
deleted file mode 100644
index ef8ee0a6e3..0000000000
--- a/activerecord/test/cases/adapters/mysql/enum_test.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-require "cases/helper"
-
-class MysqlEnumTest < ActiveRecord::MysqlTestCase
- class EnumTest < ActiveRecord::Base
- end
-
- def test_enum_limit
- assert_equal 6, EnumTest.columns.first.limit
- end
-end
diff --git a/activerecord/test/cases/adapters/mysql/explain_test.rb b/activerecord/test/cases/adapters/mysql/explain_test.rb
deleted file mode 100644
index c44c1e6648..0000000000
--- a/activerecord/test/cases/adapters/mysql/explain_test.rb
+++ /dev/null
@@ -1,21 +0,0 @@
-require "cases/helper"
-require 'models/developer'
-require 'models/computer'
-
-class MysqlExplainTest < ActiveRecord::MysqlTestCase
- fixtures :developers
-
- def test_explain_for_one_query
- explain = Developer.where(id: 1).explain
- assert_match %(EXPLAIN for: SELECT `developers`.* FROM `developers` WHERE `developers`.`id` = 1), explain
- assert_match %r(developers |.* const), explain
- end
-
- def test_explain_with_eager_loading
- explain = Developer.where(id: 1).includes(:audit_logs).explain
- assert_match %(EXPLAIN for: SELECT `developers`.* FROM `developers` WHERE `developers`.`id` = 1), explain
- assert_match %r(developers |.* const), explain
- assert_match %(EXPLAIN for: SELECT `audit_logs`.* FROM `audit_logs` WHERE `audit_logs`.`developer_id` = 1), explain
- assert_match %r(audit_logs |.* ALL), explain
- end
-end
diff --git a/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb b/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb
deleted file mode 100644
index d2ce48fc00..0000000000
--- a/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb
+++ /dev/null
@@ -1,119 +0,0 @@
-require "cases/helper"
-require 'support/ddl_helper'
-
-module ActiveRecord
- module ConnectionAdapters
- class MysqlAdapterTest < ActiveRecord::MysqlTestCase
- include DdlHelper
-
- def setup
- @conn = ActiveRecord::Base.connection
- end
-
- def test_bad_connection_mysql
- assert_raise ActiveRecord::NoDatabaseError do
- configuration = ActiveRecord::Base.configurations['arunit'].merge(database: 'inexistent_activerecord_unittest')
- connection = ActiveRecord::Base.mysql_connection(configuration)
- connection.drop_table 'ex', if_exists: true
- end
- end
-
- def test_valid_column
- with_example_table do
- column = @conn.columns('ex').find { |col| col.name == 'id' }
- assert @conn.valid_type?(column.type)
- end
- end
-
- def test_invalid_column
- assert_not @conn.valid_type?(:foobar)
- end
-
- def test_client_encoding
- assert_equal Encoding::UTF_8, @conn.client_encoding
- end
-
- def test_exec_insert_number
- with_example_table do
- insert(@conn, 'number' => 10)
-
- result = @conn.exec_query('SELECT number FROM ex WHERE number = 10')
-
- assert_equal 1, result.rows.length
- # if there are no bind parameters, it will return a string (due to
- # the libmysql api)
- assert_equal '10', result.rows.last.last
- end
- end
-
- def test_exec_insert_string
- with_example_table do
- str = 'ã„ãŸã ãã¾ã™ï¼'
- insert(@conn, 'number' => 10, 'data' => str)
-
- result = @conn.exec_query('SELECT number, data FROM ex WHERE number = 10')
-
- value = result.rows.last.last
-
- # FIXME: this should probably be inside the mysql AR adapter?
- value.force_encoding(@conn.client_encoding)
-
- # The strings in this file are utf-8, so transcode to utf-8
- value.encode!(Encoding::UTF_8)
-
- assert_equal str, value
- end
- end
-
- def test_composite_primary_key
- with_example_table '`id` INT, `number` INT, foo INT, PRIMARY KEY (`id`, `number`)' do
- assert_nil @conn.primary_key('ex')
- end
- end
-
- def test_tinyint_integer_typecasting
- with_example_table '`status` TINYINT(4)' do
- insert(@conn, { 'status' => 2 }, 'ex')
-
- result = @conn.exec_query('SELECT status FROM ex')
-
- assert_equal 2, result.column_types['status'].deserialize(result.last['status'])
- end
- end
-
- def test_supports_extensions
- assert_not @conn.supports_extensions?, 'does not support extensions'
- end
-
- def test_respond_to_enable_extension
- assert @conn.respond_to?(:enable_extension)
- end
-
- def test_respond_to_disable_extension
- assert @conn.respond_to?(:disable_extension)
- end
-
- private
- def insert(ctx, data, table='ex')
- binds = data.map { |name, value|
- Relation::QueryAttribute.new(name, value, Type::Value.new)
- }
- columns = binds.map(&:name)
-
- sql = "INSERT INTO #{table} (#{columns.join(", ")})
- VALUES (#{(['?'] * columns.length).join(', ')})"
-
- ctx.exec_insert(sql, 'SQL', binds)
- end
-
- def with_example_table(definition = nil, &block)
- definition ||= <<-SQL
- `id` int auto_increment PRIMARY KEY,
- `number` integer,
- `data` varchar(255)
- SQL
- super(@conn, 'ex', definition, &block)
- end
- end
- end
-end
diff --git a/activerecord/test/cases/adapters/mysql/quoting_test.rb b/activerecord/test/cases/adapters/mysql/quoting_test.rb
deleted file mode 100644
index 2024aa36ab..0000000000
--- a/activerecord/test/cases/adapters/mysql/quoting_test.rb
+++ /dev/null
@@ -1,29 +0,0 @@
-require "cases/helper"
-
-class MysqlQuotingTest < ActiveRecord::MysqlTestCase
- def setup
- @conn = ActiveRecord::Base.connection
- end
-
- def test_type_cast_true
- assert_equal 1, @conn.type_cast(true)
- end
-
- def test_type_cast_false
- assert_equal 0, @conn.type_cast(false)
- end
-
- def test_quoted_date_precision_for_gte_564
- @conn.stubs(:full_version).returns('5.6.4')
- @conn.remove_instance_variable(:@version) if @conn.instance_variable_defined?(:@version)
- t = Time.now.change(usec: 1)
- assert_match(/\.000001\z/, @conn.quoted_date(t))
- end
-
- def test_quoted_date_precision_for_lt_564
- @conn.stubs(:full_version).returns('5.6.3')
- @conn.remove_instance_variable(:@version) if @conn.instance_variable_defined?(:@version)
- t = Time.now.change(usec: 1)
- assert_no_match(/\.000001\z/, @conn.quoted_date(t))
- end
-end
diff --git a/activerecord/test/cases/adapters/mysql/reserved_word_test.rb b/activerecord/test/cases/adapters/mysql/reserved_word_test.rb
deleted file mode 100644
index 4ea1d9ad36..0000000000
--- a/activerecord/test/cases/adapters/mysql/reserved_word_test.rb
+++ /dev/null
@@ -1,153 +0,0 @@
-require "cases/helper"
-
-# a suite of tests to ensure the ConnectionAdapters#MysqlAdapter can handle tables with
-# reserved word names (ie: group, order, values, etc...)
-class MysqlReservedWordTest < ActiveRecord::MysqlTestCase
- class Group < ActiveRecord::Base
- Group.table_name = 'group'
- belongs_to :select
- has_one :values
- end
-
- class Select < ActiveRecord::Base
- Select.table_name = 'select'
- has_many :groups
- end
-
- class Values < ActiveRecord::Base
- Values.table_name = 'values'
- end
-
- class Distinct < ActiveRecord::Base
- Distinct.table_name = 'distinct'
- has_and_belongs_to_many :selects
- has_many :values, :through => :groups
- end
-
- def setup
- @connection = ActiveRecord::Base.connection
-
- # we call execute directly here (and do similar below) because ActiveRecord::Base#create_table()
- # will fail with these table names if these test cases fail
-
- create_tables_directly 'group'=>'id int auto_increment primary key, `order` varchar(255), select_id int',
- 'select'=>'id int auto_increment primary key',
- 'values'=>'id int auto_increment primary key, group_id int',
- 'distinct'=>'id int auto_increment primary key',
- 'distinct_select'=>'distinct_id int, select_id int'
- end
-
- teardown do
- drop_tables_directly ['group', 'select', 'values', 'distinct', 'distinct_select', 'order']
- end
-
- # create tables with reserved-word names and columns
- def test_create_tables
- assert_nothing_raised {
- @connection.create_table :order do |t|
- t.column :group, :string
- end
- }
- end
-
- # rename tables with reserved-word names
- def test_rename_tables
- assert_nothing_raised { @connection.rename_table(:group, :order) }
- end
-
- # alter column with a reserved-word name in a table with a reserved-word name
- def test_change_columns
- assert_nothing_raised { @connection.change_column_default(:group, :order, 'whatever') }
- #the quoting here will reveal any double quoting issues in change_column's interaction with the column method in the adapter
- assert_nothing_raised { @connection.change_column('group', 'order', :Int, :default => 0) }
- assert_nothing_raised { @connection.rename_column(:group, :order, :values) }
- end
-
- # introspect table with reserved word name
- def test_introspect
- assert_nothing_raised { @connection.columns(:group) }
- assert_nothing_raised { @connection.indexes(:group) }
- end
-
- #fixtures
- self.use_instantiated_fixtures = true
- self.use_transactional_tests = false
-
- #activerecord model class with reserved-word table name
- def test_activerecord_model
- create_test_fixtures :select, :distinct, :group, :values, :distinct_select
- x = nil
- assert_nothing_raised { x = Group.new }
- x.order = 'x'
- assert_nothing_raised { x.save }
- x.order = 'y'
- assert_nothing_raised { x.save }
- assert_nothing_raised { Group.find_by_order('y') }
- assert_nothing_raised { Group.find(1) }
- Group.find(1)
- end
-
- # has_one association with reserved-word table name
- def test_has_one_associations
- create_test_fixtures :select, :distinct, :group, :values, :distinct_select
- v = nil
- assert_nothing_raised { v = Group.find(1).values }
- assert_equal 2, v.id
- end
-
- # belongs_to association with reserved-word table name
- def test_belongs_to_associations
- create_test_fixtures :select, :distinct, :group, :values, :distinct_select
- gs = nil
- assert_nothing_raised { gs = Select.find(2).groups }
- assert_equal gs.length, 2
- assert(gs.collect(&:id).sort == [2, 3])
- end
-
- # has_and_belongs_to_many with reserved-word table name
- def test_has_and_belongs_to_many
- create_test_fixtures :select, :distinct, :group, :values, :distinct_select
- s = nil
- assert_nothing_raised { s = Distinct.find(1).selects }
- assert_equal s.length, 2
- assert(s.collect(&:id).sort == [1, 2])
- end
-
- # activerecord model introspection with reserved-word table and column names
- def test_activerecord_introspection
- assert_nothing_raised { Group.table_exists? }
- assert_nothing_raised { Group.columns }
- end
-
- # Calculations
- def test_calculations_work_with_reserved_words
- assert_nothing_raised { Group.count }
- end
-
- def test_associations_work_with_reserved_words
- assert_nothing_raised { Select.all.merge!(:includes => [:groups]).to_a }
- end
-
- #the following functions were added to DRY test cases
-
- private
- # custom fixture loader, uses FixtureSet#create_fixtures and appends base_path to the current file's path
- def create_test_fixtures(*fixture_names)
- ActiveRecord::FixtureSet.create_fixtures(FIXTURES_ROOT + "/reserved_words", fixture_names)
- end
-
- # custom drop table, uses execute on connection to drop a table if it exists. note: escapes table_name
- def drop_tables_directly(table_names, connection = @connection)
- table_names.each do |name|
- connection.drop_table name, if_exists: true
- end
- end
-
- # custom create table, uses execute on connection to create a table, note: escapes table_name, does NOT escape columns
- def create_tables_directly (tables, connection = @connection)
- tables.each do |table_name, column_properties|
- connection.execute("CREATE TABLE `#{table_name}` ( #{column_properties} )")
- end
- end
-
-end
diff --git a/activerecord/test/cases/adapters/mysql/schema_test.rb b/activerecord/test/cases/adapters/mysql/schema_test.rb
deleted file mode 100644
index 14dbdd375b..0000000000
--- a/activerecord/test/cases/adapters/mysql/schema_test.rb
+++ /dev/null
@@ -1,94 +0,0 @@
-require "cases/helper"
-require 'models/post'
-require 'models/comment'
-
-module ActiveRecord
- module ConnectionAdapters
- class MysqlSchemaTest < ActiveRecord::MysqlTestCase
- fixtures :posts
-
- def setup
- @connection = ActiveRecord::Base.connection
- db = Post.connection_pool.spec.config[:database]
- table = Post.table_name
- @db_name = db
-
- @omgpost = Class.new(ActiveRecord::Base) do
- self.inheritance_column = :disabled
- self.table_name = "#{db}.#{table}"
- def self.name; 'Post'; end
- end
- end
-
- def test_float_limits
- @connection.create_table :mysql_doubles do |t|
- t.float :float_no_limit
- t.float :float_short, limit: 5
- t.float :float_long, limit: 53
-
- t.float :float_23, limit: 23
- t.float :float_24, limit: 24
- t.float :float_25, limit: 25
- end
-
- column_no_limit = @connection.columns(:mysql_doubles).find { |c| c.name == 'float_no_limit' }
- column_short = @connection.columns(:mysql_doubles).find { |c| c.name == 'float_short' }
- column_long = @connection.columns(:mysql_doubles).find { |c| c.name == 'float_long' }
-
- column_23 = @connection.columns(:mysql_doubles).find { |c| c.name == 'float_23' }
- column_24 = @connection.columns(:mysql_doubles).find { |c| c.name == 'float_24' }
- column_25 = @connection.columns(:mysql_doubles).find { |c| c.name == 'float_25' }
-
- # Mysql floats are precision 0..24, Mysql doubles are precision 25..53
- assert_equal 24, column_no_limit.limit
- assert_equal 24, column_short.limit
- assert_equal 53, column_long.limit
-
- assert_equal 24, column_23.limit
- assert_equal 24, column_24.limit
- assert_equal 53, column_25.limit
- ensure
- @connection.drop_table "mysql_doubles", if_exists: true
- end
-
- def test_schema
- assert @omgpost.first
- end
-
- def test_primary_key
- assert_equal 'id', @omgpost.primary_key
- end
-
- def test_data_source_exists?
- name = @omgpost.table_name
- assert @connection.data_source_exists?(name), "#{name} data_source should exist"
- end
-
- def test_data_source_exists_wrong_schema
- assert(!@connection.data_source_exists?("#{@db_name}.zomg"), "data_source should not exist")
- end
-
- def test_dump_indexes
- index_a_name = 'index_key_tests_on_snack'
- index_b_name = 'index_key_tests_on_pizza'
- index_c_name = 'index_key_tests_on_awesome'
-
- table = 'key_tests'
-
- indexes = @connection.indexes(table).sort_by(&:name)
- assert_equal 3,indexes.size
-
- index_a = indexes.select{|i| i.name == index_a_name}[0]
- index_b = indexes.select{|i| i.name == index_b_name}[0]
- index_c = indexes.select{|i| i.name == index_c_name}[0]
- assert_equal :btree, index_a.using
- assert_nil index_a.type
- assert_equal :btree, index_b.using
- assert_nil index_b.type
-
- assert_nil index_c.using
- assert_equal :fulltext, index_c.type
- end
- end
- end
-end
diff --git a/activerecord/test/cases/adapters/mysql/sp_test.rb b/activerecord/test/cases/adapters/mysql/sp_test.rb
deleted file mode 100644
index 7849248dcc..0000000000
--- a/activerecord/test/cases/adapters/mysql/sp_test.rb
+++ /dev/null
@@ -1,30 +0,0 @@
-require "cases/helper"
-require 'models/topic'
-require 'models/reply'
-
-class MysqlStoredProcedureTest < ActiveRecord::MysqlTestCase
- fixtures :topics
-
- def setup
- @connection = ActiveRecord::Base.connection
- unless ActiveRecord::Base.connection.version >= '5.6.0' || Mysql.const_defined?(:CLIENT_MULTI_RESULTS)
- skip("no stored procedure support")
- end
- end
-
- # Test that MySQL allows multiple results for stored procedures
- #
- # In MySQL 5.6, CLIENT_MULTI_RESULTS is enabled by default.
- # http://dev.mysql.com/doc/refman/5.6/en/call.html
- def test_multi_results
- rows = @connection.select_rows('CALL ten();')
- assert_equal 10, rows[0][0].to_i, "ten() did not return 10 as expected: #{rows.inspect}"
- assert @connection.active?, "Bad connection use by 'MysqlAdapter.select_rows'"
- end
-
- def test_multi_results_from_find_by_sql
- topics = Topic.find_by_sql 'CALL topics(3);'
- assert_equal 3, topics.size
- assert @connection.active?, "Bad connection use by 'MysqlAdapter.select'"
- end
-end
diff --git a/activerecord/test/cases/adapters/mysql/sql_types_test.rb b/activerecord/test/cases/adapters/mysql/sql_types_test.rb
deleted file mode 100644
index d18579f242..0000000000
--- a/activerecord/test/cases/adapters/mysql/sql_types_test.rb
+++ /dev/null
@@ -1,14 +0,0 @@
-require "cases/helper"
-
-class MysqlSqlTypesTest < ActiveRecord::MysqlTestCase
- def test_binary_types
- assert_equal 'varbinary(64)', type_to_sql(:binary, 64)
- assert_equal 'varbinary(4095)', type_to_sql(:binary, 4095)
- assert_equal 'blob', type_to_sql(:binary, 4096)
- assert_equal 'blob', type_to_sql(:binary)
- end
-
- def type_to_sql(*args)
- ActiveRecord::Base.connection.type_to_sql(*args)
- end
-end
diff --git a/activerecord/test/cases/adapters/mysql/statement_pool_test.rb b/activerecord/test/cases/adapters/mysql/statement_pool_test.rb
deleted file mode 100644
index 0d1f968022..0000000000
--- a/activerecord/test/cases/adapters/mysql/statement_pool_test.rb
+++ /dev/null
@@ -1,19 +0,0 @@
-require 'cases/helper'
-
-class MysqlStatementPoolTest < ActiveRecord::MysqlTestCase
- if Process.respond_to?(:fork)
- def test_cache_is_per_pid
- cache = ActiveRecord::ConnectionAdapters::MysqlAdapter::StatementPool.new(10)
- cache['foo'] = 'bar'
- assert_equal 'bar', cache['foo']
-
- pid = fork {
- lookup = cache['foo'];
- exit!(!lookup)
- }
-
- Process.waitpid pid
- assert $?.success?, 'process should exit successfully'
- end
- end
-end
diff --git a/activerecord/test/cases/adapters/mysql/table_options_test.rb b/activerecord/test/cases/adapters/mysql/table_options_test.rb
deleted file mode 100644
index 99df6d6cba..0000000000
--- a/activerecord/test/cases/adapters/mysql/table_options_test.rb
+++ /dev/null
@@ -1,42 +0,0 @@
-require "cases/helper"
-require 'support/schema_dumping_helper'
-
-class MysqlTableOptionsTest < ActiveRecord::MysqlTestCase
- include SchemaDumpingHelper
-
- def setup
- @connection = ActiveRecord::Base.connection
- end
-
- def teardown
- @connection.drop_table "mysql_table_options", if_exists: true
- end
-
- test "table options with ENGINE" do
- @connection.create_table "mysql_table_options", force: true, options: "ENGINE=MyISAM"
- output = dump_table_schema("mysql_table_options")
- options = %r{create_table "mysql_table_options", force: :cascade, options: "(?<options>.*)"}.match(output)[:options]
- assert_match %r{ENGINE=MyISAM}, options
- end
-
- test "table options with ROW_FORMAT" do
- @connection.create_table "mysql_table_options", force: true, options: "ROW_FORMAT=REDUNDANT"
- output = dump_table_schema("mysql_table_options")
- options = %r{create_table "mysql_table_options", force: :cascade, options: "(?<options>.*)"}.match(output)[:options]
- assert_match %r{ROW_FORMAT=REDUNDANT}, options
- end
-
- test "table options with CHARSET" do
- @connection.create_table "mysql_table_options", force: true, options: "CHARSET=utf8mb4"
- output = dump_table_schema("mysql_table_options")
- options = %r{create_table "mysql_table_options", force: :cascade, options: "(?<options>.*)"}.match(output)[:options]
- assert_match %r{CHARSET=utf8mb4}, options
- end
-
- test "table options with COLLATE" do
- @connection.create_table "mysql_table_options", force: true, options: "COLLATE=utf8mb4_bin"
- output = dump_table_schema("mysql_table_options")
- options = %r{create_table "mysql_table_options", force: :cascade, options: "(?<options>.*)"}.match(output)[:options]
- assert_match %r{COLLATE=utf8mb4_bin}, options
- end
-end
diff --git a/activerecord/test/cases/adapters/mysql/unsigned_type_test.rb b/activerecord/test/cases/adapters/mysql/unsigned_type_test.rb
deleted file mode 100644
index 84c5394c2e..0000000000
--- a/activerecord/test/cases/adapters/mysql/unsigned_type_test.rb
+++ /dev/null
@@ -1,65 +0,0 @@
-require "cases/helper"
-require "support/schema_dumping_helper"
-
-class MysqlUnsignedTypeTest < ActiveRecord::MysqlTestCase
- include SchemaDumpingHelper
- self.use_transactional_tests = false
-
- class UnsignedType < ActiveRecord::Base
- end
-
- setup do
- @connection = ActiveRecord::Base.connection
- @connection.create_table("unsigned_types", force: true) do |t|
- t.integer :unsigned_integer, unsigned: true
- t.bigint :unsigned_bigint, unsigned: true
- t.float :unsigned_float, unsigned: true
- t.decimal :unsigned_decimal, unsigned: true, precision: 10, scale: 2
- end
- end
-
- teardown do
- @connection.drop_table "unsigned_types", if_exists: true
- end
-
- test "unsigned int max value is in range" do
- assert expected = UnsignedType.create(unsigned_integer: 4294967295)
- assert_equal expected, UnsignedType.find_by(unsigned_integer: 4294967295)
- end
-
- test "minus value is out of range" do
- assert_raise(RangeError) do
- UnsignedType.create(unsigned_integer: -10)
- end
- assert_raise(RangeError) do
- UnsignedType.create(unsigned_bigint: -10)
- end
- assert_raise(ActiveRecord::StatementInvalid) do
- UnsignedType.create(unsigned_float: -10.0)
- end
- assert_raise(ActiveRecord::StatementInvalid) do
- UnsignedType.create(unsigned_decimal: -10.0)
- end
- end
-
- test "schema definition can use unsigned as the type" do
- @connection.change_table("unsigned_types") do |t|
- t.unsigned_integer :unsigned_integer_t
- t.unsigned_bigint :unsigned_bigint_t
- t.unsigned_float :unsigned_float_t
- t.unsigned_decimal :unsigned_decimal_t, precision: 10, scale: 2
- end
-
- @connection.columns("unsigned_types").select { |c| /^unsigned_/ === c.name }.each do |column|
- assert column.unsigned?
- end
- end
-
- test "schema dump includes unsigned option" do
- schema = dump_table_schema "unsigned_types"
- assert_match %r{t.integer\s+"unsigned_integer",\s+limit: 4,\s+unsigned: true$}, schema
- assert_match %r{t.integer\s+"unsigned_bigint",\s+limit: 8,\s+unsigned: true$}, schema
- assert_match %r{t.float\s+"unsigned_float",\s+limit: 24,\s+unsigned: true$}, schema
- assert_match %r{t.decimal\s+"unsigned_decimal",\s+precision: 10,\s+scale: 2,\s+unsigned: true$}, schema
- end
-end
diff --git a/activerecord/test/cases/adapters/mysql2/active_schema_test.rb b/activerecord/test/cases/adapters/mysql2/active_schema_test.rb
index b97eb3e228..99f97c7914 100644
--- a/activerecord/test/cases/adapters/mysql2/active_schema_test.rb
+++ b/activerecord/test/cases/adapters/mysql2/active_schema_test.rb
@@ -16,7 +16,7 @@ class Mysql2ActiveSchemaTest < ActiveRecord::Mysql2TestCase
end
def test_add_index
- # add_index calls table_exists? and index_name_exists? which can't work since execute is stubbed
+ # add_index calls data_source_exists? and index_name_exists? which can't work since execute is stubbed
def (ActiveRecord::Base.connection).data_source_exists?(*); true; end
def (ActiveRecord::Base.connection).index_name_exists?(*); false; end
diff --git a/activerecord/test/cases/adapters/mysql2/charset_collation_test.rb b/activerecord/test/cases/adapters/mysql2/charset_collation_test.rb
index 4fd34def15..668c07dacb 100644
--- a/activerecord/test/cases/adapters/mysql2/charset_collation_test.rb
+++ b/activerecord/test/cases/adapters/mysql2/charset_collation_test.rb
@@ -48,7 +48,7 @@ class Mysql2CharsetCollationTest < ActiveRecord::Mysql2TestCase
test "schema dump includes collation" do
output = dump_table_schema("charset_collations")
- assert_match %r{t.string\s+"string_ascii_bin",\s+limit: 255,\s+collation: "ascii_bin"$}, output
+ assert_match %r{t.string\s+"string_ascii_bin",\s+collation: "ascii_bin"$}, output
assert_match %r{t.text\s+"text_ucs2_unicode_ci",\s+limit: 65535,\s+collation: "ucs2_unicode_ci"$}, output
end
end
diff --git a/activerecord/test/cases/adapters/mysql2/connection_test.rb b/activerecord/test/cases/adapters/mysql2/connection_test.rb
index 71c4028675..8fabcfb5c0 100644
--- a/activerecord/test/cases/adapters/mysql2/connection_test.rb
+++ b/activerecord/test/cases/adapters/mysql2/connection_test.rb
@@ -83,6 +83,13 @@ class Mysql2ConnectionTest < ActiveRecord::Mysql2TestCase
assert_equal [['']], result.rows
end
end
+
+ def test_passing_arbitary_flags_to_adapter
+ run_without_connection do |orig_connection|
+ ActiveRecord::Base.establish_connection(orig_connection.merge({flags: Mysql2::Client::COMPRESS}))
+ assert_equal (Mysql2::Client::COMPRESS | Mysql2::Client::FOUND_ROWS), ActiveRecord::Base.connection.raw_connection.query_options[:flags]
+ end
+ end
def test_mysql_strict_mode_specified_default
run_without_connection do |orig_connection|
@@ -133,30 +140,30 @@ class Mysql2ConnectionTest < ActiveRecord::Mysql2TestCase
end
def test_get_and_release_advisory_lock
- key = "test_key"
+ lock_name = "test_lock_name"
- got_lock = @connection.get_advisory_lock(key)
+ got_lock = @connection.get_advisory_lock(lock_name)
assert got_lock, "get_advisory_lock should have returned true but it didn't"
- assert_equal test_lock_free(key), false,
+ assert_equal test_lock_free(lock_name), false,
"expected the test advisory lock to be held but it wasn't"
- released_lock = @connection.release_advisory_lock(key)
+ released_lock = @connection.release_advisory_lock(lock_name)
assert released_lock, "expected release_advisory_lock to return true but it didn't"
- assert test_lock_free(key), 'expected the test key to be available after releasing'
+ assert test_lock_free(lock_name), 'expected the test lock to be available after releasing'
end
def test_release_non_existent_advisory_lock
- fake_key = "fake_key"
- released_non_existent_lock = @connection.release_advisory_lock(fake_key)
+ lock_name = "fake_lock_name"
+ released_non_existent_lock = @connection.release_advisory_lock(lock_name)
assert_equal released_non_existent_lock, false,
'expected release_advisory_lock to return false when there was no lock to release'
end
protected
- def test_lock_free(key)
- @connection.select_value("SELECT IS_FREE_LOCK('#{key}');") == 1
+ def test_lock_free(lock_name)
+ @connection.select_value("SELECT IS_FREE_LOCK('#{lock_name}');") == 1
end
end
diff --git a/activerecord/test/cases/adapters/mysql2/unsigned_type_test.rb b/activerecord/test/cases/adapters/mysql2/unsigned_type_test.rb
index a6f6dd21bb..c95a64cc16 100644
--- a/activerecord/test/cases/adapters/mysql2/unsigned_type_test.rb
+++ b/activerecord/test/cases/adapters/mysql2/unsigned_type_test.rb
@@ -57,7 +57,7 @@ class Mysql2UnsignedTypeTest < ActiveRecord::Mysql2TestCase
test "schema dump includes unsigned option" do
schema = dump_table_schema "unsigned_types"
- assert_match %r{t.integer\s+"unsigned_integer",\s+limit: 4,\s+unsigned: true$}, schema
+ assert_match %r{t.integer\s+"unsigned_integer",\s+unsigned: true$}, schema
assert_match %r{t.integer\s+"unsigned_bigint",\s+limit: 8,\s+unsigned: true$}, schema
assert_match %r{t.float\s+"unsigned_float",\s+limit: 24,\s+unsigned: true$}, schema
assert_match %r{t.decimal\s+"unsigned_decimal",\s+precision: 10,\s+scale: 2,\s+unsigned: true$}, schema
diff --git a/activerecord/test/cases/adapters/postgresql/active_schema_test.rb b/activerecord/test/cases/adapters/postgresql/active_schema_test.rb
index 24def31e36..ed44bf7362 100644
--- a/activerecord/test/cases/adapters/postgresql/active_schema_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/active_schema_test.rb
@@ -54,8 +54,10 @@ class PostgresqlActiveSchemaTest < ActiveRecord::PostgreSQLTestCase
end
def test_remove_index
- # remove_index calls index_name_exists? which can't work since execute is stubbed
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.send(:define_method, :index_name_exists?) { |*| true }
+ # remove_index calls index_name_for_remove which can't work since execute is stubbed
+ ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.send(:define_method, :index_name_for_remove) do |*|
+ 'index_people_on_last_name'
+ end
expected = %(DROP INDEX CONCURRENTLY "index_people_on_last_name")
assert_equal expected, remove_index(:people, name: "index_people_on_last_name", algorithm: :concurrently)
@@ -64,7 +66,7 @@ class PostgresqlActiveSchemaTest < ActiveRecord::PostgreSQLTestCase
add_index(:people, :last_name, algorithm: :copy)
end
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.send :remove_method, :index_name_exists?
+ ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.send :remove_method, :index_name_for_remove
end
private
diff --git a/activerecord/test/cases/adapters/postgresql/connection_test.rb b/activerecord/test/cases/adapters/postgresql/connection_test.rb
index 0ecac2cfa3..d559de3e28 100644
--- a/activerecord/test/cases/adapters/postgresql/connection_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/connection_test.rb
@@ -211,33 +211,33 @@ module ActiveRecord
end
def test_get_and_release_advisory_lock
- key = 5295901941911233559
+ lock_id = 5295901941911233559
list_advisory_locks = <<-SQL
SELECT locktype,
- (classid::bigint << 32) | objid::bigint AS lock_key
+ (classid::bigint << 32) | objid::bigint AS lock_id
FROM pg_locks
WHERE locktype = 'advisory'
SQL
- got_lock = @connection.get_advisory_lock(key)
+ got_lock = @connection.get_advisory_lock(lock_id)
assert got_lock, "get_advisory_lock should have returned true but it didn't"
- advisory_lock = @connection.query(list_advisory_locks).find {|l| l[1] == key}
+ advisory_lock = @connection.query(list_advisory_locks).find {|l| l[1] == lock_id}
assert advisory_lock,
- "expected to find an advisory lock with key #{key} but there wasn't one"
+ "expected to find an advisory lock with lock_id #{lock_id} but there wasn't one"
- released_lock = @connection.release_advisory_lock(key)
+ released_lock = @connection.release_advisory_lock(lock_id)
assert released_lock, "expected release_advisory_lock to return true but it didn't"
- advisory_locks = @connection.query(list_advisory_locks).select {|l| l[1] == key}
+ advisory_locks = @connection.query(list_advisory_locks).select {|l| l[1] == lock_id}
assert_empty advisory_locks,
- "expected to have released advisory lock with key #{key} but it was still held"
+ "expected to have released advisory lock with lock_id #{lock_id} but it was still held"
end
def test_release_non_existent_advisory_lock
- fake_key = 2940075057017742022
+ fake_lock_id = 2940075057017742022
with_warning_suppression do
- released_non_existent_lock = @connection.release_advisory_lock(fake_key)
+ released_non_existent_lock = @connection.release_advisory_lock(fake_lock_id)
assert_equal released_non_existent_lock, false,
'expected release_advisory_lock to return false when there was no lock to release'
end
diff --git a/activerecord/test/cases/adapters/postgresql/extension_migration_test.rb b/activerecord/test/cases/adapters/postgresql/extension_migration_test.rb
index 9cfc133308..b2a805333c 100644
--- a/activerecord/test/cases/adapters/postgresql/extension_migration_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/extension_migration_test.rb
@@ -3,13 +3,13 @@ require "cases/helper"
class PostgresqlExtensionMigrationTest < ActiveRecord::PostgreSQLTestCase
self.use_transactional_tests = false
- class EnableHstore < ActiveRecord::Migration
+ class EnableHstore < ActiveRecord::Migration::Current
def change
enable_extension "hstore"
end
end
- class DisableHstore < ActiveRecord::Migration
+ class DisableHstore < ActiveRecord::Migration::Current
def change
disable_extension "hstore"
end
diff --git a/activerecord/test/cases/adapters/postgresql/geometric_test.rb b/activerecord/test/cases/adapters/postgresql/geometric_test.rb
index 0baf985654..9e250c2b7c 100644
--- a/activerecord/test/cases/adapters/postgresql/geometric_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/geometric_test.rb
@@ -7,10 +7,10 @@ class PostgresqlPointTest < ActiveRecord::PostgreSQLTestCase
include SchemaDumpingHelper
class PostgresqlPoint < ActiveRecord::Base
- attribute :x, :rails_5_1_point
- attribute :y, :rails_5_1_point
- attribute :z, :rails_5_1_point
- attribute :array_of_points, :rails_5_1_point, array: true
+ attribute :x, :point
+ attribute :y, :point
+ attribute :z, :point
+ attribute :array_of_points, :point, array: true
attribute :legacy_x, :legacy_point
attribute :legacy_y, :legacy_point
attribute :legacy_z, :legacy_point
@@ -167,16 +167,18 @@ class PostgresqlPointTest < ActiveRecord::PostgreSQLTestCase
end
class PostgresqlGeometricTest < ActiveRecord::PostgreSQLTestCase
+ include SchemaDumpingHelper
+
class PostgresqlGeometric < ActiveRecord::Base; end
setup do
@connection = ActiveRecord::Base.connection
@connection.create_table("postgresql_geometrics") do |t|
- t.column :a_line_segment, :lseg
- t.column :a_box, :box
- t.column :a_path, :path
- t.column :a_polygon, :polygon
- t.column :a_circle, :circle
+ t.lseg :a_line_segment
+ t.box :a_box
+ t.path :a_path
+ t.polygon :a_polygon
+ t.circle :a_circle
end
end
@@ -233,4 +235,144 @@ class PostgresqlGeometricTest < ActiveRecord::PostgreSQLTestCase
objs = PostgresqlGeometric.find_by_sql "SELECT isclosed(a_path) FROM postgresql_geometrics ORDER BY id ASC"
assert_equal [false, true], objs.map(&:isclosed)
end
+
+ def test_schema_dumping
+ output = dump_table_schema("postgresql_geometrics")
+ assert_match %r{t\.lseg\s+"a_line_segment"$}, output
+ assert_match %r{t\.box\s+"a_box"$}, output
+ assert_match %r{t\.path\s+"a_path"$}, output
+ assert_match %r{t\.polygon\s+"a_polygon"$}, output
+ assert_match %r{t\.circle\s+"a_circle"$}, output
+ end
+end
+
+class PostgreSQLGeometricLineTest < ActiveRecord::PostgreSQLTestCase
+ include SchemaDumpingHelper
+
+ class PostgresqlLine < ActiveRecord::Base; end
+
+ setup do
+ unless ActiveRecord::Base.connection.send(:postgresql_version) >= 90400
+ skip("line type is not fully implemented")
+ end
+ @connection = ActiveRecord::Base.connection
+ @connection.create_table("postgresql_lines") do |t|
+ t.line :a_line
+ end
+ end
+
+ teardown do
+ if defined?(@connection)
+ @connection.drop_table 'postgresql_lines', if_exists: true
+ end
+ end
+
+ def test_geometric_line_type
+ g = PostgresqlLine.new(
+ a_line: '{2.0, 3, 5.5}'
+ )
+ g.save!
+
+ h = PostgresqlLine.find(g.id)
+ assert_equal '{2,3,5.5}', h.a_line
+ end
+
+ def test_alternative_format_line_type
+ g = PostgresqlLine.new(
+ a_line: '(2.0, 3), (4.0, 6.0)'
+ )
+ g.save!
+
+ h = PostgresqlLine.find(g.id)
+ assert_equal '{1.5,-1,0}', h.a_line
+ end
+
+ def test_schema_dumping_for_line_type
+ output = dump_table_schema("postgresql_lines")
+ assert_match %r{t\.line\s+"a_line"$}, output
+ end
+end
+
+class PostgreSQLGeometricTypesTest < ActiveRecord::PostgreSQLTestCase
+ attr_reader :connection, :table_name
+
+ def setup
+ super
+ @connection = ActiveRecord::Base.connection
+ @table_name = :testings
+ end
+
+ def test_creating_column_with_point_type
+ connection.create_table(table_name) do |t|
+ t.point :foo_point
+ end
+
+ assert_column_exists(:foo_point)
+ assert_type_correct(:foo_point, :point)
+ end
+
+ def test_creating_column_with_line_type
+ connection.create_table(table_name) do |t|
+ t.line :foo_line
+ end
+
+ assert_column_exists(:foo_line)
+ assert_type_correct(:foo_line, :line)
+ end
+
+ def test_creating_column_with_lseg_type
+ connection.create_table(table_name) do |t|
+ t.lseg :foo_lseg
+ end
+
+ assert_column_exists(:foo_lseg)
+ assert_type_correct(:foo_lseg, :lseg)
+ end
+
+ def test_creating_column_with_box_type
+ connection.create_table(table_name) do |t|
+ t.box :foo_box
+ end
+
+ assert_column_exists(:foo_box)
+ assert_type_correct(:foo_box, :box)
+ end
+
+ def test_creating_column_with_path_type
+ connection.create_table(table_name) do |t|
+ t.path :foo_path
+ end
+
+ assert_column_exists(:foo_path)
+ assert_type_correct(:foo_path, :path)
+ end
+
+ def test_creating_column_with_polygon_type
+ connection.create_table(table_name) do |t|
+ t.polygon :foo_polygon
+ end
+
+ assert_column_exists(:foo_polygon)
+ assert_type_correct(:foo_polygon, :polygon)
+ end
+
+ def test_creating_column_with_circle_type
+ connection.create_table(table_name) do |t|
+ t.circle :foo_circle
+ end
+
+ assert_column_exists(:foo_circle)
+ assert_type_correct(:foo_circle, :circle)
+ end
+
+ private
+
+ def assert_column_exists(column_name)
+ assert connection.column_exists?(table_name, column_name)
+ end
+
+ def assert_type_correct(column_name, type)
+ column = connection.columns(table_name).find { |c| c.name == column_name.to_s }
+ assert_equal type, column.type
+ end
end
diff --git a/activerecord/test/cases/adapters/postgresql/hstore_test.rb b/activerecord/test/cases/adapters/postgresql/hstore_test.rb
index 6a2d501646..27cc65a643 100644
--- a/activerecord/test/cases/adapters/postgresql/hstore_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/hstore_test.rb
@@ -86,7 +86,7 @@ if ActiveRecord::Base.connection.supports_extensions?
end
def test_hstore_migration
- hstore_migration = Class.new(ActiveRecord::Migration) do
+ hstore_migration = Class.new(ActiveRecord::Migration::Current) do
def change
change_table("hstores") do |t|
t.hstore :keys
diff --git a/activerecord/test/cases/adapters/postgresql/schema_test.rb b/activerecord/test/cases/adapters/postgresql/schema_test.rb
index 7c9169f6e2..4aeca4d709 100644
--- a/activerecord/test/cases/adapters/postgresql/schema_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/schema_test.rb
@@ -321,16 +321,33 @@ class SchemaTest < ActiveRecord::PostgreSQLTestCase
do_dump_index_tests_for_schema("public, #{SCHEMA_NAME}", INDEX_A_COLUMN, INDEX_B_COLUMN_S1, INDEX_D_COLUMN, INDEX_E_COLUMN)
end
+ def test_dump_indexes_for_table_with_scheme_specified_in_name
+ indexes = @connection.indexes("#{SCHEMA_NAME}.#{TABLE_NAME}")
+ assert_equal 4, indexes.size
+ end
+
def test_with_uppercase_index_name
@connection.execute "CREATE INDEX \"things_Index\" ON #{SCHEMA_NAME}.things (name)"
- assert_nothing_raised { @connection.remove_index "things", name: "#{SCHEMA_NAME}.things_Index"}
- @connection.execute "CREATE INDEX \"things_Index\" ON #{SCHEMA_NAME}.things (name)"
with_schema_search_path SCHEMA_NAME do
assert_nothing_raised { @connection.remove_index "things", name: "things_Index"}
end
end
+ def test_remove_index_when_schema_specified
+ @connection.execute "CREATE INDEX \"things_Index\" ON #{SCHEMA_NAME}.things (name)"
+ assert_nothing_raised { @connection.remove_index "things", name: "#{SCHEMA_NAME}.things_Index" }
+
+ @connection.execute "CREATE INDEX \"things_Index\" ON #{SCHEMA_NAME}.things (name)"
+ assert_nothing_raised { @connection.remove_index "#{SCHEMA_NAME}.things", name: "things_Index" }
+
+ @connection.execute "CREATE INDEX \"things_Index\" ON #{SCHEMA_NAME}.things (name)"
+ assert_nothing_raised { @connection.remove_index "#{SCHEMA_NAME}.things", name: "#{SCHEMA_NAME}.things_Index" }
+
+ @connection.execute "CREATE INDEX \"things_Index\" ON #{SCHEMA_NAME}.things (name)"
+ assert_raises(ArgumentError) { @connection.remove_index "#{SCHEMA2_NAME}.things", name: "#{SCHEMA_NAME}.things_Index" }
+ end
+
def test_primary_key_with_schema_specified
[
%("#{SCHEMA_NAME}"."#{PK_TABLE_NAME}"),
diff --git a/activerecord/test/cases/adapters/postgresql/uuid_test.rb b/activerecord/test/cases/adapters/postgresql/uuid_test.rb
index 7127d69e9e..049ed1732e 100644
--- a/activerecord/test/cases/adapters/postgresql/uuid_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/uuid_test.rb
@@ -20,6 +20,8 @@ class PostgresqlUUIDTest < ActiveRecord::PostgreSQLTestCase
end
setup do
+ enable_extension!('uuid-ossp', connection)
+
connection.create_table "uuid_data_type" do |t|
t.uuid 'guid'
end
diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_create_folder_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_create_folder_test.rb
index 887dcfc96c..9b675b804b 100644
--- a/activerecord/test/cases/adapters/sqlite3/sqlite3_create_folder_test.rb
+++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_create_folder_test.rb
@@ -6,13 +6,17 @@ module ActiveRecord
class SQLite3CreateFolder < ActiveRecord::SQLite3TestCase
def test_sqlite_creates_directory
Dir.mktmpdir do |dir|
- dir = Pathname.new(dir)
- @conn = Base.sqlite3_connection :database => dir.join("db/foo.sqlite3"),
- :adapter => 'sqlite3',
- :timeout => 100
+ begin
+ dir = Pathname.new(dir)
+ @conn = Base.sqlite3_connection :database => dir.join("db/foo.sqlite3"),
+ :adapter => 'sqlite3',
+ :timeout => 100
- assert Dir.exist? dir.join('db')
- assert File.exist? dir.join('db/foo.sqlite3')
+ assert Dir.exist? dir.join('db')
+ assert File.exist? dir.join('db/foo.sqlite3')
+ ensure
+ @conn.disconnect! if @conn
+ end
end
end
end
diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb
index 938350627f..4f99c57c3c 100644
--- a/activerecord/test/cases/associations/belongs_to_associations_test.rb
+++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb
@@ -53,7 +53,7 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
def test_belongs_to_with_primary_key_joins_on_correct_column
sql = Client.joins(:firm_with_primary_key).to_sql
- if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ if current_adapter?(:Mysql2Adapter)
assert_no_match(/`firm_with_primary_keys_companies`\.`id`/, sql)
assert_match(/`firm_with_primary_keys_companies`\.`name`/, sql)
elsif current_adapter?(:OracleAdapter)
diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb
index 0c09713971..874d53c51f 100644
--- a/activerecord/test/cases/associations/eager_test.rb
+++ b/activerecord/test/cases/associations/eager_test.rb
@@ -1402,4 +1402,10 @@ class EagerAssociationTest < ActiveRecord::TestCase
post = Post.eager_load(:tags).where('tags.name = ?', 'General').first
assert_equal posts(:welcome), post
end
+
+ # CollectionProxy#reader is expensive, so the preloader avoids calling it.
+ test "preloading has_many_through association avoids calling association.reader" do
+ ActiveRecord::Associations::HasManyAssociation.any_instance.expects(:reader).never
+ Author.preload(:readonly_comments).first!
+ 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 eb94870a35..ad157582a4 100644
--- a/activerecord/test/cases/associations/has_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -203,9 +203,22 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
bulb = car.bulbs.create
assert_equal 'defaulty', bulb.name
+ end
+
+ def test_build_and_create_from_association_should_respect_passed_attributes_over_default_scope
+ car = Car.create(name: 'honda')
- bulb = car.bulbs.create(:name => 'exotic')
+ bulb = car.bulbs.build(name: 'exotic')
assert_equal 'exotic', bulb.name
+
+ bulb = car.bulbs.create(name: 'exotic')
+ assert_equal 'exotic', bulb.name
+
+ bulb = car.awesome_bulbs.build(frickinawesome: false)
+ assert_equal false, bulb.frickinawesome
+
+ bulb = car.awesome_bulbs.create(frickinawesome: false)
+ assert_equal false, bulb.frickinawesome
end
def test_build_from_association_should_respect_scope
@@ -2335,6 +2348,12 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal [first_bulb, second_bulb], car.bulbs
end
+ test 'double insertion of new object to association when same association used in the after create callback of a new object' do
+ car = Car.create!
+ car.bulbs << TrickyBulb.new
+ assert_equal 1, car.bulbs.size
+ end
+
def test_association_force_reload_with_only_true_is_deprecated
company = Company.find(1)
diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb
index 52d197718e..94dfbc3346 100644
--- a/activerecord/test/cases/attribute_methods_test.rb
+++ b/activerecord/test/cases/attribute_methods_test.rb
@@ -175,7 +175,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase
assert_equal category_attrs , category.attributes_before_type_cast
end
- if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ if current_adapter?(:Mysql2Adapter)
def test_read_attributes_before_type_cast_on_boolean
bool = Boolean.create!({ "value" => false })
if RUBY_PLATFORM =~ /java/
diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb
index d961f4710e..79791af187 100644
--- a/activerecord/test/cases/base_test.rb
+++ b/activerecord/test/cases/base_test.rb
@@ -112,7 +112,9 @@ class BasicsTest < ActiveRecord::TestCase
unless current_adapter?(:PostgreSQLAdapter, :OracleAdapter, :SQLServerAdapter, :FbAdapter)
def test_limit_with_comma
- assert Topic.limit("1,2").to_a
+ assert_deprecated do
+ assert Topic.limit("1,2").to_a
+ end
end
end
@@ -138,14 +140,10 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_limit_should_sanitize_sql_injection_for_limit_with_commas
- assert_raises(ArgumentError) do
- Topic.limit("1, 7 procedure help()").to_a
- end
- end
-
- unless current_adapter?(:MysqlAdapter, :Mysql2Adapter)
- def test_limit_should_allow_sql_literal
- assert_equal 1, Topic.limit(Arel.sql('2-1')).to_a.length
+ assert_deprecated do
+ assert_raises(ArgumentError) do
+ Topic.limit("1, 7 procedure help()").to_a
+ end
end
end
@@ -213,7 +211,7 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_preserving_time_objects_with_local_time_conversion_to_default_timezone_utc
- with_env_tz 'America/New_York' do
+ with_env_tz eastern_time_zone do
with_timezone_config default: :utc do
time = Time.local(2000)
topic = Topic.create('written_on' => time)
@@ -226,7 +224,7 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_preserving_time_objects_with_time_with_zone_conversion_to_default_timezone_utc
- with_env_tz 'America/New_York' do
+ with_env_tz eastern_time_zone do
with_timezone_config default: :utc do
Time.use_zone 'Central Time (US & Canada)' do
time = Time.zone.local(2000)
@@ -241,7 +239,7 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_preserving_time_objects_with_utc_time_conversion_to_default_timezone_local
- with_env_tz 'America/New_York' do
+ with_env_tz eastern_time_zone do
with_timezone_config default: :local do
time = Time.utc(2000)
topic = Topic.create('written_on' => time)
@@ -254,7 +252,7 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_preserving_time_objects_with_time_with_zone_conversion_to_default_timezone_local
- with_env_tz 'America/New_York' do
+ with_env_tz eastern_time_zone do
with_timezone_config default: :local do
Time.use_zone 'Central Time (US & Canada)' do
time = Time.zone.local(2000)
@@ -268,6 +266,14 @@ class BasicsTest < ActiveRecord::TestCase
end
end
+ def eastern_time_zone
+ if Gem.win_platform?
+ "EST5EDT"
+ else
+ "America/New_York"
+ end
+ end
+
def test_custom_mutator
topic = Topic.find(1)
# This mutator is protected in the class definition
@@ -438,7 +444,7 @@ class BasicsTest < ActiveRecord::TestCase
Post.reset_table_name
end
- if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ if current_adapter?(:Mysql2Adapter)
def test_update_all_with_order_and_limit
assert_equal 1, Topic.limit(1).order('id DESC').update_all(:content => 'bulk updated!')
end
@@ -519,7 +525,8 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_find_by_slug_with_array
- assert_equal Topic.find(['1-meowmeow', '2-hello']), Topic.find([1, 2])
+ assert_equal Topic.find([1, 2]), Topic.find(['1-meowmeow', '2-hello'])
+ assert_equal 'The Second Topic of the day', Topic.find(['2-hello', '1-meowmeow']).first.title
end
def test_find_by_slug_with_range
@@ -1345,6 +1352,19 @@ class BasicsTest < ActiveRecord::TestCase
Company.attribute_names
end
+ def test_has_attribute
+ assert Company.has_attribute?('id')
+ assert Company.has_attribute?('type')
+ assert Company.has_attribute?('name')
+ assert_not Company.has_attribute?('lastname')
+ assert_not Company.has_attribute?('age')
+ end
+
+ def test_has_attribute_with_symbol
+ assert Company.has_attribute?(:id)
+ assert_not Company.has_attribute?(:age)
+ end
+
def test_attribute_names_on_table_not_exists
assert_equal [], NonExistentTable.attribute_names
end
diff --git a/activerecord/test/cases/binary_test.rb b/activerecord/test/cases/binary_test.rb
index 86dee929bf..9eb5352150 100644
--- a/activerecord/test/cases/binary_test.rb
+++ b/activerecord/test/cases/binary_test.rb
@@ -20,10 +20,6 @@ unless current_adapter?(:DB2Adapter)
name = binary.name
- # MySQL adapter doesn't properly encode things, so we have to do it
- if current_adapter?(:MysqlAdapter)
- name.force_encoding(Encoding::UTF_8)
- end
assert_equal 'ã„ãŸã ãã¾ã™ï¼', name
end
diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb
index 4a0e6f497f..d09009b65d 100644
--- a/activerecord/test/cases/calculations_test.rb
+++ b/activerecord/test/cases/calculations_test.rb
@@ -546,7 +546,7 @@ class CalculationsTest < ActiveRecord::TestCase
end
def test_from_option_with_specified_index
- if Edge.connection.adapter_name == 'MySQL' or Edge.connection.adapter_name == 'Mysql2'
+ if Edge.connection.adapter_name == 'Mysql2'
assert_equal Edge.count(:all), Edge.from('edges USE INDEX(unique_edge_index)').count(:all)
assert_equal Edge.where('sink_id < 5').count(:all),
Edge.from('edges USE INDEX(unique_edge_index)').where('sink_id < 5').count(:all)
diff --git a/activerecord/test/cases/callbacks_test.rb b/activerecord/test/cases/callbacks_test.rb
index 73ac30e547..4f70ae3a1d 100644
--- a/activerecord/test/cases/callbacks_test.rb
+++ b/activerecord/test/cases/callbacks_test.rb
@@ -33,7 +33,7 @@ class CallbackDeveloper < ActiveRecord::Base
ActiveRecord::Callbacks::CALLBACKS.each do |callback_method|
next if callback_method.to_s =~ /^around_/
define_callback_method(callback_method)
- send(callback_method, callback_string(callback_method))
+ ActiveSupport::Deprecation.silence { send(callback_method, callback_string(callback_method)) }
send(callback_method, callback_proc(callback_method))
send(callback_method, callback_object(callback_method))
send(callback_method) { |model| model.history << [callback_method, :block] }
diff --git a/activerecord/test/cases/column_definition_test.rb b/activerecord/test/cases/column_definition_test.rb
index 14b95ecab1..da0d7f5195 100644
--- a/activerecord/test/cases/column_definition_test.rb
+++ b/activerecord/test/cases/column_definition_test.rb
@@ -38,7 +38,7 @@ module ActiveRecord
assert_equal %Q{title varchar(20) DEFAULT 'Hello' NOT NULL}, @viz.accept(column_def)
end
- if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ if current_adapter?(:Mysql2Adapter)
def test_should_set_default_for_mysql_binary_data_types
type = SqlTypeMetadata.new(type: :binary, sql_type: "binary(1)")
binary_column = AbstractMysqlAdapter::Column.new("title", "a", type)
diff --git a/activerecord/test/cases/connection_adapters/mysql_type_lookup_test.rb b/activerecord/test/cases/connection_adapters/mysql_type_lookup_test.rb
index 2749273884..f2b1d9e4e7 100644
--- a/activerecord/test/cases/connection_adapters/mysql_type_lookup_test.rb
+++ b/activerecord/test/cases/connection_adapters/mysql_type_lookup_test.rb
@@ -1,6 +1,6 @@
require "cases/helper"
-if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+if current_adapter?(:Mysql2Adapter)
module ActiveRecord
module ConnectionAdapters
class MysqlTypeLookupTest < ActiveRecord::TestCase
diff --git a/activerecord/test/cases/custom_locking_test.rb b/activerecord/test/cases/custom_locking_test.rb
index e8290297e3..26d015bf71 100644
--- a/activerecord/test/cases/custom_locking_test.rb
+++ b/activerecord/test/cases/custom_locking_test.rb
@@ -6,7 +6,7 @@ module ActiveRecord
fixtures :people
def test_custom_lock
- if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ if current_adapter?(:Mysql2Adapter)
assert_match 'SHARE MODE', Person.lock('LOCK IN SHARE MODE').to_sql
assert_sql(/LOCK IN SHARE MODE/) do
Person.all.merge!(:lock => 'LOCK IN SHARE MODE').find(1)
diff --git a/activerecord/test/cases/date_time_precision_test.rb b/activerecord/test/cases/date_time_precision_test.rb
index 698f1b852e..e996d142a2 100644
--- a/activerecord/test/cases/date_time_precision_test.rb
+++ b/activerecord/test/cases/date_time_precision_test.rb
@@ -10,6 +10,7 @@ class DateTimePrecisionTest < ActiveRecord::TestCase
setup do
@connection = ActiveRecord::Base.connection
+ Foo.reset_column_information
end
teardown do
@@ -20,24 +21,24 @@ class DateTimePrecisionTest < ActiveRecord::TestCase
@connection.create_table(:foos, force: true)
@connection.add_column :foos, :created_at, :datetime, precision: 0
@connection.add_column :foos, :updated_at, :datetime, precision: 5
- assert_equal 0, activerecord_column_option('foos', 'created_at', 'precision')
- assert_equal 5, activerecord_column_option('foos', 'updated_at', 'precision')
+ assert_equal 0, Foo.columns_hash['created_at'].precision
+ assert_equal 5, Foo.columns_hash['updated_at'].precision
end
def test_timestamps_helper_with_custom_precision
@connection.create_table(:foos, force: true) do |t|
t.timestamps precision: 4
end
- assert_equal 4, activerecord_column_option('foos', 'created_at', 'precision')
- assert_equal 4, activerecord_column_option('foos', 'updated_at', 'precision')
+ assert_equal 4, Foo.columns_hash['created_at'].precision
+ assert_equal 4, Foo.columns_hash['updated_at'].precision
end
def test_passing_precision_to_datetime_does_not_set_limit
@connection.create_table(:foos, force: true) do |t|
t.timestamps precision: 4
end
- assert_nil activerecord_column_option('foos', 'created_at', 'limit')
- assert_nil activerecord_column_option('foos', 'updated_at', 'limit')
+ assert_nil Foo.columns_hash['created_at'].limit
+ assert_nil Foo.columns_hash['updated_at'].limit
end
def test_invalid_datetime_precision_raises_error
@@ -48,14 +49,6 @@ class DateTimePrecisionTest < ActiveRecord::TestCase
end
end
- def test_database_agrees_with_activerecord_about_precision
- @connection.create_table(:foos, force: true) do |t|
- t.timestamps precision: 4
- end
- assert_equal 4, database_datetime_precision('foos', 'created_at')
- assert_equal 4, database_datetime_precision('foos', 'updated_at')
- end
-
def test_formatting_datetime_according_to_precision
@connection.create_table(:foos, force: true) do |t|
t.datetime :created_at, precision: 0
@@ -91,21 +84,5 @@ class DateTimePrecisionTest < ActiveRecord::TestCase
end
end
- private
-
- def database_datetime_precision(table_name, column_name)
- results = @connection.exec_query("SELECT column_name, datetime_precision FROM information_schema.columns WHERE table_name = '#{table_name}'")
- result = results.find do |result_hash|
- result_hash["column_name"] == column_name
- end
- result && result["datetime_precision"].to_i
- end
-
- def activerecord_column_option(tablename, column_name, option)
- result = @connection.columns(tablename).find do |column|
- column.name == column_name
- end
- result && result.send(option)
- end
end
end
diff --git a/activerecord/test/cases/defaults_test.rb b/activerecord/test/cases/defaults_test.rb
index 67fddebf45..fb2d3bd497 100644
--- a/activerecord/test/cases/defaults_test.rb
+++ b/activerecord/test/cases/defaults_test.rb
@@ -4,17 +4,10 @@ require 'models/entrant'
class DefaultTest < ActiveRecord::TestCase
def test_nil_defaults_for_not_null_columns
- column_defaults =
- if current_adapter?(:MysqlAdapter) && (Mysql.client_version < 50051 || (50100..50122).include?(Mysql.client_version))
- { 'id' => nil, 'name' => '', 'course_id' => nil }
- else
- { 'id' => nil, 'name' => nil, 'course_id' => nil }
- end
-
- column_defaults.each do |name, default|
+ %w(id name course_id).each do |name|
column = Entrant.columns_hash[name]
assert !column.null, "#{name} column should be NOT NULL"
- assert_equal default, column.default, "#{name} column should be DEFAULT #{default.inspect}"
+ assert_not column.default, "#{name} column should be DEFAULT 'nil'"
end
end
@@ -87,7 +80,7 @@ class DefaultStringsTest < ActiveRecord::TestCase
end
end
-if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+if current_adapter?(:Mysql2Adapter)
class DefaultsTestWithoutTransactionalFixtures < ActiveRecord::TestCase
# ActiveRecord::Base#create! (and #save and other related methods) will
# open a new transaction. When in transactional tests mode, this will
diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb
index 6686ce012d..9f90ab79a1 100644
--- a/activerecord/test/cases/finder_test.rb
+++ b/activerecord/test/cases/finder_test.rb
@@ -48,6 +48,75 @@ class FinderTest < ActiveRecord::TestCase
end
end
+ def test_find_with_ids_returning_ordered
+ records = Topic.find([4,2,5])
+ assert_equal 'The Fourth Topic of the day', records[0].title
+ assert_equal 'The Second Topic of the day', records[1].title
+ assert_equal 'The Fifth Topic of the day', records[2].title
+
+ records = Topic.find(4,2,5)
+ assert_equal 'The Fourth Topic of the day', records[0].title
+ assert_equal 'The Second Topic of the day', records[1].title
+ assert_equal 'The Fifth Topic of the day', records[2].title
+
+ records = Topic.find(['4','2','5'])
+ assert_equal 'The Fourth Topic of the day', records[0].title
+ assert_equal 'The Second Topic of the day', records[1].title
+ assert_equal 'The Fifth Topic of the day', records[2].title
+
+ records = Topic.find('4','2','5')
+ assert_equal 'The Fourth Topic of the day', records[0].title
+ assert_equal 'The Second Topic of the day', records[1].title
+ assert_equal 'The Fifth Topic of the day', records[2].title
+ end
+
+ def test_find_with_ids_and_order_clause
+ # The order clause takes precedence over the informed ids
+ records = Topic.order(:author_name).find([5,3,1])
+ assert_equal 'The Third Topic of the day', records[0].title
+ assert_equal 'The First Topic', records[1].title
+ assert_equal 'The Fifth Topic of the day', records[2].title
+
+ records = Topic.order(:id).find([5,3,1])
+ assert_equal 'The First Topic', records[0].title
+ assert_equal 'The Third Topic of the day', records[1].title
+ assert_equal 'The Fifth Topic of the day', records[2].title
+ end
+
+ def test_find_with_ids_with_limit_and_order_clause
+ # The order clause takes precedence over the informed ids
+ records = Topic.limit(2).order(:id).find([5,3,1])
+ assert_equal 2, records.size
+ assert_equal 'The First Topic', records[0].title
+ assert_equal 'The Third Topic of the day', records[1].title
+ end
+
+ def test_find_with_ids_and_limit
+ records = Topic.limit(3).find([3,2,5,1,4])
+ assert_equal 3, records.size
+ assert_equal 'The Third Topic of the day', records[0].title
+ assert_equal 'The Second Topic of the day', records[1].title
+ assert_equal 'The Fifth Topic of the day', records[2].title
+ end
+
+ def test_find_with_ids_where_and_limit
+ # Please note that Topic 1 is the only not approved so
+ # if it were among the first 3 it would raise a ActiveRecord::RecordNotFound
+ records = Topic.where(approved: true).limit(3).find([3,2,5,1,4])
+ assert_equal 3, records.size
+ assert_equal 'The Third Topic of the day', records[0].title
+ assert_equal 'The Second Topic of the day', records[1].title
+ assert_equal 'The Fifth Topic of the day', records[2].title
+ end
+
+ def test_find_with_ids_and_offset
+ records = Topic.offset(2).find([3,2,5,1,4])
+ assert_equal 3, records.size
+ assert_equal 'The Fifth Topic of the day', records[0].title
+ assert_equal 'The First Topic', records[1].title
+ assert_equal 'The Fourth Topic of the day', records[2].title
+ end
+
def test_find_passing_active_record_object_is_deprecated
assert_deprecated do
Topic.find(Topic.last)
@@ -195,7 +264,9 @@ class FinderTest < ActiveRecord::TestCase
def test_find_by_ids_with_limit_and_offset
assert_equal 2, Entrant.limit(2).find([1,3,2]).size
- assert_equal 1, Entrant.limit(3).offset(2).find([1,3,2]).size
+ entrants = Entrant.limit(3).offset(2).find([1,3,2])
+ assert_equal 1, entrants.size
+ assert_equal 'Ruby Guru', entrants.first.name
# Also test an edge case: If you have 11 results, and you set a
# limit of 3 and offset of 9, then you should find that there
@@ -203,6 +274,8 @@ class FinderTest < ActiveRecord::TestCase
devs = Developer.all
last_devs = Developer.limit(3).offset(9).find devs.map(&:id)
assert_equal 2, last_devs.size
+ assert_equal 'fixture_10', last_devs[0].name
+ assert_equal 'Jamis', last_devs[1].name
end
def test_find_with_large_number
@@ -434,9 +507,9 @@ class FinderTest < ActiveRecord::TestCase
end
def test_take_and_first_and_last_with_integer_should_use_sql_limit
- assert_sql(/LIMIT 3|ROWNUM <= 3/) { Topic.take(3).entries }
- assert_sql(/LIMIT 2|ROWNUM <= 2/) { Topic.first(2).entries }
- assert_sql(/LIMIT 5|ROWNUM <= 5/) { Topic.last(5).entries }
+ assert_sql(/LIMIT|ROWNUM <=/) { Topic.take(3).entries }
+ assert_sql(/LIMIT|ROWNUM <=/) { Topic.first(2).entries }
+ assert_sql(/LIMIT|ROWNUM <=/) { Topic.last(5).entries }
end
def test_last_with_integer_and_order_should_keep_the_order
@@ -706,96 +779,13 @@ class FinderTest < ActiveRecord::TestCase
assert Company.where(["name = :name", {name: "37signals' go'es agains"}]).first
end
- def test_bind_arity
- assert_nothing_raised { bind '' }
- assert_raise(ActiveRecord::PreparedStatementInvalid) { bind '', 1 }
-
- assert_raise(ActiveRecord::PreparedStatementInvalid) { bind '?' }
- assert_nothing_raised { bind '?', 1 }
- assert_raise(ActiveRecord::PreparedStatementInvalid) { bind '?', 1, 1 }
- end
-
def test_named_bind_variables
- assert_equal '1', bind(':a', :a => 1) # ' ruby-mode
- assert_equal '1 1', bind(':a :a', :a => 1) # ' ruby-mode
-
- assert_nothing_raised { bind("'+00:00'", :foo => "bar") }
-
assert_kind_of Firm, Company.where(["name = :name", { name: "37signals" }]).first
assert_nil Company.where(["name = :name", { name: "37signals!" }]).first
assert_nil Company.where(["name = :name", { name: "37signals!' OR 1=1" }]).first
assert_kind_of Time, Topic.where(["id = :id", { id: 1 }]).first.written_on
end
- def test_named_bind_arity
- assert_nothing_raised { bind "name = :name", { name: "37signals" } }
- assert_nothing_raised { bind "name = :name", { name: "37signals", id: 1 } }
- assert_raise(ActiveRecord::PreparedStatementInvalid) { bind "name = :name", { id: 1 } }
- end
-
- class SimpleEnumerable
- include Enumerable
-
- def initialize(ary)
- @ary = ary
- end
-
- def each(&b)
- @ary.each(&b)
- end
- end
-
- def test_bind_enumerable
- quoted_abc = %(#{ActiveRecord::Base.connection.quote('a')},#{ActiveRecord::Base.connection.quote('b')},#{ActiveRecord::Base.connection.quote('c')})
-
- assert_equal '1,2,3', bind('?', [1, 2, 3])
- assert_equal quoted_abc, bind('?', %w(a b c))
-
- assert_equal '1,2,3', bind(':a', :a => [1, 2, 3])
- assert_equal quoted_abc, bind(':a', :a => %w(a b c)) # '
-
- assert_equal '1,2,3', bind('?', SimpleEnumerable.new([1, 2, 3]))
- assert_equal quoted_abc, bind('?', SimpleEnumerable.new(%w(a b c)))
-
- assert_equal '1,2,3', bind(':a', :a => SimpleEnumerable.new([1, 2, 3]))
- assert_equal quoted_abc, bind(':a', :a => SimpleEnumerable.new(%w(a b c))) # '
- end
-
- def test_bind_empty_enumerable
- quoted_nil = ActiveRecord::Base.connection.quote(nil)
- assert_equal quoted_nil, bind('?', [])
- assert_equal " in (#{quoted_nil})", bind(' in (?)', [])
- assert_equal "foo in (#{quoted_nil})", bind('foo in (?)', [])
- end
-
- def test_bind_empty_string
- quoted_empty = ActiveRecord::Base.connection.quote('')
- assert_equal quoted_empty, bind('?', '')
- end
-
- def test_bind_chars
- quoted_bambi = ActiveRecord::Base.connection.quote("Bambi")
- quoted_bambi_and_thumper = ActiveRecord::Base.connection.quote("Bambi\nand\nThumper")
- assert_equal "name=#{quoted_bambi}", bind('name=?', "Bambi")
- assert_equal "name=#{quoted_bambi_and_thumper}", bind('name=?', "Bambi\nand\nThumper")
- assert_equal "name=#{quoted_bambi}", bind('name=?', "Bambi".mb_chars)
- assert_equal "name=#{quoted_bambi_and_thumper}", bind('name=?', "Bambi\nand\nThumper".mb_chars)
- end
-
- def test_bind_record
- o = Struct.new(:quoted_id).new(1)
- assert_equal '1', bind('?', o)
-
- os = [o] * 3
- assert_equal '1,1,1', bind('?', os)
- end
-
- def test_named_bind_with_postgresql_type_casts
- l = Proc.new { bind(":a::integer '2009-01-01'::date", :a => '10') }
- assert_nothing_raised(&l)
- assert_equal "#{ActiveRecord::Base.connection.quote('10')}::integer '2009-01-01'::date", l.call
- end
-
def test_string_sanitation
assert_not_equal "'something ' 1=1'", ActiveRecord::Base.sanitize("something ' 1=1")
assert_equal "'something; select table'", ActiveRecord::Base.sanitize("something; select table")
@@ -1136,14 +1126,6 @@ class FinderTest < ActiveRecord::TestCase
end
protected
- def bind(statement, *vars)
- if vars.first.is_a?(Hash)
- ActiveRecord::Base.send(:replace_named_bind_variables, statement, vars.first)
- else
- ActiveRecord::Base.send(:replace_bind_variables, statement, vars)
- end
- end
-
def table_with_custom_primary_key
yield(Class.new(Toy) do
def self.name
diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb
index f30ed4fcc8..c73958900b 100644
--- a/activerecord/test/cases/fixtures_test.rb
+++ b/activerecord/test/cases/fixtures_test.rb
@@ -184,7 +184,6 @@ class FixturesTest < ActiveRecord::TestCase
end
def test_fixtures_from_root_yml_with_instantiation
- # assert_equal 2, @accounts.size
assert_equal 50, @unknown.credit_limit
end
diff --git a/activerecord/test/cases/forbidden_attributes_protection_test.rb b/activerecord/test/cases/forbidden_attributes_protection_test.rb
index f4e7646f03..91921469b8 100644
--- a/activerecord/test/cases/forbidden_attributes_protection_test.rb
+++ b/activerecord/test/cases/forbidden_attributes_protection_test.rb
@@ -1,14 +1,20 @@
require 'cases/helper'
require 'active_support/core_ext/hash/indifferent_access'
-require 'models/person'
+
require 'models/company'
+require 'models/person'
+require 'models/ship'
+require 'models/ship_part'
+require 'models/treasure'
-class ProtectedParams < ActiveSupport::HashWithIndifferentAccess
+class ProtectedParams
attr_accessor :permitted
alias :permitted? :permitted
+ delegate :keys, :key?, :has_key?, :empty?, to: :@parameters
+
def initialize(attributes)
- super(attributes)
+ @parameters = attributes.with_indifferent_access
@permitted = false
end
@@ -17,6 +23,18 @@ class ProtectedParams < ActiveSupport::HashWithIndifferentAccess
self
end
+ def [](key)
+ @parameters[key]
+ end
+
+ def to_h
+ @parameters
+ end
+
+ def stringify_keys
+ dup
+ end
+
def dup
super.tap do |duplicate|
duplicate.instance_variable_set :@permitted, @permitted
@@ -75,6 +93,13 @@ class ForbiddenAttributesProtectionTest < ActiveRecord::TestCase
end
end
+ def test_create_with_works_with_permitted_params
+ params = ProtectedParams.new(first_name: 'Guille').permit!
+
+ person = Person.create_with(params).create!
+ assert_equal 'Guille', person.first_name
+ end
+
def test_create_with_works_with_params_values
params = ProtectedParams.new(first_name: 'Guille')
@@ -90,10 +115,51 @@ class ForbiddenAttributesProtectionTest < ActiveRecord::TestCase
end
end
+ def test_where_works_with_permitted_params
+ params = ProtectedParams.new(first_name: 'Guille').permit!
+
+ person = Person.where(params).create!
+ assert_equal 'Guille', person.first_name
+ end
+
def test_where_works_with_params_values
params = ProtectedParams.new(first_name: 'Guille')
person = Person.where(first_name: params[:first_name]).create!
assert_equal 'Guille', person.first_name
end
+
+ def test_where_not_checks_permitted
+ params = ProtectedParams.new(first_name: 'Guille', gender: 'm')
+
+ assert_raises(ActiveModel::ForbiddenAttributesError) do
+ Person.where().not(params)
+ end
+ end
+
+ def test_where_not_works_with_permitted_params
+ params = ProtectedParams.new(first_name: 'Guille').permit!
+ Person.create!(params)
+ assert_empty Person.where.not(params).select {|p| p.first_name == 'Guille' }
+ end
+
+ def test_strong_params_style_objects_work_with_singular_associations
+ params = ProtectedParams.new( name: "Stern", ship_attributes: ProtectedParams.new(name: "The Black Rock").permit!).permit!
+ part = ShipPart.new(params)
+
+ assert_equal "Stern", part.name
+ assert_equal "The Black Rock", part.ship.name
+ end
+
+ def test_strong_params_style_objects_work_with_collection_associations
+ params = ProtectedParams.new(
+ trinkets_attributes: ProtectedParams.new(
+ "0" => ProtectedParams.new(name: "Necklace").permit!,
+ "1" => ProtectedParams.new(name: "Spoon").permit! ) ).permit!
+ part = ShipPart.new(params)
+
+ assert_equal "Necklace", part.trinkets[0].name
+ assert_equal "Spoon", part.trinkets[1].name
+ end
+
end
diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb
index d82a3040fc..95f8706d73 100644
--- a/activerecord/test/cases/helper.rb
+++ b/activerecord/test/cases/helper.rb
@@ -47,11 +47,11 @@ def in_memory_db?
end
def subsecond_precision_supported?
- !current_adapter?(:MysqlAdapter, :Mysql2Adapter) || ActiveRecord::Base.connection.version >= '5.6.4'
+ ActiveRecord::Base.connection.supports_datetime_with_precision?
end
def mysql_enforcing_gtid_consistency?
- current_adapter?(:MysqlAdapter, :Mysql2Adapter) && 'ON' == ActiveRecord::Base.connection.show_variable('enforce_gtid_consistency')
+ current_adapter?(:Mysql2Adapter) && 'ON' == ActiveRecord::Base.connection.show_variable('enforce_gtid_consistency')
end
def supports_savepoints?
diff --git a/activerecord/test/cases/inheritance_test.rb b/activerecord/test/cases/inheritance_test.rb
index 52e3734dd0..03bce547da 100644
--- a/activerecord/test/cases/inheritance_test.rb
+++ b/activerecord/test/cases/inheritance_test.rb
@@ -478,4 +478,49 @@ class InheritanceComputeTypeTest < ActiveRecord::TestCase
product = Shop::Product.new(:type => phone)
assert product.save
end
+
+ def test_inheritance_new_with_subclass_as_default
+ original_type = Company.columns_hash["type"].default
+ ActiveRecord::Base.connection.change_column_default :companies, :type, 'Firm'
+ Company.reset_column_information
+
+ firm = Company.new # without arguments
+ assert_equal 'Firm', firm.type
+ assert_instance_of Firm, firm
+
+ firm = Company.new(firm_name: 'Shri Hans Plastic') # with arguments
+ assert_equal 'Firm', firm.type
+ assert_instance_of Firm, firm
+
+ firm = Company.new(type: 'Client') # overwrite the default type
+ assert_equal 'Client', firm.type
+ assert_instance_of Client, firm
+ ensure
+ ActiveRecord::Base.connection.change_column_default :companies, :type, original_type
+ Company.reset_column_information
+ end
+end
+
+class InheritanceAttributeTest < ActiveRecord::TestCase
+
+ class Company < ActiveRecord::Base
+ self.table_name = 'companies'
+ attribute :type, :string, default: "InheritanceAttributeTest::Startup"
+ end
+
+ class Startup < Company
+ end
+
+ class Empire < Company
+ end
+
+ def test_inheritance_new_with_subclass_as_default
+ startup = Company.new # without arguments
+ assert_equal 'InheritanceAttributeTest::Startup', startup.type
+ assert_instance_of Startup, startup
+
+ empire = Company.new(type: 'InheritanceAttributeTest::Empire') # without arguments
+ assert_equal 'InheritanceAttributeTest::Empire', empire.type
+ assert_instance_of Empire, empire
+ end
end
diff --git a/activerecord/test/cases/invalid_connection_test.rb b/activerecord/test/cases/invalid_connection_test.rb
index 6523fc29fd..c26623e3ca 100644
--- a/activerecord/test/cases/invalid_connection_test.rb
+++ b/activerecord/test/cases/invalid_connection_test.rb
@@ -9,7 +9,7 @@ class TestAdapterWithInvalidConnection < ActiveRecord::TestCase
def setup
# Can't just use current adapter; sqlite3 will create a database
# file on the fly.
- Bird.establish_connection adapter: 'mysql', database: 'i_do_not_exist'
+ Bird.establish_connection adapter: 'mysql2', database: 'i_do_not_exist'
end
teardown do
diff --git a/activerecord/test/cases/invertible_migration_test.rb b/activerecord/test/cases/invertible_migration_test.rb
index 0da58040c8..e030f6c588 100644
--- a/activerecord/test/cases/invertible_migration_test.rb
+++ b/activerecord/test/cases/invertible_migration_test.rb
@@ -5,7 +5,7 @@ end
module ActiveRecord
class InvertibleMigrationTest < ActiveRecord::TestCase
- class SilentMigration < ActiveRecord::Migration
+ class SilentMigration < ActiveRecord::Migration::Current
def write(text = '')
# sssshhhhh!!
end
@@ -105,7 +105,7 @@ module ActiveRecord
end
end
- class LegacyMigration < ActiveRecord::Migration
+ class LegacyMigration < ActiveRecord::Migration::Current
def self.up
create_table("horses") do |t|
t.column :content, :text
@@ -354,7 +354,7 @@ module ActiveRecord
end
# MySQL 5.7 and Oracle do not allow to create duplicate indexes on the same columns
- unless current_adapter?(:MysqlAdapter, :Mysql2Adapter, :OracleAdapter)
+ unless current_adapter?(:Mysql2Adapter, :OracleAdapter)
def test_migrate_revert_add_index_with_name
RevertNamedIndexMigration1.new.migrate(:up)
RevertNamedIndexMigration2.new.migrate(:up)
diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb
index 2e1363334d..4fe76e563a 100644
--- a/activerecord/test/cases/locking_test.rb
+++ b/activerecord/test/cases/locking_test.rb
@@ -441,7 +441,7 @@ unless in_memory_db?
def test_lock_sending_custom_lock_statement
Person.transaction do
person = Person.find(1)
- assert_sql(/LIMIT 1 FOR SHARE NOWAIT/) do
+ assert_sql(/LIMIT \$\d FOR SHARE NOWAIT/) do
person.lock!('FOR SHARE NOWAIT')
end
end
diff --git a/activerecord/test/cases/migration/change_schema_test.rb b/activerecord/test/cases/migration/change_schema_test.rb
index 2ff9cf8cf5..d6963b48d7 100644
--- a/activerecord/test/cases/migration/change_schema_test.rb
+++ b/activerecord/test/cases/migration/change_schema_test.rb
@@ -50,7 +50,7 @@ module ActiveRecord
def test_create_table_with_defaults
# MySQL doesn't allow defaults on TEXT or BLOB columns.
- mysql = current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ mysql = current_adapter?(:Mysql2Adapter)
connection.create_table :testings do |t|
t.column :one, :string, :default => "hello"
@@ -141,7 +141,7 @@ module ActiveRecord
assert_equal 'smallint', one.sql_type
assert_equal 'integer', four.sql_type
assert_equal 'bigint', eight.sql_type
- elsif current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ elsif current_adapter?(:Mysql2Adapter)
assert_match 'int(11)', default.sql_type
assert_match 'tinyint', one.sql_type
assert_match 'int', four.sql_type
@@ -339,7 +339,7 @@ module ActiveRecord
def test_change_column_null
testing_table_with_only_foo_attribute do
- notnull_migration = Class.new(ActiveRecord::Migration) do
+ notnull_migration = Class.new(ActiveRecord::Migration::Current) do
def change
change_column_null :testings, :foo, false
end
@@ -442,7 +442,7 @@ module ActiveRecord
end
def test_create_table_with_force_cascade_drops_dependent_objects
- skip "MySQL > 5.5 does not drop dependent objects with DROP TABLE CASCADE" if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ skip "MySQL > 5.5 does not drop dependent objects with DROP TABLE CASCADE" if current_adapter?(:Mysql2Adapter)
# can't re-create table referenced by foreign key
assert_raises(ActiveRecord::StatementInvalid) do
@connection.create_table :trains, force: true
diff --git a/activerecord/test/cases/migration/column_attributes_test.rb b/activerecord/test/cases/migration/column_attributes_test.rb
index 8d8e661aa5..d0940b3937 100644
--- a/activerecord/test/cases/migration/column_attributes_test.rb
+++ b/activerecord/test/cases/migration/column_attributes_test.rb
@@ -37,13 +37,13 @@ module ActiveRecord
def test_add_column_without_limit
# TODO: limit: nil should work with all adapters.
- skip "MySQL wrongly enforces a limit of 255" if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ skip "MySQL wrongly enforces a limit of 255" if current_adapter?(:Mysql2Adapter)
add_column :test_models, :description, :string, limit: nil
TestModel.reset_column_information
assert_nil TestModel.columns_hash["description"].limit
end
- if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ if current_adapter?(:Mysql2Adapter)
def test_unabstracted_database_dependent_types
add_column :test_models, :intelligence_quotient, :tinyint
TestModel.reset_column_information
@@ -171,7 +171,7 @@ module ActiveRecord
end
end
- if current_adapter?(:MysqlAdapter, :Mysql2Adapter, :PostgreSQLAdapter)
+ if current_adapter?(:Mysql2Adapter, :PostgreSQLAdapter)
def test_out_of_range_limit_should_raise
assert_raise(ActiveRecordError) { add_column :test_models, :integer_too_big, :integer, :limit => 10 }
diff --git a/activerecord/test/cases/migration/column_positioning_test.rb b/activerecord/test/cases/migration/column_positioning_test.rb
index 4637970ce0..8294da0373 100644
--- a/activerecord/test/cases/migration/column_positioning_test.rb
+++ b/activerecord/test/cases/migration/column_positioning_test.rb
@@ -23,7 +23,7 @@ module ActiveRecord
ActiveRecord::Base.primary_key_prefix_type = nil
end
- if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ if current_adapter?(:Mysql2Adapter)
def test_column_positioning
assert_equal %w(first second third), conn.columns(:testings).map(&:name)
end
diff --git a/activerecord/test/cases/migration/columns_test.rb b/activerecord/test/cases/migration/columns_test.rb
index ab3f584350..fca1cb7e97 100644
--- a/activerecord/test/cases/migration/columns_test.rb
+++ b/activerecord/test/cases/migration/columns_test.rb
@@ -62,7 +62,7 @@ module ActiveRecord
assert_equal '70000', default_after
end
- if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ if current_adapter?(:Mysql2Adapter)
def test_mysql_rename_column_preserves_auto_increment
rename_column "test_models", "id", "id_test"
assert connection.columns("test_models").find { |c| c.name == "id_test" }.auto_increment?
diff --git a/activerecord/test/cases/migration/compatibility_test.rb b/activerecord/test/cases/migration/compatibility_test.rb
new file mode 100644
index 0000000000..267d2fcccc
--- /dev/null
+++ b/activerecord/test/cases/migration/compatibility_test.rb
@@ -0,0 +1,42 @@
+require 'cases/helper'
+
+module ActiveRecord
+ class Migration
+ class CompatibilityTest < ActiveRecord::TestCase
+ attr_reader :connection
+ self.use_transactional_tests = false
+
+ def setup
+ super
+ @connection = ActiveRecord::Base.connection
+ @verbose_was = ActiveRecord::Migration.verbose
+ ActiveRecord::Migration.verbose = false
+
+ connection.create_table :testings do |t|
+ t.column :foo, :string, :limit => 100
+ t.column :bar, :string, :limit => 100
+ end
+ end
+
+ teardown do
+ connection.drop_table :testings rescue nil
+ ActiveRecord::Migration.verbose = @verbose_was
+ end
+
+ def test_migration_doesnt_remove_named_index
+ connection.add_index :testings, :foo, :name => "custom_index_name"
+
+ migration = Class.new(ActiveRecord::Migration[4.2]) {
+ def version; 101 end
+ def migrate(x)
+ remove_index :testings, :foo
+ end
+ }.new
+
+ assert connection.index_exists?(:testings, :foo, name: "custom_index_name")
+ assert_raise(StandardError) { ActiveRecord::Migrator.new(:up, [migration]).migrate }
+ assert connection.index_exists?(:testings, :foo, name: "custom_index_name")
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/migration/foreign_key_test.rb b/activerecord/test/cases/migration/foreign_key_test.rb
index 72f2fa95f1..01162dcefe 100644
--- a/activerecord/test/cases/migration/foreign_key_test.rb
+++ b/activerecord/test/cases/migration/foreign_key_test.rb
@@ -99,7 +99,7 @@ module ActiveRecord
assert_equal 1, foreign_keys.size
fk = foreign_keys.first
- if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ if current_adapter?(:Mysql2Adapter)
# ON DELETE RESTRICT is the default on MySQL
assert_equal nil, fk.on_delete
else
@@ -224,7 +224,7 @@ module ActiveRecord
assert_match %r{\s+add_foreign_key "astronauts",.+on_update: :cascade,.+on_delete: :nullify$}, output
end
- class CreateCitiesAndHousesMigration < ActiveRecord::Migration
+ class CreateCitiesAndHousesMigration < ActiveRecord::Migration::Current
def change
create_table("cities") { |t| }
@@ -243,7 +243,7 @@ module ActiveRecord
silence_stream($stdout) { migration.migrate(:down) }
end
- class CreateSchoolsAndClassesMigration < ActiveRecord::Migration
+ class CreateSchoolsAndClassesMigration < ActiveRecord::Migration::Current
def change
create_table(:schools)
diff --git a/activerecord/test/cases/migration/index_test.rb b/activerecord/test/cases/migration/index_test.rb
index b23b9a679f..5abd37bfa2 100644
--- a/activerecord/test/cases/migration/index_test.rb
+++ b/activerecord/test/cases/migration/index_test.rb
@@ -130,7 +130,17 @@ module ActiveRecord
def test_named_index_exists
connection.add_index :testings, :foo, :name => "custom_index_name"
+ assert connection.index_exists?(:testings, :foo)
assert connection.index_exists?(:testings, :foo, :name => "custom_index_name")
+ assert !connection.index_exists?(:testings, :foo, :name => "other_index_name")
+ end
+
+ def test_remove_named_index
+ connection.add_index :testings, :foo, :name => "custom_index_name"
+
+ assert connection.index_exists?(:testings, :foo)
+ connection.remove_index :testings, :foo
+ assert !connection.index_exists?(:testings, :foo)
end
def test_add_index_attribute_length_limit
@@ -176,7 +186,7 @@ module ActiveRecord
connection.remove_index("testings", :name => "named_admin")
# Selected adapters support index sort order
- if current_adapter?(:SQLite3Adapter, :MysqlAdapter, :Mysql2Adapter, :PostgreSQLAdapter)
+ if current_adapter?(:SQLite3Adapter, :Mysql2Adapter, :PostgreSQLAdapter)
connection.add_index("testings", ["last_name"], :order => {:last_name => :desc})
connection.remove_index("testings", ["last_name"])
connection.add_index("testings", ["last_name", "first_name"], :order => {:last_name => :desc})
diff --git a/activerecord/test/cases/migration/postgresql_geometric_types_test.rb b/activerecord/test/cases/migration/postgresql_geometric_types_test.rb
deleted file mode 100644
index e4772905bb..0000000000
--- a/activerecord/test/cases/migration/postgresql_geometric_types_test.rb
+++ /dev/null
@@ -1,93 +0,0 @@
-require 'cases/helper'
-
-module ActiveRecord
- class Migration
- class PostgreSQLGeometricTypesTest < ActiveRecord::TestCase
- attr_reader :connection, :table_name
-
- def setup
- super
- @connection = ActiveRecord::Base.connection
- @table_name = :testings
- end
-
- if current_adapter?(:PostgreSQLAdapter)
- def test_creating_column_with_point_type
- connection.create_table(table_name) do |t|
- t.point :foo_point
- end
-
- assert_column_exists(:foo_point)
- assert_type_correct(:foo_point, :point)
- end
-
- def test_creating_column_with_line_type
- connection.create_table(table_name) do |t|
- t.line :foo_line
- end
-
- assert_column_exists(:foo_line)
- assert_type_correct(:foo_line, :line)
- end
-
- def test_creating_column_with_lseg_type
- connection.create_table(table_name) do |t|
- t.lseg :foo_lseg
- end
-
- assert_column_exists(:foo_lseg)
- assert_type_correct(:foo_lseg, :lseg)
- end
-
- def test_creating_column_with_box_type
- connection.create_table(table_name) do |t|
- t.box :foo_box
- end
-
- assert_column_exists(:foo_box)
- assert_type_correct(:foo_box, :box)
- end
-
- def test_creating_column_with_path_type
- connection.create_table(table_name) do |t|
- t.path :foo_path
- end
-
- assert_column_exists(:foo_path)
- assert_type_correct(:foo_path, :path)
- end
-
- def test_creating_column_with_polygon_type
- connection.create_table(table_name) do |t|
- t.polygon :foo_polygon
- end
-
- assert_column_exists(:foo_polygon)
- assert_type_correct(:foo_polygon, :polygon)
- end
-
- def test_creating_column_with_circle_type
- connection.create_table(table_name) do |t|
- t.circle :foo_circle
- end
-
- assert_column_exists(:foo_circle)
- assert_type_correct(:foo_circle, :circle)
- end
- end
-
- private
- def assert_column_exists(column_name)
- columns = connection.columns(table_name)
- assert columns.map(&:name).include?(column_name.to_s)
- end
-
- def assert_type_correct(column_name, type)
- columns = connection.columns(table_name)
- column = columns.select{ |c| c.name == column_name.to_s }.first
- assert_equal type.to_s, column.sql_type
- end
-
- end
- end
-end \ No newline at end of file
diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb
index 15a0e0516d..b5b241ad1a 100644
--- a/activerecord/test/cases/migration_test.rb
+++ b/activerecord/test/cases/migration_test.rb
@@ -132,12 +132,12 @@ class MigrationTest < ActiveRecord::TestCase
end
def test_migration_instance_has_connection
- migration = Class.new(ActiveRecord::Migration).new
+ migration = Class.new(ActiveRecord::Migration::Current).new
assert_equal ActiveRecord::Base.connection, migration.connection
end
def test_method_missing_delegates_to_connection
- migration = Class.new(ActiveRecord::Migration) {
+ migration = Class.new(ActiveRecord::Migration::Current) {
def connection
Class.new {
def create_table; "hi mom!"; end
@@ -226,7 +226,7 @@ class MigrationTest < ActiveRecord::TestCase
assert_raise(ActiveRecord::StatementInvalid) { Reminder.first }
end
- class MockMigration < ActiveRecord::Migration
+ class MockMigration < ActiveRecord::Migration::Current
attr_reader :went_up, :went_down
def initialize
@went_up = false
@@ -268,7 +268,7 @@ class MigrationTest < ActiveRecord::TestCase
def test_migrator_one_up_with_exception_and_rollback
assert_no_column Person, :last_name
- migration = Class.new(ActiveRecord::Migration) {
+ migration = Class.new(ActiveRecord::Migration::Current) {
def version; 100 end
def migrate(x)
add_column "people", "last_name", :string
@@ -289,7 +289,7 @@ class MigrationTest < ActiveRecord::TestCase
def test_migrator_one_up_with_exception_and_rollback_using_run
assert_no_column Person, :last_name
- migration = Class.new(ActiveRecord::Migration) {
+ migration = Class.new(ActiveRecord::Migration::Current) {
def version; 100 end
def migrate(x)
add_column "people", "last_name", :string
@@ -310,7 +310,7 @@ class MigrationTest < ActiveRecord::TestCase
def test_migration_without_transaction
assert_no_column Person, :last_name
- migration = Class.new(ActiveRecord::Migration) {
+ migration = Class.new(ActiveRecord::Migration::Current) {
self.disable_ddl_transaction!
def version; 101 end
@@ -500,7 +500,7 @@ class MigrationTest < ActiveRecord::TestCase
end
end
- if current_adapter?(:MysqlAdapter, :Mysql2Adapter, :PostgreSQLAdapter)
+ if current_adapter?(:Mysql2Adapter, :PostgreSQLAdapter)
def test_out_of_range_limit_should_raise
Person.connection.drop_table :test_limits rescue nil
e = assert_raise(ActiveRecord::ActiveRecordError, "integer limit didn't raise") do
@@ -524,39 +524,38 @@ class MigrationTest < ActiveRecord::TestCase
end
if ActiveRecord::Base.connection.supports_advisory_locks?
- def test_migrator_generates_valid_lock_key
- migration = Class.new(ActiveRecord::Migration).new
+ def test_migrator_generates_valid_lock_id
+ migration = Class.new(ActiveRecord::Migration::Current).new
migrator = ActiveRecord::Migrator.new(:up, [migration], 100)
- lock_key = migrator.send(:generate_migrator_advisory_lock_key)
+ lock_id = migrator.send(:generate_migrator_advisory_lock_id)
- assert ActiveRecord::Base.connection.get_advisory_lock(lock_key),
- "the Migrator should have generated a valid lock key, but it didn't"
- assert ActiveRecord::Base.connection.release_advisory_lock(lock_key),
- "the Migrator should have generated a valid lock key, but it didn't"
+ assert ActiveRecord::Base.connection.get_advisory_lock(lock_id),
+ "the Migrator should have generated a valid lock id, but it didn't"
+ assert ActiveRecord::Base.connection.release_advisory_lock(lock_id),
+ "the Migrator should have generated a valid lock id, but it didn't"
end
- def test_generate_migrator_advisory_lock_key
+ def test_generate_migrator_advisory_lock_id
# It is important we are consistent with how we generate this so that
# exclusive locking works across migrator versions
- migration = Class.new(ActiveRecord::Migration).new
+ migration = Class.new(ActiveRecord::Migration::Current).new
migrator = ActiveRecord::Migrator.new(:up, [migration], 100)
- lock_key = migrator.send(:generate_migrator_advisory_lock_key)
+ lock_id = migrator.send(:generate_migrator_advisory_lock_id)
current_database = ActiveRecord::Base.connection.current_database
salt = ActiveRecord::Migrator::MIGRATOR_SALT
- expected_key = Zlib.crc32(current_database) * salt
+ expected_id = Zlib.crc32(current_database) * salt
- assert lock_key == expected_key, "expected lock key generated by the migrator to be #{expected_key}, but it was #{lock_key} instead"
- assert lock_key.is_a?(Fixnum), "expected lock key to be a Fixnum, but it wasn't"
- assert lock_key.bit_length <= 63, "lock key must be a signed integer of max 63 bits magnitude"
+ assert lock_id == expected_id, "expected lock id generated by the migrator to be #{expected_id}, but it was #{lock_id} instead"
+ assert lock_id.bit_length <= 63, "lock id must be a signed integer of max 63 bits magnitude"
end
def test_migrator_one_up_with_unavailable_lock
assert_no_column Person, :last_name
- migration = Class.new(ActiveRecord::Migration) {
+ migration = Class.new(ActiveRecord::Migration::Current) {
def version; 100 end
def migrate(x)
add_column "people", "last_name", :string
@@ -564,9 +563,9 @@ class MigrationTest < ActiveRecord::TestCase
}.new
migrator = ActiveRecord::Migrator.new(:up, [migration], 100)
- lock_key = migrator.send(:generate_migrator_advisory_lock_key)
+ lock_id = migrator.send(:generate_migrator_advisory_lock_id)
- with_another_process_holding_lock(lock_key) do
+ with_another_process_holding_lock(lock_id) do
assert_raise(ActiveRecord::ConcurrentMigrationError) { migrator.migrate }
end
@@ -577,7 +576,7 @@ class MigrationTest < ActiveRecord::TestCase
def test_migrator_one_up_with_unavailable_lock_using_run
assert_no_column Person, :last_name
- migration = Class.new(ActiveRecord::Migration) {
+ migration = Class.new(ActiveRecord::Migration::Current) {
def version; 100 end
def migrate(x)
add_column "people", "last_name", :string
@@ -585,9 +584,9 @@ class MigrationTest < ActiveRecord::TestCase
}.new
migrator = ActiveRecord::Migrator.new(:up, [migration], 100)
- lock_key = migrator.send(:generate_migrator_advisory_lock_key)
+ lock_id = migrator.send(:generate_migrator_advisory_lock_id)
- with_another_process_holding_lock(lock_key) do
+ with_another_process_holding_lock(lock_id) do
assert_raise(ActiveRecord::ConcurrentMigrationError) { migrator.run }
end
@@ -606,18 +605,18 @@ class MigrationTest < ActiveRecord::TestCase
}
end
- def with_another_process_holding_lock(lock_key)
+ def with_another_process_holding_lock(lock_id)
thread_lock = Concurrent::CountDownLatch.new
test_terminated = Concurrent::CountDownLatch.new
other_process = Thread.new do
begin
conn = ActiveRecord::Base.connection_pool.checkout
- conn.get_advisory_lock(lock_key)
+ conn.get_advisory_lock(lock_id)
thread_lock.count_down
test_terminated.wait # hold the lock open until we tested everything
ensure
- conn.release_advisory_lock(lock_key)
+ conn.release_advisory_lock(lock_id)
ActiveRecord::Base.connection_pool.checkin(conn)
end
end
diff --git a/activerecord/test/cases/migrator_test.rb b/activerecord/test/cases/migrator_test.rb
index dbf088f455..86eca53141 100644
--- a/activerecord/test/cases/migrator_test.rb
+++ b/activerecord/test/cases/migrator_test.rb
@@ -6,7 +6,7 @@ class MigratorTest < ActiveRecord::TestCase
# Use this class to sense if migrations have gone
# up or down.
- class Sensor < ActiveRecord::Migration
+ class Sensor < ActiveRecord::Migration::Current
attr_reader :went_up, :went_down
def initialize name = self.class.name, version = nil
diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb
index 93cb631a04..0b700afcb4 100644
--- a/activerecord/test/cases/nested_attributes_test.rb
+++ b/activerecord/test/cases/nested_attributes_test.rb
@@ -1068,39 +1068,4 @@ class TestHasManyAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveR
assert_not part.valid?
assert_equal ["Ship name can't be blank"], part.errors.full_messages
end
-
- class ProtectedParameters
- def initialize(hash)
- @hash = hash
- end
-
- def permitted?
- true
- end
-
- def [](key)
- @hash[key]
- end
-
- def to_h
- @hash
- end
- end
-
- test "strong params style objects can be assigned for singular associations" do
- params = { name: "Stern", ship_attributes:
- ProtectedParameters.new(name: "The Black Rock") }
- part = ShipPart.new(params)
-
- assert_equal "Stern", part.name
- assert_equal "The Black Rock", part.ship.name
- end
-
- test "strong params style objects can be assigned for collection associations" do
- params = { trinkets_attributes: ProtectedParameters.new("0" => ProtectedParameters.new(name: "Necklace"), "1" => ProtectedParameters.new(name: "Spoon")) }
- part = ShipPart.new(params)
-
- assert_equal "Necklace", part.trinkets[0].name
- assert_equal "Spoon", part.trinkets[1].name
- end
end
diff --git a/activerecord/test/cases/persistence_test.rb b/activerecord/test/cases/persistence_test.rb
index b2e59e3970..af15e63d9c 100644
--- a/activerecord/test/cases/persistence_test.rb
+++ b/activerecord/test/cases/persistence_test.rb
@@ -19,6 +19,8 @@ require 'models/person'
require 'models/pet'
require 'models/ship'
require 'models/toy'
+require 'models/admin'
+require 'models/admin/user'
require 'rexml/document'
class PersistenceTest < ActiveRecord::TestCase
@@ -161,7 +163,24 @@ class PersistenceTest < ActiveRecord::TestCase
assert !company.valid?
original_errors = company.errors
client = company.becomes(Client)
- assert_equal original_errors, client.errors
+ assert_equal original_errors.keys, client.errors.keys
+ end
+
+ def test_becomes_errors_base
+ child_class = Class.new(Admin::User) do
+ store_accessor :settings, :foo
+
+ def self.name; 'Admin::ChildUser'; end
+ end
+
+ admin = Admin::User.new
+ admin.errors.add :token, :invalid
+ child = admin.becomes(child_class)
+
+ assert_equal [:token], child.errors.keys
+ assert_nothing_raised do
+ child.errors.add :foo, :invalid
+ end
end
def test_dupd_becomes_persists_changes_from_the_original
diff --git a/activerecord/test/cases/primary_keys_test.rb b/activerecord/test/cases/primary_keys_test.rb
index d883784553..7e18313c00 100644
--- a/activerecord/test/cases/primary_keys_test.rb
+++ b/activerecord/test/cases/primary_keys_test.rb
@@ -268,7 +268,7 @@ class CompositePrimaryKeyTest < ActiveRecord::TestCase
end
end
-if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+if current_adapter?(:Mysql2Adapter)
class PrimaryKeyWithAnsiQuotesTest < ActiveRecord::TestCase
self.use_transactional_tests = false
@@ -308,7 +308,7 @@ if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
end
end
-if current_adapter?(:PostgreSQLAdapter, :MysqlAdapter, :Mysql2Adapter)
+if current_adapter?(:PostgreSQLAdapter, :Mysql2Adapter)
class PrimaryKeyBigSerialTest < ActiveRecord::TestCase
include SchemaDumpingHelper
@@ -351,7 +351,7 @@ if current_adapter?(:PostgreSQLAdapter, :MysqlAdapter, :Mysql2Adapter)
end
end
- if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ if current_adapter?(:Mysql2Adapter)
test "primary key column type with options" do
@connection.create_table(:widgets, id: :primary_key, limit: 8, unsigned: true, force: true)
column = @connection.columns(:widgets).find { |c| c.name == 'id' }
diff --git a/activerecord/test/cases/relation/delegation_test.rb b/activerecord/test/cases/relation/delegation_test.rb
index 989f4e1e5d..f0e07e0731 100644
--- a/activerecord/test/cases/relation/delegation_test.rb
+++ b/activerecord/test/cases/relation/delegation_test.rb
@@ -27,7 +27,7 @@ module ActiveRecord
module DelegationWhitelistBlacklistTests
ARRAY_DELEGATES = [
- :+, :-, :|, :&, :[],
+ :+, :-, :|, :&, :[], :shuffle,
:all?, :collect, :compact, :detect, :each, :each_cons, :each_with_index,
:exclude?, :find_all, :flat_map, :group_by, :include?, :length,
:map, :none?, :one?, :partition, :reject, :reverse,
@@ -40,12 +40,6 @@ module ActiveRecord
assert_respond_to target, method
end
end
-
- ActiveRecord::Delegation::BLACKLISTED_ARRAY_METHODS.each do |method|
- define_method "test_#{method}_is_not_delegated_to_Array" do
- assert_raises(NoMethodError) { call_method(target, method) }
- end
- end
end
class DelegationAssociationTest < DelegationTest
diff --git a/activerecord/test/cases/relation_test.rb b/activerecord/test/cases/relation_test.rb
index 8794bc8043..f46d414b95 100644
--- a/activerecord/test/cases/relation_test.rb
+++ b/activerecord/test/cases/relation_test.rb
@@ -235,6 +235,13 @@ module ActiveRecord
assert_equal 3, relation.where(id: post.id).pluck(:id).size
end
+ def test_merge_raises_with_invalid_argument
+ assert_raises ArgumentError do
+ relation = Relation.new(FakeKlass, :b, nil)
+ relation.merge(true)
+ end
+ end
+
def test_respond_to_for_non_selected_element
post = Post.select(:title).first
assert_equal false, post.respond_to?(:body), "post should not respond_to?(:body) since invoking it raises exception"
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index cd23c1b3e1..7149c7d072 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -18,6 +18,7 @@ require 'models/minivan'
require 'models/aircraft'
require "models/possession"
require "models/reader"
+require "models/categorization"
class RelationTest < ActiveRecord::TestCase
fixtures :authors, :topics, :entrants, :developers, :companies, :developers_projects, :accounts, :categories, :categorizations, :posts, :comments,
@@ -918,6 +919,12 @@ class RelationTest < ActiveRecord::TestCase
assert authors.exists?(authors(:david).id)
end
+ def test_any_with_scope_on_hash_includes
+ post = authors(:david).posts.first
+ categories = Categorization.includes(author: :posts).where(posts: { id: post.id })
+ assert categories.exists?
+ end
+
def test_last
authors = Author.all
assert_equal authors(:bob), authors.last
diff --git a/activerecord/test/cases/sanitize_test.rb b/activerecord/test/cases/sanitize_test.rb
index 14e392ac30..239f63d27b 100644
--- a/activerecord/test/cases/sanitize_test.rb
+++ b/activerecord/test/cases/sanitize_test.rb
@@ -25,6 +25,16 @@ class SanitizeTest < ActiveRecord::TestCase
assert_equal "name=#{quoted_bambi_and_thumper}", Binary.send(:sanitize_sql_array, ["name=?", "Bambi\nand\nThumper".mb_chars])
end
+ def test_sanitize_sql_array_handles_named_bind_variables
+ quoted_bambi = ActiveRecord::Base.connection.quote("Bambi")
+ assert_equal "name=#{quoted_bambi}", Binary.send(:sanitize_sql_array, ["name=:name", name: "Bambi"])
+ assert_equal "name=#{quoted_bambi} AND id=1", Binary.send(:sanitize_sql_array, ["name=:name AND id=:id", name: "Bambi", id: 1])
+
+ quoted_bambi_and_thumper = ActiveRecord::Base.connection.quote("Bambi\nand\nThumper")
+ assert_equal "name=#{quoted_bambi_and_thumper}", Binary.send(:sanitize_sql_array, ["name=:name", name: "Bambi\nand\nThumper"])
+ assert_equal "name=#{quoted_bambi_and_thumper} AND name2=#{quoted_bambi_and_thumper}", Binary.send(:sanitize_sql_array, ["name=:name AND name2=:name", name: "Bambi\nand\nThumper"])
+ end
+
def test_sanitize_sql_array_handles_relations
david = Author.create!(name: 'David')
david_posts = david.posts.select(:id)
@@ -69,4 +79,98 @@ class SanitizeTest < ActiveRecord::TestCase
searchable_post.search("20% _reduction_!").to_a
end
end
+
+ def test_bind_arity
+ assert_nothing_raised { bind '' }
+ assert_raise(ActiveRecord::PreparedStatementInvalid) { bind '', 1 }
+
+ assert_raise(ActiveRecord::PreparedStatementInvalid) { bind '?' }
+ assert_nothing_raised { bind '?', 1 }
+ assert_raise(ActiveRecord::PreparedStatementInvalid) { bind '?', 1, 1 }
+ end
+
+ def test_named_bind_variables
+ assert_equal '1', bind(':a', :a => 1) # ' ruby-mode
+ assert_equal '1 1', bind(':a :a', :a => 1) # ' ruby-mode
+
+ assert_nothing_raised { bind("'+00:00'", :foo => "bar") }
+ end
+
+ def test_named_bind_arity
+ assert_nothing_raised { bind "name = :name", { name: "37signals" } }
+ assert_nothing_raised { bind "name = :name", { name: "37signals", id: 1 } }
+ assert_raise(ActiveRecord::PreparedStatementInvalid) { bind "name = :name", { id: 1 } }
+ end
+
+ class SimpleEnumerable
+ include Enumerable
+
+ def initialize(ary)
+ @ary = ary
+ end
+
+ def each(&b)
+ @ary.each(&b)
+ end
+ end
+
+ def test_bind_enumerable
+ quoted_abc = %(#{ActiveRecord::Base.connection.quote('a')},#{ActiveRecord::Base.connection.quote('b')},#{ActiveRecord::Base.connection.quote('c')})
+
+ assert_equal '1,2,3', bind('?', [1, 2, 3])
+ assert_equal quoted_abc, bind('?', %w(a b c))
+
+ assert_equal '1,2,3', bind(':a', :a => [1, 2, 3])
+ assert_equal quoted_abc, bind(':a', :a => %w(a b c)) # '
+
+ assert_equal '1,2,3', bind('?', SimpleEnumerable.new([1, 2, 3]))
+ assert_equal quoted_abc, bind('?', SimpleEnumerable.new(%w(a b c)))
+
+ assert_equal '1,2,3', bind(':a', :a => SimpleEnumerable.new([1, 2, 3]))
+ assert_equal quoted_abc, bind(':a', :a => SimpleEnumerable.new(%w(a b c))) # '
+ end
+
+ def test_bind_empty_enumerable
+ quoted_nil = ActiveRecord::Base.connection.quote(nil)
+ assert_equal quoted_nil, bind('?', [])
+ assert_equal " in (#{quoted_nil})", bind(' in (?)', [])
+ assert_equal "foo in (#{quoted_nil})", bind('foo in (?)', [])
+ end
+
+ def test_bind_empty_string
+ quoted_empty = ActiveRecord::Base.connection.quote('')
+ assert_equal quoted_empty, bind('?', '')
+ end
+
+ def test_bind_chars
+ quoted_bambi = ActiveRecord::Base.connection.quote("Bambi")
+ quoted_bambi_and_thumper = ActiveRecord::Base.connection.quote("Bambi\nand\nThumper")
+ assert_equal "name=#{quoted_bambi}", bind('name=?', "Bambi")
+ assert_equal "name=#{quoted_bambi_and_thumper}", bind('name=?', "Bambi\nand\nThumper")
+ assert_equal "name=#{quoted_bambi}", bind('name=?', "Bambi".mb_chars)
+ assert_equal "name=#{quoted_bambi_and_thumper}", bind('name=?', "Bambi\nand\nThumper".mb_chars)
+ end
+
+ def test_bind_record
+ o = Struct.new(:quoted_id).new(1)
+ assert_equal '1', bind('?', o)
+
+ os = [o] * 3
+ assert_equal '1,1,1', bind('?', os)
+ end
+
+ def test_named_bind_with_postgresql_type_casts
+ l = Proc.new { bind(":a::integer '2009-01-01'::date", :a => '10') }
+ assert_nothing_raised(&l)
+ assert_equal "#{ActiveRecord::Base.connection.quote('10')}::integer '2009-01-01'::date", l.call
+ end
+
+ private
+ def bind(statement, *vars)
+ if vars.first.is_a?(Hash)
+ ActiveRecord::Base.send(:replace_named_bind_variables, statement, vars.first)
+ else
+ ActiveRecord::Base.send(:replace_bind_variables, statement, vars)
+ end
+ end
end
diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb
index 2a2c2bc8d0..a7735a2c7e 100644
--- a/activerecord/test/cases/schema_dumper_test.rb
+++ b/activerecord/test/cases/schema_dumper_test.rb
@@ -117,8 +117,8 @@ class SchemaDumperTest < ActiveRecord::TestCase
assert_match %r{c_int_4.*}, output
assert_no_match %r{c_int_4.*limit:}, output
- elsif current_adapter?(:MysqlAdapter, :Mysql2Adapter)
- assert_match %r{c_int_without_limit.*limit: 4}, output
+ elsif current_adapter?(:Mysql2Adapter)
+ assert_match %r{c_int_without_limit"$}, output
assert_match %r{c_int_1.*limit: 1}, output
assert_match %r{c_int_2.*limit: 2}, output
@@ -169,7 +169,7 @@ class SchemaDumperTest < ActiveRecord::TestCase
def test_schema_dumps_index_columns_in_right_order
index_definition = standard_dump.split(/\n/).grep(/t\.index.*company_index/).first.strip
- if current_adapter?(:MysqlAdapter, :Mysql2Adapter, :PostgreSQLAdapter)
+ if current_adapter?(:Mysql2Adapter, :PostgreSQLAdapter)
assert_equal 't.index ["firm_id", "type", "rating"], name: "company_index", using: :btree', index_definition
else
assert_equal 't.index ["firm_id", "type", "rating"], name: "company_index"', index_definition
@@ -180,7 +180,7 @@ class SchemaDumperTest < ActiveRecord::TestCase
index_definition = standard_dump.split(/\n/).grep(/t\.index.*company_partial_index/).first.strip
if current_adapter?(:PostgreSQLAdapter)
assert_equal 't.index ["firm_id", "type"], name: "company_partial_index", where: "(rating > 10)", using: :btree', index_definition
- elsif current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ elsif current_adapter?(:Mysql2Adapter)
assert_equal 't.index ["firm_id", "type"], name: "company_partial_index", using: :btree', index_definition
elsif current_adapter?(:SQLite3Adapter) && ActiveRecord::Base.connection.supports_partial_index?
assert_equal 't.index ["firm_id", "type"], name: "company_partial_index", where: "rating > 10"', index_definition
@@ -201,7 +201,7 @@ class SchemaDumperTest < ActiveRecord::TestCase
assert_match %r{t\.boolean\s+"has_fun",.+default: false}, output
end
- if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+ if current_adapter?(:Mysql2Adapter)
def test_schema_dump_should_add_default_value_for_mysql_text_field
output = standard_dump
assert_match %r{t\.text\s+"body",\s+limit: 65535,\s+null: false$}, output
@@ -312,7 +312,7 @@ class SchemaDumperTest < ActiveRecord::TestCase
end
end
- class CreateDogMigration < ActiveRecord::Migration
+ class CreateDogMigration < ActiveRecord::Migration::Current
def up
create_table("dog_owners") do |t|
end
@@ -353,6 +353,38 @@ class SchemaDumperTest < ActiveRecord::TestCase
ActiveRecord::Base.table_name_suffix = ActiveRecord::Base.table_name_prefix = ''
$stdout = original
end
+
+ def test_schema_dump_with_table_name_prefix_and_ignoring_tables
+ original, $stdout = $stdout, StringIO.new
+
+ create_cat_migration = Class.new(ActiveRecord::Migration::Current) do
+ def change
+ create_table("cats") do |t|
+ end
+ create_table("omg_cats") do |t|
+ end
+ end
+ end
+
+ original_table_name_prefix = ActiveRecord::Base.table_name_prefix
+ original_schema_dumper_ignore_tables = ActiveRecord::SchemaDumper.ignore_tables
+ ActiveRecord::Base.table_name_prefix = 'omg_'
+ ActiveRecord::SchemaDumper.ignore_tables = ["cats"]
+ migration = create_cat_migration.new
+ migration.migrate(:up)
+
+ stream = StringIO.new
+ output = ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, stream).string
+
+ assert_match %r{create_table "omg_cats"}, output
+ refute_match %r{create_table "cats"}, output
+ ensure
+ migration.migrate(:down)
+ ActiveRecord::Base.table_name_prefix = original_table_name_prefix
+ ActiveRecord::SchemaDumper.ignore_tables = original_schema_dumper_ignore_tables
+
+ $stdout = original
+ end
end
class SchemaDumperDefaultsTest < ActiveRecord::TestCase
diff --git a/activerecord/test/cases/tasks/mysql_rake_test.rb b/activerecord/test/cases/tasks/mysql_rake_test.rb
index 723a7618ba..7cc74f9d9f 100644
--- a/activerecord/test/cases/tasks/mysql_rake_test.rb
+++ b/activerecord/test/cases/tasks/mysql_rake_test.rb
@@ -1,12 +1,12 @@
require 'cases/helper'
-if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
+if current_adapter?(:Mysql2Adapter)
module ActiveRecord
class MysqlDBCreateTest < ActiveRecord::TestCase
def setup
@connection = stub(:create_database => true)
@configuration = {
- 'adapter' => 'mysql',
+ 'adapter' => 'mysql2',
'database' => 'my-app-db'
}
@@ -16,7 +16,7 @@ module ActiveRecord
def test_establishes_connection_without_database
ActiveRecord::Base.expects(:establish_connection).
- with('adapter' => 'mysql', 'database' => nil)
+ with('adapter' => 'mysql2', 'database' => nil)
ActiveRecord::Tasks::DatabaseTasks.create @configuration
end
@@ -65,7 +65,7 @@ module ActiveRecord
@connection = stub("Connection", create_database: true)
@error = Mysql::Error.new "Invalid permissions"
@configuration = {
- 'adapter' => 'mysql',
+ 'adapter' => 'mysql2',
'database' => 'my-app-db',
'username' => 'pat',
'password' => 'wossname'
@@ -92,7 +92,7 @@ module ActiveRecord
def test_connection_established_as_root
assert_permissions_granted_for "pat"
ActiveRecord::Base.expects(:establish_connection).with(
- 'adapter' => 'mysql',
+ 'adapter' => 'mysql2',
'database' => nil,
'username' => 'root',
'password' => 'secret'
@@ -124,7 +124,7 @@ module ActiveRecord
assert_permissions_granted_for "pat"
ActiveRecord::Base.expects(:establish_connection).returns do
ActiveRecord::Base.expects(:establish_connection).with(
- 'adapter' => 'mysql',
+ 'adapter' => 'mysql2',
'database' => 'my-app-db',
'username' => 'pat',
'password' => 'secret'
@@ -157,7 +157,7 @@ module ActiveRecord
def setup
@connection = stub(:drop_database => true)
@configuration = {
- 'adapter' => 'mysql',
+ 'adapter' => 'mysql2',
'database' => 'my-app-db'
}
@@ -182,7 +182,7 @@ module ActiveRecord
def setup
@connection = stub(:recreate_database => true)
@configuration = {
- 'adapter' => 'mysql',
+ 'adapter' => 'mysql2',
'database' => 'test-db'
}
@@ -216,7 +216,7 @@ module ActiveRecord
def setup
@connection = stub(:create_database => true)
@configuration = {
- 'adapter' => 'mysql',
+ 'adapter' => 'mysql2',
'database' => 'my-app-db'
}
@@ -234,7 +234,7 @@ module ActiveRecord
def setup
@connection = stub(:create_database => true)
@configuration = {
- 'adapter' => 'mysql',
+ 'adapter' => 'mysql2',
'database' => 'my-app-db'
}
@@ -251,7 +251,7 @@ module ActiveRecord
class MySQLStructureDumpTest < ActiveRecord::TestCase
def setup
@configuration = {
- 'adapter' => 'mysql',
+ 'adapter' => 'mysql2',
'database' => 'test-db'
}
end
@@ -297,7 +297,7 @@ module ActiveRecord
class MySQLStructureLoadTest < ActiveRecord::TestCase
def setup
@configuration = {
- 'adapter' => 'mysql',
+ 'adapter' => 'mysql2',
'database' => 'test-db'
}
end
diff --git a/activerecord/test/cases/tasks/postgresql_rake_test.rb b/activerecord/test/cases/tasks/postgresql_rake_test.rb
index c31f94b2f2..ba53f340ae 100644
--- a/activerecord/test/cases/tasks/postgresql_rake_test.rb
+++ b/activerecord/test/cases/tasks/postgresql_rake_test.rb
@@ -212,7 +212,7 @@ module ActiveRecord
def test_structure_dump_with_schema_search_path
@configuration['schema_search_path'] = 'foo,bar'
- Kernel.expects(:system).with('pg_dump', '-s', '-x', '-O', '-f', @filename, '--schema=foo --schema=bar', 'my-app-db').returns(true)
+ Kernel.expects(:system).with('pg_dump', '-s', '-x', '-O', '-f', @filename, '--schema=foo', '--schema=bar', 'my-app-db').returns(true)
ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, @filename)
end
@@ -228,7 +228,7 @@ module ActiveRecord
end
def test_structure_dump_with_dump_schemas_string
- Kernel.expects(:system).with("pg_dump", '-s', '-x', '-O', '-f', @filename, '--schema=foo --schema=bar', "my-app-db").returns(true)
+ Kernel.expects(:system).with("pg_dump", '-s', '-x', '-O', '-f', @filename, '--schema=foo', '--schema=bar', "my-app-db").returns(true)
with_dump_schemas('foo,bar') do
ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, @filename)
diff --git a/activerecord/test/cases/test_case.rb b/activerecord/test/cases/test_case.rb
index 47e664f4e7..87299c0dab 100644
--- a/activerecord/test/cases/test_case.rb
+++ b/activerecord/test/cases/test_case.rb
@@ -77,12 +77,6 @@ module ActiveRecord
end
end
- class MysqlTestCase < TestCase
- def self.run(*args)
- super if current_adapter?(:MysqlAdapter)
- end
- end
-
class SQLite3TestCase < TestCase
def self.run(*args)
super if current_adapter?(:SQLite3Adapter)
diff --git a/activerecord/test/cases/time_precision_test.rb b/activerecord/test/cases/time_precision_test.rb
index ff7a81fe60..3b6e4dcc2b 100644
--- a/activerecord/test/cases/time_precision_test.rb
+++ b/activerecord/test/cases/time_precision_test.rb
@@ -10,6 +10,7 @@ class TimePrecisionTest < ActiveRecord::TestCase
setup do
@connection = ActiveRecord::Base.connection
+ Foo.reset_column_information
end
teardown do
@@ -20,8 +21,8 @@ class TimePrecisionTest < ActiveRecord::TestCase
@connection.create_table(:foos, force: true)
@connection.add_column :foos, :start, :time, precision: 3
@connection.add_column :foos, :finish, :time, precision: 6
- assert_equal 3, activerecord_column_option('foos', 'start', 'precision')
- assert_equal 6, activerecord_column_option('foos', 'finish', 'precision')
+ assert_equal 3, Foo.columns_hash['start'].precision
+ assert_equal 6, Foo.columns_hash['finish'].precision
end
def test_passing_precision_to_time_does_not_set_limit
@@ -29,8 +30,8 @@ class TimePrecisionTest < ActiveRecord::TestCase
t.time :start, precision: 3
t.time :finish, precision: 6
end
- assert_nil activerecord_column_option('foos', 'start', 'limit')
- assert_nil activerecord_column_option('foos', 'finish', 'limit')
+ assert_nil Foo.columns_hash['start'].limit
+ assert_nil Foo.columns_hash['finish'].limit
end
def test_invalid_time_precision_raises_error
@@ -42,15 +43,6 @@ class TimePrecisionTest < ActiveRecord::TestCase
end
end
- def test_database_agrees_with_activerecord_about_precision
- @connection.create_table(:foos, force: true) do |t|
- t.time :start, precision: 2
- t.time :finish, precision: 4
- end
- assert_equal 2, database_datetime_precision('foos', 'start')
- assert_equal 4, database_datetime_precision('foos', 'finish')
- end
-
def test_formatting_time_according_to_precision
@connection.create_table(:foos, force: true) do |t|
t.time :start, precision: 0
@@ -88,21 +80,5 @@ class TimePrecisionTest < ActiveRecord::TestCase
end
end
- private
-
- def database_datetime_precision(table_name, column_name)
- results = @connection.exec_query("SELECT column_name, datetime_precision FROM information_schema.columns WHERE table_name = '#{table_name}'")
- result = results.find do |result_hash|
- result_hash["column_name"] == column_name
- end
- result && result["datetime_precision"].to_i
- end
-
- def activerecord_column_option(tablename, column_name, option)
- result = @connection.columns(tablename).find do |column|
- column.name == column_name
- end
- result && result.send(option)
- end
end
end
diff --git a/activerecord/test/cases/touch_later_test.rb b/activerecord/test/cases/touch_later_test.rb
index 7058f4fbe2..b47769eed7 100644
--- a/activerecord/test/cases/touch_later_test.rb
+++ b/activerecord/test/cases/touch_later_test.rb
@@ -95,16 +95,14 @@ class TouchLaterTest < ActiveRecord::TestCase
end
def test_touching_three_deep
- skip "Pending from #19324"
-
previous_tree_updated_at = trees(:root).updated_at
previous_grandparent_updated_at = nodes(:grandparent).updated_at
previous_parent_updated_at = nodes(:parent_a).updated_at
previous_child_updated_at = nodes(:child_one_of_a).updated_at
- travel 5.seconds
-
- Node.create! parent: nodes(:child_one_of_a), tree: trees(:root)
+ travel 5.seconds do
+ Node.create! parent: nodes(:child_one_of_a), tree: trees(:root)
+ end
assert_not_equal nodes(:child_one_of_a).reload.updated_at, previous_child_updated_at
assert_not_equal nodes(:parent_a).reload.updated_at, previous_parent_updated_at
diff --git a/activerecord/test/cases/transaction_callbacks_test.rb b/activerecord/test/cases/transaction_callbacks_test.rb
index f2229939c8..637f89196e 100644
--- a/activerecord/test/cases/transaction_callbacks_test.rb
+++ b/activerecord/test/cases/transaction_callbacks_test.rb
@@ -35,9 +35,9 @@ class TransactionCallbacksTest < ActiveRecord::TestCase
has_many :replies, class_name: "ReplyWithCallbacks", foreign_key: "parent_id"
after_commit { |record| record.do_after_commit(nil) }
- after_commit(on: :create) { |record| record.do_after_commit(:create) }
- after_commit(on: :update) { |record| record.do_after_commit(:update) }
- after_commit(on: :destroy) { |record| record.do_after_commit(:destroy) }
+ after_create_commit { |record| record.do_after_commit(:create) }
+ after_update_commit { |record| record.do_after_commit(:update) }
+ after_destroy_commit { |record| record.do_after_commit(:destroy) }
after_rollback { |record| record.do_after_rollback(nil) }
after_rollback(on: :create) { |record| record.do_after_rollback(:create) }
after_rollback(on: :update) { |record| record.do_after_rollback(:update) }
diff --git a/activerecord/test/cases/view_test.rb b/activerecord/test/cases/view_test.rb
index d50ae74e35..f3c2d2f30e 100644
--- a/activerecord/test/cases/view_test.rb
+++ b/activerecord/test/cases/view_test.rb
@@ -150,7 +150,7 @@ class ViewWithoutPrimaryKeyTest < ActiveRecord::TestCase
end
# sqlite dose not support CREATE, INSERT, and DELETE for VIEW
-if current_adapter?(:MysqlAdapter, :Mysql2Adapter, :PostgreSQLAdapter)
+if current_adapter?(:Mysql2Adapter, :PostgreSQLAdapter)
class UpdateableViewTest < ActiveRecord::TestCase
self.use_transactional_tests = false
fixtures :books
@@ -196,7 +196,7 @@ class UpdateableViewTest < ActiveRecord::TestCase
end
end
end
-end # end fo `if current_adapter?(:MysqlAdapter, :Mysql2Adapter, :PostgreSQLAdapter)`
+end # end fo `if current_adapter?(:Mysql2Adapter, :PostgreSQLAdapter)`
end # end fo `if ActiveRecord::Base.connection.supports_views?`
if ActiveRecord::Base.connection.respond_to?(:supports_materialized_views?) &&
diff --git a/activerecord/test/config.example.yml b/activerecord/test/config.example.yml
index e3b55d640e..58e2d45748 100644
--- a/activerecord/test/config.example.yml
+++ b/activerecord/test/config.example.yml
@@ -51,15 +51,6 @@ connections:
password: arunit
database: arunit2
- mysql:
- arunit:
- username: rails
- encoding: utf8
- collation: utf8_unicode_ci
- arunit2:
- username: rails
- encoding: utf8
-
mysql2:
arunit:
username: rails
diff --git a/activerecord/test/migrations/10_urban/9_add_expressions.rb b/activerecord/test/migrations/10_urban/9_add_expressions.rb
index 79a342e574..e908c9eabc 100644
--- a/activerecord/test/migrations/10_urban/9_add_expressions.rb
+++ b/activerecord/test/migrations/10_urban/9_add_expressions.rb
@@ -1,4 +1,4 @@
-class AddExpressions < ActiveRecord::Migration
+class AddExpressions < ActiveRecord::Migration::Current
def self.up
create_table("expressions") do |t|
t.column :expression, :string
diff --git a/activerecord/test/migrations/decimal/1_give_me_big_numbers.rb b/activerecord/test/migrations/decimal/1_give_me_big_numbers.rb
index 0aed7cbd84..549647de86 100644
--- a/activerecord/test/migrations/decimal/1_give_me_big_numbers.rb
+++ b/activerecord/test/migrations/decimal/1_give_me_big_numbers.rb
@@ -1,4 +1,4 @@
-class GiveMeBigNumbers < ActiveRecord::Migration
+class GiveMeBigNumbers < ActiveRecord::Migration::Current
def self.up
create_table :big_numbers do |table|
table.column :bank_balance, :decimal, :precision => 10, :scale => 2
diff --git a/activerecord/test/migrations/magic/1_currencies_have_symbols.rb b/activerecord/test/migrations/magic/1_currencies_have_symbols.rb
index c066c068c2..53b263bf55 100644
--- a/activerecord/test/migrations/magic/1_currencies_have_symbols.rb
+++ b/activerecord/test/migrations/magic/1_currencies_have_symbols.rb
@@ -1,6 +1,6 @@
# coding: ISO-8859-15
-class CurrenciesHaveSymbols < ActiveRecord::Migration
+class CurrenciesHaveSymbols < ActiveRecord::Migration::Current
def self.up
# We use ¤ for default currency symbol
add_column "currencies", "symbol", :string, :default => "¤"
diff --git a/activerecord/test/migrations/missing/1000_people_have_middle_names.rb b/activerecord/test/migrations/missing/1000_people_have_middle_names.rb
index 4b83d61beb..e046944e31 100644
--- a/activerecord/test/migrations/missing/1000_people_have_middle_names.rb
+++ b/activerecord/test/migrations/missing/1000_people_have_middle_names.rb
@@ -1,4 +1,4 @@
-class PeopleHaveMiddleNames < ActiveRecord::Migration
+class PeopleHaveMiddleNames < ActiveRecord::Migration::Current
def self.up
add_column "people", "middle_name", :string
end
diff --git a/activerecord/test/migrations/missing/1_people_have_last_names.rb b/activerecord/test/migrations/missing/1_people_have_last_names.rb
index 68209f3ce9..50fe2a9c8e 100644
--- a/activerecord/test/migrations/missing/1_people_have_last_names.rb
+++ b/activerecord/test/migrations/missing/1_people_have_last_names.rb
@@ -1,4 +1,4 @@
-class PeopleHaveLastNames < ActiveRecord::Migration
+class PeopleHaveLastNames < ActiveRecord::Migration::Current
def self.up
add_column "people", "last_name", :string
end
diff --git a/activerecord/test/migrations/missing/3_we_need_reminders.rb b/activerecord/test/migrations/missing/3_we_need_reminders.rb
index 25bb49cb32..d7c63ac892 100644
--- a/activerecord/test/migrations/missing/3_we_need_reminders.rb
+++ b/activerecord/test/migrations/missing/3_we_need_reminders.rb
@@ -1,4 +1,4 @@
-class WeNeedReminders < ActiveRecord::Migration
+class WeNeedReminders < ActiveRecord::Migration::Current
def self.up
create_table("reminders") do |t|
t.column :content, :text
diff --git a/activerecord/test/migrations/missing/4_innocent_jointable.rb b/activerecord/test/migrations/missing/4_innocent_jointable.rb
index 002a1bf2a6..20fe183777 100644
--- a/activerecord/test/migrations/missing/4_innocent_jointable.rb
+++ b/activerecord/test/migrations/missing/4_innocent_jointable.rb
@@ -1,4 +1,4 @@
-class InnocentJointable < ActiveRecord::Migration
+class InnocentJointable < ActiveRecord::Migration::Current
def self.up
create_table("people_reminders", :id => false) do |t|
t.column :reminder_id, :integer
diff --git a/activerecord/test/migrations/rename/1_we_need_things.rb b/activerecord/test/migrations/rename/1_we_need_things.rb
index f5484ac54f..9dce01acfd 100644
--- a/activerecord/test/migrations/rename/1_we_need_things.rb
+++ b/activerecord/test/migrations/rename/1_we_need_things.rb
@@ -1,4 +1,4 @@
-class WeNeedThings < ActiveRecord::Migration
+class WeNeedThings < ActiveRecord::Migration::Current
def self.up
create_table("things") do |t|
t.column :content, :text
diff --git a/activerecord/test/migrations/rename/2_rename_things.rb b/activerecord/test/migrations/rename/2_rename_things.rb
index 533a113ea8..cb8484e7dc 100644
--- a/activerecord/test/migrations/rename/2_rename_things.rb
+++ b/activerecord/test/migrations/rename/2_rename_things.rb
@@ -1,4 +1,4 @@
-class RenameThings < ActiveRecord::Migration
+class RenameThings < ActiveRecord::Migration::Current
def self.up
rename_table "things", "awesome_things"
end
diff --git a/activerecord/test/migrations/to_copy/1_people_have_hobbies.rb b/activerecord/test/migrations/to_copy/1_people_have_hobbies.rb
index 639841f663..607113b091 100644
--- a/activerecord/test/migrations/to_copy/1_people_have_hobbies.rb
+++ b/activerecord/test/migrations/to_copy/1_people_have_hobbies.rb
@@ -1,4 +1,4 @@
-class PeopleHaveLastNames < ActiveRecord::Migration
+class PeopleHaveLastNames < ActiveRecord::Migration::Current
def self.up
add_column "people", "hobbies", :text
end
diff --git a/activerecord/test/migrations/to_copy/2_people_have_descriptions.rb b/activerecord/test/migrations/to_copy/2_people_have_descriptions.rb
index b3d0b30640..d4cbddab50 100644
--- a/activerecord/test/migrations/to_copy/2_people_have_descriptions.rb
+++ b/activerecord/test/migrations/to_copy/2_people_have_descriptions.rb
@@ -1,4 +1,4 @@
-class PeopleHaveLastNames < ActiveRecord::Migration
+class PeopleHaveLastNames < ActiveRecord::Migration::Current
def self.up
add_column "people", "description", :text
end
diff --git a/activerecord/test/migrations/to_copy2/1_create_articles.rb b/activerecord/test/migrations/to_copy2/1_create_articles.rb
index 0f048d90f7..2e9f5ec6bc 100644
--- a/activerecord/test/migrations/to_copy2/1_create_articles.rb
+++ b/activerecord/test/migrations/to_copy2/1_create_articles.rb
@@ -1,4 +1,4 @@
-class CreateArticles < ActiveRecord::Migration
+class CreateArticles < ActiveRecord::Migration::Current
def self.up
end
diff --git a/activerecord/test/migrations/to_copy2/2_create_comments.rb b/activerecord/test/migrations/to_copy2/2_create_comments.rb
index 0f048d90f7..2e9f5ec6bc 100644
--- a/activerecord/test/migrations/to_copy2/2_create_comments.rb
+++ b/activerecord/test/migrations/to_copy2/2_create_comments.rb
@@ -1,4 +1,4 @@
-class CreateArticles < ActiveRecord::Migration
+class CreateArticles < ActiveRecord::Migration::Current
def self.up
end
diff --git a/activerecord/test/migrations/to_copy_with_name_collision/1_people_have_hobbies.rb b/activerecord/test/migrations/to_copy_with_name_collision/1_people_have_hobbies.rb
index e438cf5999..8f81805fe1 100644
--- a/activerecord/test/migrations/to_copy_with_name_collision/1_people_have_hobbies.rb
+++ b/activerecord/test/migrations/to_copy_with_name_collision/1_people_have_hobbies.rb
@@ -1,4 +1,4 @@
-class PeopleHaveLastNames < ActiveRecord::Migration
+class PeopleHaveLastNames < ActiveRecord::Migration::Current
def self.up
add_column "people", "hobbies", :string
end
diff --git a/activerecord/test/migrations/to_copy_with_timestamps/20090101010101_people_have_hobbies.rb b/activerecord/test/migrations/to_copy_with_timestamps/20090101010101_people_have_hobbies.rb
index 639841f663..607113b091 100644
--- a/activerecord/test/migrations/to_copy_with_timestamps/20090101010101_people_have_hobbies.rb
+++ b/activerecord/test/migrations/to_copy_with_timestamps/20090101010101_people_have_hobbies.rb
@@ -1,4 +1,4 @@
-class PeopleHaveLastNames < ActiveRecord::Migration
+class PeopleHaveLastNames < ActiveRecord::Migration::Current
def self.up
add_column "people", "hobbies", :text
end
diff --git a/activerecord/test/migrations/to_copy_with_timestamps/20090101010202_people_have_descriptions.rb b/activerecord/test/migrations/to_copy_with_timestamps/20090101010202_people_have_descriptions.rb
index b3d0b30640..d4cbddab50 100644
--- a/activerecord/test/migrations/to_copy_with_timestamps/20090101010202_people_have_descriptions.rb
+++ b/activerecord/test/migrations/to_copy_with_timestamps/20090101010202_people_have_descriptions.rb
@@ -1,4 +1,4 @@
-class PeopleHaveLastNames < ActiveRecord::Migration
+class PeopleHaveLastNames < ActiveRecord::Migration::Current
def self.up
add_column "people", "description", :text
end
diff --git a/activerecord/test/migrations/to_copy_with_timestamps2/20090101010101_create_articles.rb b/activerecord/test/migrations/to_copy_with_timestamps2/20090101010101_create_articles.rb
index 0f048d90f7..2e9f5ec6bc 100644
--- a/activerecord/test/migrations/to_copy_with_timestamps2/20090101010101_create_articles.rb
+++ b/activerecord/test/migrations/to_copy_with_timestamps2/20090101010101_create_articles.rb
@@ -1,4 +1,4 @@
-class CreateArticles < ActiveRecord::Migration
+class CreateArticles < ActiveRecord::Migration::Current
def self.up
end
diff --git a/activerecord/test/migrations/to_copy_with_timestamps2/20090101010202_create_comments.rb b/activerecord/test/migrations/to_copy_with_timestamps2/20090101010202_create_comments.rb
index 2b048edbb5..d361847d4b 100644
--- a/activerecord/test/migrations/to_copy_with_timestamps2/20090101010202_create_comments.rb
+++ b/activerecord/test/migrations/to_copy_with_timestamps2/20090101010202_create_comments.rb
@@ -1,4 +1,4 @@
-class CreateComments < ActiveRecord::Migration
+class CreateComments < ActiveRecord::Migration::Current
def self.up
end
diff --git a/activerecord/test/migrations/valid/1_valid_people_have_last_names.rb b/activerecord/test/migrations/valid/1_valid_people_have_last_names.rb
index 06cb911117..c450211d8c 100644
--- a/activerecord/test/migrations/valid/1_valid_people_have_last_names.rb
+++ b/activerecord/test/migrations/valid/1_valid_people_have_last_names.rb
@@ -1,4 +1,4 @@
-class ValidPeopleHaveLastNames < ActiveRecord::Migration
+class ValidPeopleHaveLastNames < ActiveRecord::Migration::Current
def self.up
add_column "people", "last_name", :string
end
diff --git a/activerecord/test/migrations/valid/2_we_need_reminders.rb b/activerecord/test/migrations/valid/2_we_need_reminders.rb
index 25bb49cb32..d7c63ac892 100644
--- a/activerecord/test/migrations/valid/2_we_need_reminders.rb
+++ b/activerecord/test/migrations/valid/2_we_need_reminders.rb
@@ -1,4 +1,4 @@
-class WeNeedReminders < ActiveRecord::Migration
+class WeNeedReminders < ActiveRecord::Migration::Current
def self.up
create_table("reminders") do |t|
t.column :content, :text
diff --git a/activerecord/test/migrations/valid/3_innocent_jointable.rb b/activerecord/test/migrations/valid/3_innocent_jointable.rb
index 002a1bf2a6..20fe183777 100644
--- a/activerecord/test/migrations/valid/3_innocent_jointable.rb
+++ b/activerecord/test/migrations/valid/3_innocent_jointable.rb
@@ -1,4 +1,4 @@
-class InnocentJointable < ActiveRecord::Migration
+class InnocentJointable < ActiveRecord::Migration::Current
def self.up
create_table("people_reminders", :id => false) do |t|
t.column :reminder_id, :integer
diff --git a/activerecord/test/migrations/valid_with_subdirectories/1_valid_people_have_last_names.rb b/activerecord/test/migrations/valid_with_subdirectories/1_valid_people_have_last_names.rb
index 06cb911117..c450211d8c 100644
--- a/activerecord/test/migrations/valid_with_subdirectories/1_valid_people_have_last_names.rb
+++ b/activerecord/test/migrations/valid_with_subdirectories/1_valid_people_have_last_names.rb
@@ -1,4 +1,4 @@
-class ValidPeopleHaveLastNames < ActiveRecord::Migration
+class ValidPeopleHaveLastNames < ActiveRecord::Migration::Current
def self.up
add_column "people", "last_name", :string
end
diff --git a/activerecord/test/migrations/valid_with_subdirectories/sub/2_we_need_reminders.rb b/activerecord/test/migrations/valid_with_subdirectories/sub/2_we_need_reminders.rb
index 25bb49cb32..d7c63ac892 100644
--- a/activerecord/test/migrations/valid_with_subdirectories/sub/2_we_need_reminders.rb
+++ b/activerecord/test/migrations/valid_with_subdirectories/sub/2_we_need_reminders.rb
@@ -1,4 +1,4 @@
-class WeNeedReminders < ActiveRecord::Migration
+class WeNeedReminders < ActiveRecord::Migration::Current
def self.up
create_table("reminders") do |t|
t.column :content, :text
diff --git a/activerecord/test/migrations/valid_with_subdirectories/sub1/3_innocent_jointable.rb b/activerecord/test/migrations/valid_with_subdirectories/sub1/3_innocent_jointable.rb
index 002a1bf2a6..20fe183777 100644
--- a/activerecord/test/migrations/valid_with_subdirectories/sub1/3_innocent_jointable.rb
+++ b/activerecord/test/migrations/valid_with_subdirectories/sub1/3_innocent_jointable.rb
@@ -1,4 +1,4 @@
-class InnocentJointable < ActiveRecord::Migration
+class InnocentJointable < ActiveRecord::Migration::Current
def self.up
create_table("people_reminders", :id => false) do |t|
t.column :reminder_id, :integer
diff --git a/activerecord/test/migrations/valid_with_timestamps/20100101010101_valid_with_timestamps_people_have_last_names.rb b/activerecord/test/migrations/valid_with_timestamps/20100101010101_valid_with_timestamps_people_have_last_names.rb
index 1da99ceaba..9fd27593f0 100644
--- a/activerecord/test/migrations/valid_with_timestamps/20100101010101_valid_with_timestamps_people_have_last_names.rb
+++ b/activerecord/test/migrations/valid_with_timestamps/20100101010101_valid_with_timestamps_people_have_last_names.rb
@@ -1,4 +1,4 @@
-class ValidWithTimestampsPeopleHaveLastNames < ActiveRecord::Migration
+class ValidWithTimestampsPeopleHaveLastNames < ActiveRecord::Migration::Current
def self.up
add_column "people", "last_name", :string
end
diff --git a/activerecord/test/migrations/valid_with_timestamps/20100201010101_valid_with_timestamps_we_need_reminders.rb b/activerecord/test/migrations/valid_with_timestamps/20100201010101_valid_with_timestamps_we_need_reminders.rb
index cb6d735c8b..4a59921136 100644
--- a/activerecord/test/migrations/valid_with_timestamps/20100201010101_valid_with_timestamps_we_need_reminders.rb
+++ b/activerecord/test/migrations/valid_with_timestamps/20100201010101_valid_with_timestamps_we_need_reminders.rb
@@ -1,4 +1,4 @@
-class ValidWithTimestampsWeNeedReminders < ActiveRecord::Migration
+class ValidWithTimestampsWeNeedReminders < ActiveRecord::Migration::Current
def self.up
create_table("reminders") do |t|
t.column :content, :text
diff --git a/activerecord/test/migrations/valid_with_timestamps/20100301010101_valid_with_timestamps_innocent_jointable.rb b/activerecord/test/migrations/valid_with_timestamps/20100301010101_valid_with_timestamps_innocent_jointable.rb
index 4bd4b4714d..bf934576c9 100644
--- a/activerecord/test/migrations/valid_with_timestamps/20100301010101_valid_with_timestamps_innocent_jointable.rb
+++ b/activerecord/test/migrations/valid_with_timestamps/20100301010101_valid_with_timestamps_innocent_jointable.rb
@@ -1,4 +1,4 @@
-class ValidWithTimestampsInnocentJointable < ActiveRecord::Migration
+class ValidWithTimestampsInnocentJointable < ActiveRecord::Migration::Current
def self.up
create_table("people_reminders", :id => false) do |t|
t.column :reminder_id, :integer
diff --git a/activerecord/test/migrations/version_check/20131219224947_migration_version_check.rb b/activerecord/test/migrations/version_check/20131219224947_migration_version_check.rb
index 9d46485a31..6f314c881c 100644
--- a/activerecord/test/migrations/version_check/20131219224947_migration_version_check.rb
+++ b/activerecord/test/migrations/version_check/20131219224947_migration_version_check.rb
@@ -1,4 +1,4 @@
-class MigrationVersionCheck < ActiveRecord::Migration
+class MigrationVersionCheck < ActiveRecord::Migration::Current
def self.up
raise "incorrect migration version" unless version == 20131219224947
end
diff --git a/activerecord/test/models/bulb.rb b/activerecord/test/models/bulb.rb
index a6e83fe353..dc0296305a 100644
--- a/activerecord/test/models/bulb.rb
+++ b/activerecord/test/models/bulb.rb
@@ -1,6 +1,7 @@
class Bulb < ActiveRecord::Base
default_scope { where(:name => 'defaulty') }
belongs_to :car, :touch => true
+ scope :awesome, -> { where(frickinawesome: true) }
attr_reader :scope_after_initialize, :attributes_after_initialize
@@ -49,3 +50,9 @@ class FailedBulb < Bulb
throw(:abort)
end
end
+
+class TrickyBulb < Bulb
+ after_create do |record|
+ record.car.bulbs.to_a
+ end
+end
diff --git a/activerecord/test/models/car.rb b/activerecord/test/models/car.rb
index 81263b79d1..778c22b1f6 100644
--- a/activerecord/test/models/car.rb
+++ b/activerecord/test/models/car.rb
@@ -4,6 +4,7 @@ class Car < ActiveRecord::Base
has_many :funky_bulbs, class_name: 'FunkyBulb', dependent: :destroy
has_many :failed_bulbs, class_name: 'FailedBulb', dependent: :destroy
has_many :foo_bulbs, -> { where(:name => 'foo') }, :class_name => "Bulb"
+ has_many :awesome_bulbs, -> { awesome }, class_name: "Bulb"
has_one :bulb
diff --git a/activerecord/test/schema/mysql_specific_schema.rb b/activerecord/test/schema/mysql_specific_schema.rb
deleted file mode 100644
index 553cb56103..0000000000
--- a/activerecord/test/schema/mysql_specific_schema.rb
+++ /dev/null
@@ -1,62 +0,0 @@
-ActiveRecord::Schema.define do
- create_table :binary_fields, force: true do |t|
- t.binary :var_binary, limit: 255
- t.binary :var_binary_large, limit: 4095
- t.blob :tiny_blob, limit: 255
- t.binary :normal_blob, limit: 65535
- t.binary :medium_blob, limit: 16777215
- t.binary :long_blob, limit: 2147483647
- t.text :tiny_text, limit: 255
- t.text :normal_text, limit: 65535
- t.text :medium_text, limit: 16777215
- t.text :long_text, limit: 2147483647
- end
-
- add_index :binary_fields, :var_binary
-
- create_table :key_tests, force: true, :options => 'ENGINE=MyISAM' do |t|
- t.string :awesome
- t.string :pizza
- t.string :snacks
- end
-
- add_index :key_tests, :awesome, :type => :fulltext, :name => 'index_key_tests_on_awesome'
- add_index :key_tests, :pizza, :using => :btree, :name => 'index_key_tests_on_pizza'
- add_index :key_tests, :snacks, :name => 'index_key_tests_on_snack'
-
- create_table :collation_tests, id: false, force: true do |t|
- t.string :string_cs_column, limit: 1, collation: 'utf8_bin'
- t.string :string_ci_column, limit: 1, collation: 'utf8_general_ci'
- end
-
- ActiveRecord::Base.connection.execute <<-SQL
-DROP PROCEDURE IF EXISTS ten;
-SQL
-
- ActiveRecord::Base.connection.execute <<-SQL
-CREATE PROCEDURE ten() SQL SECURITY INVOKER
-BEGIN
- select 10;
-END
-SQL
-
- ActiveRecord::Base.connection.execute <<-SQL
-DROP PROCEDURE IF EXISTS topics;
-SQL
-
- ActiveRecord::Base.connection.execute <<-SQL
-CREATE PROCEDURE topics(IN num INT) SQL SECURITY INVOKER
-BEGIN
- select * from topics limit num;
-END
-SQL
-
- ActiveRecord::Base.connection.drop_table "enum_tests", if_exists: true
-
- ActiveRecord::Base.connection.execute <<-SQL
-CREATE TABLE enum_tests (
- enum_column ENUM('text','blob','tiny','medium','long')
-)
-SQL
-
-end
diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb
index 66a1f5aa8a..025184f63a 100644
--- a/activerecord/test/schema/schema.rb
+++ b/activerecord/test/schema/schema.rb
@@ -114,7 +114,7 @@ ActiveRecord::Schema.define do
create_table :bulbs, force: true do |t|
t.integer :car_id
t.string :name
- t.boolean :frickinawesome
+ t.boolean :frickinawesome, default: false
t.string :color
end
@@ -356,7 +356,7 @@ ActiveRecord::Schema.define do
t.column :key, :string
end
- create_table :guitar, force: true do |t|
+ create_table :guitars, force: true do |t|
t.string :color
end
diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md
index 9a00825247..2656d3f113 100644
--- a/activesupport/CHANGELOG.md
+++ b/activesupport/CHANGELOG.md
@@ -1,15 +1,92 @@
-* Implements an evented file system monitor to asynchronously detect changes
- in the application source code, routes, locales, etc.
+## Rails 5.0.0.beta1 (December 18, 2015) ##
- To opt-in load the [listen](https://github.com/guard/listen) gem in `Gemfile`:
+* No changes.
+
+
+* Add thread_m/cattr_accessor/reader/writer suite of methods for declaring class and module variables that live per-thread.
+ This makes it easy to declare per-thread globals that are encapsulated. Note: This is a sharp edge. A wild proliferation
+ of globals is A Bad Thing. But like other sharp tools, when it's right, it's right.
+
+ Here's an example of a simple event tracking system where the object being tracked needs not pass a creator that it
+ doesn't need itself along:
+
+ module Current
+ thread_mattr_accessor :account
+ thread_mattr_accessor :user
+
+ def self.reset() self.account = self.user = nil end
+ end
+
+ class ApplicationController < ActiveController::Base
+ before_action :set_current
+ after_action { Current.reset }
+
+ private
+ def set_current
+ Current.account = Account.find(params[:account_id])
+ Current.user = Current.account.users.find(params[:user_id])
+ end
+ end
+
+ class MessagesController < ApplicationController
+ def create
+ @message = Message.create!(message_params)
+ end
+ end
+
+ class Message < ApplicationRecord
+ has_many :events
+ after_create :track_created
+
+ private
+ def track_created
+ events.create! origin: self, action: :create
+ end
+ end
+
+ class Event < ApplicationRecord
+ belongs_to :creator, class_name: 'User'
+ before_validation { self.creator ||= Current.user }
+ end
+
+ *DHH*
+
+
+* Deprecated `Module#qualified_const_` in favour of the builtin Module#const_
+ methods.
+
+ *Genadi Samokovarov*
+
+* Deprecate passing string to define callback.
+
+ *Yuichiro Kaneko*
+
+* `ActiveSupport::Cache::Store#namespaced_key`,
+ `ActiveSupport::Cache::MemCachedStore#escape_key`, and
+ `ActiveSupport::Cache::FileStore#key_file_path`
+ are deprecated and replaced with `normalize_key` that now calls `super`.
+
+ `ActiveSupport::Cache::LocaleCache#set_cache_value` is deprecated and replaced with `write_cache_value`.
+
+ *Michael Grosser*
+
+* Implements an evented file watcher to asynchronously detect changes in the
+ application source code, routes, locales, etc.
+
+ This watcher is disabled by default, applications my enable it in the configuration:
+
+ # config/environments/development.rb
+ config.file_watcher = ActiveSupport::EventedFileUpdateChecker
+
+ This feature depends on the [listen](https://github.com/guard/listen) gem:
group :development do
- gem 'listen', '~> 3.0.4'
+ gem 'listen', '~> 3.0.5'
end
*Puneet Agarwal* and *Xavier Noria*
-* Added `Time#days_in_year` to return the number of days in the given year, or the
+* Added `Time.days_in_year` to return the number of days in the given year, or the
current year if no argument is provided.
*Jon Pascoe*
diff --git a/activesupport/README.rdoc b/activesupport/README.rdoc
index cd72f53821..14ce204303 100644
--- a/activesupport/README.rdoc
+++ b/activesupport/README.rdoc
@@ -10,7 +10,7 @@ outside of Rails.
The latest version of Active Support can be installed with RubyGems:
- % gem install activesupport
+ $ gem install activesupport
Source code can be downloaded as part of the Rails project on GitHub:
@@ -37,4 +37,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/activesupport/activesupport.gemspec b/activesupport/activesupport.gemspec
index 404c16b29f..32e28c0212 100644
--- a/activesupport/activesupport.gemspec
+++ b/activesupport/activesupport.gemspec
@@ -24,6 +24,6 @@ Gem::Specification.new do |s|
s.add_dependency 'json', '~> 1.7', '>= 1.7.7'
s.add_dependency 'tzinfo', '~> 1.1'
s.add_dependency 'minitest', '~> 5.1'
- s.add_dependency 'concurrent-ruby', '~> 1.0.0.pre5', '< 2.0.0'
+ s.add_dependency 'concurrent-ruby', '~> 1.0'
s.add_dependency 'method_source'
end
diff --git a/activesupport/bin/generate_tables b/activesupport/bin/generate_tables
index 71a6b78652..2193533588 100755
--- a/activesupport/bin/generate_tables
+++ b/activesupport/bin/generate_tables
@@ -50,16 +50,11 @@ module ActiveSupport
([0-9A-F]*); # simple lowercase mapping
([0-9A-F]*)$/ix # simple titlecase mapping
codepoint.code = $1.hex
- #codepoint.name = $2
- #codepoint.category = $3
codepoint.combining_class = Integer($4)
- #codepoint.bidi_class = $5
codepoint.decomp_type = $7
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
- #codepoint.titlecase_mapping = ($18=='') ? nil : $18.hex
@ucd.codepoints[codepoint.code] = codepoint
end
diff --git a/activesupport/lib/active_support.rb b/activesupport/lib/active_support.rb
index 3a2a7d28cb..2019afeb00 100644
--- a/activesupport/lib/active_support.rb
+++ b/activesupport/lib/active_support.rb
@@ -34,7 +34,7 @@ module ActiveSupport
autoload :Dependencies
autoload :DescendantsTracker
autoload :FileUpdateChecker
- autoload :FileEventedUpdateChecker
+ autoload :EventedFileUpdateChecker
autoload :LogSubscriber
autoload :Notifications
diff --git a/activesupport/lib/active_support/cache.rb b/activesupport/lib/active_support/cache.rb
index d0e53eaf05..8272d3395c 100644
--- a/activesupport/lib/active_support/cache.rb
+++ b/activesupport/lib/active_support/cache.rb
@@ -8,6 +8,7 @@ require 'active_support/core_ext/numeric/bytes'
require 'active_support/core_ext/numeric/time'
require 'active_support/core_ext/object/to_param'
require 'active_support/core_ext/string/inflections'
+require 'active_support/core_ext/string/strip'
module ActiveSupport
# See ActiveSupport::Cache::Store for documentation.
@@ -275,20 +276,20 @@ module ActiveSupport
def fetch(name, options = nil)
if block_given?
options = merged_options(options)
- key = namespaced_key(name, options)
+ key = normalize_key(name, options)
+ entry = nil
instrument(:read, name, options) do |payload|
cached_entry = read_entry(key, options) unless options[:force]
- payload[:super_operation] = :fetch if payload
entry = handle_expired_entry(cached_entry, key, options)
+ payload[:super_operation] = :fetch if payload
+ payload[:hit] = !!entry if payload
+ end
- if entry
- payload[:hit] = true if payload
- get_entry_value(entry, name, options)
- else
- payload[:hit] = false if payload
- save_block_result_to_cache(name, options) { |_name| yield _name }
- end
+ if entry
+ get_entry_value(entry, name, options)
+ else
+ save_block_result_to_cache(name, options) { |_name| yield _name }
end
else
read(name, options)
@@ -302,7 +303,7 @@ module ActiveSupport
# Options are passed to the underlying cache implementation.
def read(name, options = nil)
options = merged_options(options)
- key = namespaced_key(name, options)
+ key = normalize_key(name, options)
instrument(:read, name, options) do |payload|
entry = read_entry(key, options)
if entry
@@ -334,7 +335,7 @@ module ActiveSupport
instrument_multi(:read, names, options) do |payload|
results = {}
names.each do |name|
- key = namespaced_key(name, options)
+ key = normalize_key(name, options)
entry = read_entry(key, options)
if entry
if entry.expired?
@@ -386,7 +387,7 @@ module ActiveSupport
instrument(:write, name, options) do
entry = Entry.new(value, options)
- write_entry(namespaced_key(name, options), entry, options)
+ write_entry(normalize_key(name, options), entry, options)
end
end
@@ -397,7 +398,7 @@ module ActiveSupport
options = merged_options(options)
instrument(:delete, name) do
- delete_entry(namespaced_key(name, options), options)
+ delete_entry(normalize_key(name, options), options)
end
end
@@ -408,7 +409,7 @@ module ActiveSupport
options = merged_options(options)
instrument(:exist?, name) do
- entry = read_entry(namespaced_key(name, options), options)
+ entry = read_entry(normalize_key(name, options), options)
(entry && !entry.expired?) || false
end
end
@@ -529,7 +530,7 @@ module ActiveSupport
# Prefix a key with the namespace. Namespace and key will be delimited
# with a colon.
- def namespaced_key(key, options)
+ def normalize_key(key, options)
key = expanded_key(key)
namespace = options[:namespace] if options
prefix = namespace.is_a?(Proc) ? namespace.call : namespace
@@ -537,8 +538,16 @@ module ActiveSupport
key
end
+ def namespaced_key(*args)
+ ActiveSupport::Deprecation.warn(<<-MESSAGE.strip_heredoc)
+ `namespaced_key` is deprecated and will be removed from Rails 5.1.
+ Please use `normalize_key` which will return a fully resolved key.
+ MESSAGE
+ normalize_key(*args)
+ end
+
def instrument(operation, key, options = nil)
- log { "Cache #{operation}: #{namespaced_key(key, options)}#{options.blank? ? "" : " (#{options.inspect})"}" }
+ log { "Cache #{operation}: #{normalize_key(key, options)}#{options.blank? ? "" : " (#{options.inspect})"}" }
payload = { :key => key }
payload.merge!(options) if options.is_a?(Hash)
diff --git a/activesupport/lib/active_support/cache/file_store.rb b/activesupport/lib/active_support/cache/file_store.rb
index 9a88fc286a..dff2443bc8 100644
--- a/activesupport/lib/active_support/cache/file_store.rb
+++ b/activesupport/lib/active_support/cache/file_store.rb
@@ -60,7 +60,7 @@ module ActiveSupport
matcher = key_matcher(matcher, options)
search_dir(cache_path) do |path|
key = file_path_key(path)
- delete_entry(key, options) if key.match(matcher)
+ delete_entry(path, options) if key.match(matcher)
end
end
end
@@ -68,9 +68,8 @@ module ActiveSupport
protected
def read_entry(key, options)
- file_name = key_file_path(key)
- if File.exist?(file_name)
- File.open(file_name) { |f| Marshal.load(f) }
+ if File.exist?(key)
+ File.open(key) { |f| Marshal.load(f) }
end
rescue => e
logger.error("FileStoreError (#{e}): #{e.message}") if logger
@@ -78,23 +77,21 @@ module ActiveSupport
end
def write_entry(key, entry, options)
- file_name = key_file_path(key)
- return false if options[:unless_exist] && File.exist?(file_name)
- ensure_cache_path(File.dirname(file_name))
- File.atomic_write(file_name, cache_path) {|f| Marshal.dump(entry, f)}
+ return false if options[:unless_exist] && File.exist?(key)
+ ensure_cache_path(File.dirname(key))
+ File.atomic_write(key, cache_path) {|f| Marshal.dump(entry, f)}
true
end
def delete_entry(key, options)
- file_name = key_file_path(key)
- if File.exist?(file_name)
+ if File.exist?(key)
begin
- File.delete(file_name)
- delete_empty_directories(File.dirname(file_name))
+ File.delete(key)
+ delete_empty_directories(File.dirname(key))
true
rescue => e
# Just in case the error was caused by another process deleting the file first.
- raise e if File.exist?(file_name)
+ raise e if File.exist?(key)
false
end
end
@@ -118,7 +115,8 @@ module ActiveSupport
end
# Translate a key into a file path.
- def key_file_path(key)
+ def normalize_key(key, options)
+ key = super
fname = URI.encode_www_form_component(key)
if fname.size > FILEPATH_MAX_SIZE
@@ -139,6 +137,14 @@ module ActiveSupport
File.join(cache_path, DIR_FORMATTER % dir_1, DIR_FORMATTER % dir_2, *fname_paths)
end
+ def key_file_path(key)
+ ActiveSupport::Deprecation.warn(<<-MESSAGE.strip_heredoc)
+ `key_file_path` is deprecated and will be removed from Rails 5.1.
+ Please use `normalize_key` which will return a fully resolved key or nothing.
+ MESSAGE
+ key
+ end
+
# Translate a file path into a key.
def file_path_key(path)
fname = path[cache_path.to_s.size..-1].split(File::SEPARATOR, 4).last
@@ -175,7 +181,7 @@ module ActiveSupport
# Modifies the amount of an already existing integer value that is stored in the cache.
# If the key is not found nothing is done.
def modify_value(name, amount, options)
- file_name = key_file_path(namespaced_key(name, options))
+ file_name = normalize_key(name, options)
lock_file(file_name) do
options = merged_options(options)
diff --git a/activesupport/lib/active_support/cache/mem_cache_store.rb b/activesupport/lib/active_support/cache/mem_cache_store.rb
index e2f536ef1e..174913365a 100644
--- a/activesupport/lib/active_support/cache/mem_cache_store.rb
+++ b/activesupport/lib/active_support/cache/mem_cache_store.rb
@@ -36,13 +36,13 @@ module ActiveSupport
end
def write_entry(key, entry, options) # :nodoc:
- retval = super
- if options[:raw] && local_cache && retval
+ if options[:raw] && local_cache
raw_entry = Entry.new(entry.value.to_s)
raw_entry.expires_at = entry.expires_at
- local_cache.write_entry(key, raw_entry, options)
+ super(key, raw_entry, options)
+ else
+ super
end
- retval
end
end
@@ -97,7 +97,7 @@ module ActiveSupport
options = merged_options(options)
instrument_multi(:read, names, options) do
- keys_to_names = Hash[names.map{|name| [escape_key(namespaced_key(name, options)), name]}]
+ keys_to_names = Hash[names.map{|name| [normalize_key(name, options), name]}]
raw_values = @data.get_multi(keys_to_names.keys, :raw => true)
values = {}
raw_values.each do |key, value|
@@ -115,11 +115,10 @@ module ActiveSupport
def increment(name, amount = 1, options = nil) # :nodoc:
options = merged_options(options)
instrument(:increment, name, :amount => amount) do
- @data.incr(escape_key(namespaced_key(name, options)), amount)
+ rescue_error_with nil do
+ @data.incr(normalize_key(name, options), amount)
+ end
end
- rescue Dalli::DalliError => e
- logger.error("DalliError (#{e}): #{e.message}") if logger
- nil
end
# Decrement a cached value. This method uses the memcached decr atomic
@@ -129,20 +128,16 @@ module ActiveSupport
def decrement(name, amount = 1, options = nil) # :nodoc:
options = merged_options(options)
instrument(:decrement, name, :amount => amount) do
- @data.decr(escape_key(namespaced_key(name, options)), amount)
+ rescue_error_with nil do
+ @data.decr(normalize_key(name, options), amount)
+ end
end
- rescue Dalli::DalliError => e
- logger.error("DalliError (#{e}): #{e.message}") if logger
- nil
end
# Clear the entire cache on all memcached servers. This method should
# be used with care when shared cache is being used.
def clear(options = nil)
- @data.flush_all
- rescue Dalli::DalliError => e
- logger.error("DalliError (#{e}): #{e.message}") if logger
- nil
+ rescue_error_with(nil) { @data.flush_all }
end
# Get the statistics from the memcached servers.
@@ -153,10 +148,7 @@ module ActiveSupport
protected
# Read an entry from the cache.
def read_entry(key, options) # :nodoc:
- deserialize_entry(@data.get(escape_key(key), options))
- rescue Dalli::DalliError => e
- logger.error("DalliError (#{e}): #{e.message}") if logger
- nil
+ rescue_error_with(nil) { deserialize_entry(@data.get(key, options)) }
end
# Write an entry to the cache.
@@ -168,18 +160,14 @@ module ActiveSupport
# Set the memcache expire a few minutes in the future to support race condition ttls on read
expires_in += 5.minutes
end
- @data.send(method, escape_key(key), value, expires_in, options)
- rescue Dalli::DalliError => e
- logger.error("DalliError (#{e}): #{e.message}") if logger
- false
+ rescue_error_with false do
+ @data.send(method, key, value, expires_in, options)
+ end
end
# Delete an entry from the cache.
def delete_entry(key, options) # :nodoc:
- @data.delete(escape_key(key))
- rescue Dalli::DalliError => e
- logger.error("DalliError (#{e}): #{e.message}") if logger
- false
+ rescue_error_with(false) { @data.delete(key) }
end
private
@@ -187,22 +175,35 @@ module ActiveSupport
# Memcache keys are binaries. So we need to force their encoding to binary
# before applying the regular expression to ensure we are escaping all
# characters properly.
- def escape_key(key)
- key = key.to_s.dup
+ def normalize_key(key, options)
+ key = super.dup
key = key.force_encoding(Encoding::ASCII_8BIT)
key = key.gsub(ESCAPE_KEY_CHARS){ |match| "%#{match.getbyte(0).to_s(16).upcase}" }
key = "#{key[0, 213]}:md5:#{Digest::MD5.hexdigest(key)}" if key.size > 250
key
end
+ def escape_key(key)
+ ActiveSupport::Deprecation.warn(<<-MESSAGE.strip_heredoc)
+ `escape_key` is deprecated and will be removed from Rails 5.1.
+ Please use `normalize_key` which will return a fully resolved key or nothing.
+ MESSAGE
+ key
+ end
+
def deserialize_entry(raw_value)
if raw_value
entry = Marshal.load(raw_value) rescue raw_value
entry.is_a?(Entry) ? entry : Entry.new(entry)
- else
- nil
end
end
+
+ def rescue_error_with(fallback)
+ yield
+ rescue Dalli::DalliError => e
+ logger.error("DalliError (#{e}): #{e.message}") if logger
+ fallback
+ end
end
end
end
diff --git a/activesupport/lib/active_support/cache/strategy/local_cache.rb b/activesupport/lib/active_support/cache/strategy/local_cache.rb
index fa007aad56..df38dbcf11 100644
--- a/activesupport/lib/active_support/cache/strategy/local_cache.rb
+++ b/activesupport/lib/active_support/cache/strategy/local_cache.rb
@@ -93,14 +93,14 @@ module ActiveSupport
def increment(name, amount = 1, options = nil) # :nodoc:
return super unless local_cache
value = bypass_local_cache{super}
- set_cache_value(value, name, amount, options)
+ write_cache_value(name, value, options)
value
end
def decrement(name, amount = 1, options = nil) # :nodoc:
return super unless local_cache
value = bypass_local_cache{super}
- set_cache_value(value, name, amount, options)
+ write_cache_value(name, value, options)
value
end
@@ -124,6 +124,15 @@ module ActiveSupport
end
def set_cache_value(value, name, amount, options) # :nodoc:
+ ActiveSupport::Deprecation.warn(<<-MESSAGE.strip_heredoc)
+ `set_cache_value` is deprecated and will be removed from Rails 5.1.
+ Please use `write_cache_value`
+ MESSAGE
+ write_cache_value name, value, options
+ end
+
+ def write_cache_value(name, value, options) # :nodoc:
+ name = normalize_key(name, options)
cache = local_cache
cache.mute do
if value
diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb
index d43fde03a9..bf560ec1fa 100644
--- a/activesupport/lib/active_support/callbacks.rb
+++ b/activesupport/lib/active_support/callbacks.rb
@@ -295,6 +295,13 @@ module ActiveSupport
class Callback #:nodoc:#
def self.build(chain, filter, kind, options)
+ if filter.is_a?(String)
+ ActiveSupport::Deprecation.warn(<<-MSG.squish)
+ Passing string to define callback is deprecated and will be removed
+ in Rails 5.1 without replacement.
+ MSG
+ end
+
new chain.name, filter, kind, options, chain.config
end
@@ -575,7 +582,7 @@ module ActiveSupport
# set_callback :save, :before_meth
#
# The callback can be specified as a symbol naming an instance method; as a
- # proc, lambda, or block; as a string to be instance evaluated; or as an
+ # proc, lambda, or block; as a string to be instance evaluated(deprecated); or as an
# object that responds to a certain method determined by the <tt>:scope</tt>
# argument to +define_callbacks+.
#
diff --git a/activesupport/lib/active_support/core_ext/class/subclasses.rb b/activesupport/lib/active_support/core_ext/class/subclasses.rb
index 3c4bfc5f1e..b0f9a8be34 100644
--- a/activesupport/lib/active_support/core_ext/class/subclasses.rb
+++ b/activesupport/lib/active_support/core_ext/class/subclasses.rb
@@ -3,7 +3,8 @@ require 'active_support/core_ext/module/reachable'
class Class
begin
- ObjectSpace.each_object(Class.new) {}
+ # Test if this Ruby supports each_object against singleton_class
+ ObjectSpace.each_object(Numeric.singleton_class) {}
def descendants # :nodoc:
descendants = []
@@ -12,7 +13,7 @@ class Class
end
descendants
end
- rescue StandardError # JRuby
+ rescue StandardError # JRuby 9.0.4.0 and earlier
def descendants # :nodoc:
descendants = []
ObjectSpace.each_object(Class) do |k|
diff --git a/activesupport/lib/active_support/core_ext/enumerable.rb b/activesupport/lib/active_support/core_ext/enumerable.rb
index fc7531d088..8a74ad4d66 100644
--- a/activesupport/lib/active_support/core_ext/enumerable.rb
+++ b/activesupport/lib/active_support/core_ext/enumerable.rb
@@ -21,7 +21,7 @@ module Enumerable
if block_given?
map(&block).sum(identity)
else
- inject { |sum, element| sum + element } || identity
+ inject(:+) || identity
end
end
diff --git a/activesupport/lib/active_support/core_ext/module.rb b/activesupport/lib/active_support/core_ext/module.rb
index b4efff8b24..ef038331c2 100644
--- a/activesupport/lib/active_support/core_ext/module.rb
+++ b/activesupport/lib/active_support/core_ext/module.rb
@@ -3,6 +3,7 @@ require 'active_support/core_ext/module/introspection'
require 'active_support/core_ext/module/anonymous'
require 'active_support/core_ext/module/reachable'
require 'active_support/core_ext/module/attribute_accessors'
+require 'active_support/core_ext/module/attribute_accessors_per_thread'
require 'active_support/core_ext/module/attr_internal'
require 'active_support/core_ext/module/concerning'
require 'active_support/core_ext/module/delegation'
diff --git a/activesupport/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb b/activesupport/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb
new file mode 100644
index 0000000000..8a7e6776da
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb
@@ -0,0 +1,141 @@
+require 'active_support/core_ext/array/extract_options'
+
+# Extends the module object with class/module and instance accessors for
+# class/module attributes, just like the native attr* accessors for instance
+# attributes, but does so on a per-thread basis.
+#
+# So the values are scoped within the Thread.current space under the class name
+# of the module.
+class Module
+ # Defines a per-thread class attribute and creates class and instance reader methods.
+ # The underlying per-thread class variable is set to +nil+, if it is not previously defined.
+ #
+ # module Current
+ # thread_mattr_reader :user
+ # end
+ #
+ # Current.user # => nil
+ # Thread.current[:attr_Current_user] = "DHH"
+ # Current.user # => "DHH"
+ #
+ # The attribute name must be a valid method name in Ruby.
+ #
+ # module Foo
+ # thread_mattr_reader :"1_Badname"
+ # end
+ # # => NameError: invalid attribute name: 1_Badname
+ #
+ # If you want to opt out the creation on the instance reader method, pass
+ # <tt>instance_reader: false</tt> or <tt>instance_accessor: false</tt>.
+ #
+ # class Current
+ # thread_mattr_reader :user, instance_reader: false
+ # end
+ #
+ # Current.new.user # => NoMethodError
+ def thread_mattr_reader(*syms)
+ options = syms.extract_options!
+
+ syms.each do |sym|
+ raise NameError.new("invalid attribute name: #{sym}") unless sym =~ /^[_A-Za-z]\w*$/
+ class_eval(<<-EOS, __FILE__, __LINE__ + 1)
+ def self.#{sym}
+ Thread.current[:"attr_#{name}_#{sym}"]
+ end
+ EOS
+
+ unless options[:instance_reader] == false || options[:instance_accessor] == false
+ class_eval(<<-EOS, __FILE__, __LINE__ + 1)
+ def #{sym}
+ Thread.current[:"attr_#{self.class.name}_#{sym}"]
+ end
+ EOS
+ end
+ end
+ end
+ alias :thread_cattr_reader :thread_mattr_reader
+
+ # Defines a per-thread class attribute and creates a class and instance writer methods to
+ # allow assignment to the attribute.
+ #
+ # module Current
+ # thread_mattr_writer :user
+ # end
+ #
+ # Current.user = "DHH"
+ # Thread.current[:attr_Current_user] # => "DHH"
+ #
+ # If you want to opt out the instance writer method, pass
+ # <tt>instance_writer: false</tt> or <tt>instance_accessor: false</tt>.
+ #
+ # class Current
+ # thread_mattr_writer :user, instance_writer: false
+ # end
+ #
+ # Current.new.user = "DHH" # => NoMethodError
+ def thread_mattr_writer(*syms)
+ options = syms.extract_options!
+ syms.each do |sym|
+ raise NameError.new("invalid attribute name: #{sym}") unless sym =~ /^[_A-Za-z]\w*$/
+ class_eval(<<-EOS, __FILE__, __LINE__ + 1)
+ def self.#{sym}=(obj)
+ Thread.current[:"attr_#{name}_#{sym}"] = obj
+ end
+ EOS
+
+ unless options[:instance_writer] == false || options[:instance_accessor] == false
+ class_eval(<<-EOS, __FILE__, __LINE__ + 1)
+ def #{sym}=(obj)
+ Thread.current[:"attr_#{self.class.name}_#{sym}"] = obj
+ end
+ EOS
+ end
+ end
+ end
+ alias :thread_cattr_writer :thread_mattr_writer
+
+ # Defines both class and instance accessors for class attributes.
+ #
+ # class Account
+ # thread_mattr_accessor :user
+ # end
+ #
+ # Account.user = "DHH"
+ # Account.user # => "DHH"
+ # Account.new.user # => "DHH"
+ #
+ # If a subclass changes the value, the parent class' value is not changed.
+ # Similarly, if the parent class changes the value, the value of subclasses
+ # is not changed.
+ #
+ # class Customer < Account
+ # end
+ #
+ # Customer.user = "Rafael"
+ # Customer.user # => "Rafael"
+ # Account.user # => "DHH"
+ #
+ # To opt out of the instance writer method, pass <tt>instance_writer: false</tt>.
+ # To opt out of the instance reader method, pass <tt>instance_reader: false</tt>.
+ #
+ # class Current
+ # thread_mattr_accessor :user, instance_writer: false, instance_reader: false
+ # end
+ #
+ # Current.new.user = "DHH" # => NoMethodError
+ # Current.new.user # => NoMethodError
+ #
+ # Or pass <tt>instance_accessor: false</tt>, to opt out both instance methods.
+ #
+ # class Current
+ # mattr_accessor :user, instance_accessor: false
+ # end
+ #
+ # Current.new.user = "DHH" # => NoMethodError
+ # Current.new.user # => NoMethodError
+ def thread_mattr_accessor(*syms, &blk)
+ thread_mattr_reader(*syms, &blk)
+ thread_mattr_writer(*syms, &blk)
+ end
+ alias :thread_cattr_accessor :thread_mattr_accessor
+end
diff --git a/activesupport/lib/active_support/core_ext/module/qualified_const.rb b/activesupport/lib/active_support/core_ext/module/qualified_const.rb
index 65525013db..3ea39d4267 100644
--- a/activesupport/lib/active_support/core_ext/module/qualified_const.rb
+++ b/activesupport/lib/active_support/core_ext/module/qualified_const.rb
@@ -3,13 +3,16 @@ require 'active_support/core_ext/string/inflections'
#--
# Allows code reuse in the methods below without polluting Module.
#++
-module QualifiedConstUtils
- def self.raise_if_absolute(path)
- raise NameError.new("wrong constant name #$&") if path =~ /\A::[^:]+/
- end
- def self.names(path)
- path.split('::')
+module ActiveSupport
+ module QualifiedConstUtils
+ def self.raise_if_absolute(path)
+ raise NameError.new("wrong constant name #$&") if path =~ /\A::[^:]+/
+ end
+
+ def self.names(path)
+ path.split('::')
+ end
end
end
@@ -24,9 +27,14 @@ end
#++
class Module
def qualified_const_defined?(path, search_parents=true)
- QualifiedConstUtils.raise_if_absolute(path)
+ ActiveSupport::Deprecation.warn(<<-MESSAGE.squish)
+ Module#qualified_const_defined? is deprecated in favour of the builtin
+ Module#const_defined? and will be removed in Rails 5.1.
+ MESSAGE
- QualifiedConstUtils.names(path).inject(self) do |mod, name|
+ ActiveSupport::QualifiedConstUtils.raise_if_absolute(path)
+
+ ActiveSupport::QualifiedConstUtils.names(path).inject(self) do |mod, name|
return unless mod.const_defined?(name, search_parents)
mod.const_get(name)
end
@@ -34,19 +42,29 @@ class Module
end
def qualified_const_get(path)
- QualifiedConstUtils.raise_if_absolute(path)
+ ActiveSupport::Deprecation.warn(<<-MESSAGE.squish)
+ Module#qualified_const_get is deprecated in favour of the builtin
+ Module#const_get and will be removed in Rails 5.1.
+ MESSAGE
+
+ ActiveSupport::QualifiedConstUtils.raise_if_absolute(path)
- QualifiedConstUtils.names(path).inject(self) do |mod, name|
+ ActiveSupport::QualifiedConstUtils.names(path).inject(self) do |mod, name|
mod.const_get(name)
end
end
def qualified_const_set(path, value)
- QualifiedConstUtils.raise_if_absolute(path)
+ ActiveSupport::Deprecation.warn(<<-MESSAGE.squish)
+ Module#qualified_const_set is deprecated in favour of the builtin
+ Module#const_set and will be removed in Rails 5.1.
+ MESSAGE
+
+ ActiveSupport::QualifiedConstUtils.raise_if_absolute(path)
const_name = path.demodulize
mod_name = path.deconstantize
- mod = mod_name.empty? ? self : qualified_const_get(mod_name)
+ mod = mod_name.empty? ? self : const_get(mod_name)
mod.const_set(const_name, value)
end
end
diff --git a/activesupport/lib/active_support/core_ext/range/conversions.rb b/activesupport/lib/active_support/core_ext/range/conversions.rb
index 83eced50bf..965436c23a 100644
--- a/activesupport/lib/active_support/core_ext/range/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/range/conversions.rb
@@ -1,34 +1,31 @@
-class Range
+module ActiveSupport::RangeWithFormat
RANGE_FORMATS = {
:db => Proc.new { |start, stop| "BETWEEN '#{start.to_s(:db)}' AND '#{stop.to_s(:db)}'" }
}
# Convert range to a formatted string. See RANGE_FORMATS for predefined formats.
#
- # This method is aliased to <tt>to_s</tt>.
- #
# range = (1..100) # => 1..100
#
- # range.to_formatted_s # => "1..100"
# range.to_s # => "1..100"
- #
- # range.to_formatted_s(:db) # => "BETWEEN '1' AND '100'"
# range.to_s(:db) # => "BETWEEN '1' AND '100'"
#
- # == Adding your own range formats to to_formatted_s
+ # == Adding your own range formats to to_s
# You can add your own formats to the Range::RANGE_FORMATS hash.
# Use the format name as the hash key and a Proc instance.
#
# # config/initializers/range_formats.rb
# Range::RANGE_FORMATS[:short] = ->(start, stop) { "Between #{start.to_s(:db)} and #{stop.to_s(:db)}" }
- def to_formatted_s(format = :default)
+ def to_s(format = :default)
if formatter = RANGE_FORMATS[format]
formatter.call(first, last)
else
- to_default_s
+ super()
end
end
alias_method :to_default_s, :to_s
- alias_method :to_s, :to_formatted_s
+ alias_method :to_formatted_s, :to_s
end
+
+Range.prepend(ActiveSupport::RangeWithFormat)
diff --git a/activesupport/lib/active_support/core_ext/time/calculations.rb b/activesupport/lib/active_support/core_ext/time/calculations.rb
index 675db8a36b..768c9a1b2c 100644
--- a/activesupport/lib/active_support/core_ext/time/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/time/calculations.rb
@@ -162,7 +162,6 @@ class Time
# Returns a new Time representing the start of the day (0:00)
def beginning_of_day
- #(self - seconds_since_midnight).change(usec: 0)
change(:hour => 0)
end
alias :midnight :beginning_of_day
diff --git a/activesupport/lib/active_support/deprecation.rb b/activesupport/lib/active_support/deprecation.rb
index 46e9996d59..24545d766c 100644
--- a/activesupport/lib/active_support/deprecation.rb
+++ b/activesupport/lib/active_support/deprecation.rb
@@ -32,7 +32,7 @@ module ActiveSupport
# and the second is a library name
#
# ActiveSupport::Deprecation.new('2.0', 'MyLibrary')
- def initialize(deprecation_horizon = '5.0', gem_name = 'Rails')
+ def initialize(deprecation_horizon = '5.1', gem_name = 'Rails')
self.gem_name = gem_name
self.deprecation_horizon = deprecation_horizon
# By default, warnings are not silenced and debugging is off.
diff --git a/activesupport/lib/active_support/file_evented_update_checker.rb b/activesupport/lib/active_support/evented_file_update_checker.rb
index 638458c6ce..315be85fb3 100644
--- a/activesupport/lib/active_support/file_evented_update_checker.rb
+++ b/activesupport/lib/active_support/evented_file_update_checker.rb
@@ -1,9 +1,9 @@
-require 'listen'
require 'set'
require 'pathname'
+require 'concurrent/atomic/atomic_boolean'
module ActiveSupport
- class FileEventedUpdateChecker #:nodoc: all
+ class EventedFileUpdateChecker #:nodoc: all
def initialize(files, dirs = {}, &block)
@ph = PathHelper.new
@files = files.map { |f| @ph.xpath(f) }.to_set
@@ -14,22 +14,25 @@ module ActiveSupport
end
@block = block
- @updated = false
+ @updated = Concurrent::AtomicBoolean.new(false)
@lcsp = @ph.longest_common_subpath(@dirs.keys)
if (dtw = directories_to_watch).any?
+ # Loading listen triggers warnings. These are originated by a legit
+ # usage of attr_* macros for private attributes, but adds a lot of noise
+ # to our test suite. Thus, we lazy load it and disable warnings locally.
+ silence_warnings { require 'listen' }
Listen.to(*dtw, &method(:changed)).start
end
end
def updated?
- @updated
+ @updated.true?
end
def execute
+ @updated.make_false
@block.call
- ensure
- @updated = false
end
def execute_if_updated
@@ -43,7 +46,7 @@ module ActiveSupport
def changed(modified, added, removed)
unless updated?
- @updated = (modified + added + removed).any? { |f| watching?(f) }
+ @updated.make_true if (modified + added + removed).any? { |f| watching?(f) }
end
end
diff --git a/activesupport/lib/active_support/gem_version.rb b/activesupport/lib/active_support/gem_version.rb
index ece68bbcb6..7790a9b2c0 100644
--- a/activesupport/lib/active_support/gem_version.rb
+++ b/activesupport/lib/active_support/gem_version.rb
@@ -8,7 +8,7 @@ module ActiveSupport
MAJOR = 5
MINOR = 0
TINY = 0
- PRE = "alpha"
+ PRE = "beta1"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/activesupport/lib/active_support/logger.rb b/activesupport/lib/active_support/logger.rb
index 33fccdcf95..82117a64d2 100644
--- a/activesupport/lib/active_support/logger.rb
+++ b/activesupport/lib/active_support/logger.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/module/attribute_accessors'
require 'active_support/logger_silence'
require 'logger'
@@ -6,16 +5,18 @@ module ActiveSupport
class Logger < ::Logger
include LoggerSilence
+ attr_accessor :broadcast_messages
+
# Broadcasts logs to multiple loggers.
def self.broadcast(logger) # :nodoc:
Module.new do
define_method(:add) do |*args, &block|
- logger.add(*args, &block)
+ logger.add(*args, &block) if broadcast_messages
super(*args, &block)
end
define_method(:<<) do |x|
- logger << x
+ logger << x if broadcast_messages
super(x)
end
@@ -44,6 +45,7 @@ module ActiveSupport
def initialize(*args)
super
@formatter = SimpleFormatter.new
+ @broadcast_messages = true
end
# Simple formatter which only displays the message.
diff --git a/activesupport/lib/active_support/logger_silence.rb b/activesupport/lib/active_support/logger_silence.rb
index a8efdef944..7d92256f24 100644
--- a/activesupport/lib/active_support/logger_silence.rb
+++ b/activesupport/lib/active_support/logger_silence.rb
@@ -1,8 +1,9 @@
require 'active_support/concern'
+require 'active_support/core_ext/module/attribute_accessors'
module LoggerSilence
extend ActiveSupport::Concern
-
+
included do
cattr_accessor :silencer
self.silencer = true
@@ -21,4 +22,4 @@ module LoggerSilence
yield self
end
end
-end \ No newline at end of file
+end
diff --git a/activesupport/lib/active_support/message_verifier.rb b/activesupport/lib/active_support/message_verifier.rb
index 64c5232cf4..854029bf83 100644
--- a/activesupport/lib/active_support/message_verifier.rb
+++ b/activesupport/lib/active_support/message_verifier.rb
@@ -15,7 +15,7 @@ module ActiveSupport
# In the authentication filter:
#
# id, time = @verifier.verify(cookies[:remember_me])
- # if time < Time.now
+ # if Time.now < time
# self.current_user = User.find(id)
# end
#
diff --git a/activesupport/lib/active_support/notifications/fanout.rb b/activesupport/lib/active_support/notifications/fanout.rb
index 7798c7ec60..c53f9c1039 100644
--- a/activesupport/lib/active_support/notifications/fanout.rb
+++ b/activesupport/lib/active_support/notifications/fanout.rb
@@ -42,8 +42,8 @@ module ActiveSupport
listeners_for(name).each { |s| s.start(name, id, payload) }
end
- def finish(name, id, payload)
- listeners_for(name).each { |s| s.finish(name, id, payload) }
+ def finish(name, id, payload, listeners = listeners_for(name))
+ listeners.each { |s| s.finish(name, id, payload) }
end
def publish(name, *args)
diff --git a/activesupport/lib/active_support/notifications/instrumenter.rb b/activesupport/lib/active_support/notifications/instrumenter.rb
index 075ddc2382..67f2ee1a7f 100644
--- a/activesupport/lib/active_support/notifications/instrumenter.rb
+++ b/activesupport/lib/active_support/notifications/instrumenter.rb
@@ -15,14 +15,15 @@ module ActiveSupport
# and publish it. Notice that events get sent even if an error occurs
# in the passed-in block.
def instrument(name, payload={})
- start name, payload
+ # some of the listeners might have state
+ listeners_state = start name, payload
begin
yield payload
rescue Exception => e
payload[:exception] = [e.class.name, e.message]
raise e
ensure
- finish name, payload
+ finish_with_state listeners_state, name, payload
end
end
@@ -36,6 +37,10 @@ module ActiveSupport
@notifier.finish name, @id, payload
end
+ def finish_with_state(listeners_state, name, payload)
+ @notifier.finish name, @id, payload, listeners_state
+ end
+
private
def unique_id
diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb
index 4680d5acb7..b1658f0f27 100644
--- a/activesupport/lib/active_support/ordered_hash.rb
+++ b/activesupport/lib/active_support/ordered_hash.rb
@@ -5,7 +5,7 @@ YAML.add_builtin_type("omap") do |type, val|
end
module ActiveSupport
- # <tt>ActiveSupport::OrderedHash</tt> implements a hash that preserves
+ # DEPRECATED: <tt>ActiveSupport::OrderedHash</tt> implements a hash that preserves
# insertion order.
#
# oh = ActiveSupport::OrderedHash.new
diff --git a/activesupport/lib/active_support/per_thread_registry.rb b/activesupport/lib/active_support/per_thread_registry.rb
index 506dd950cb..88e2b12cc7 100644
--- a/activesupport/lib/active_support/per_thread_registry.rb
+++ b/activesupport/lib/active_support/per_thread_registry.rb
@@ -1,4 +1,9 @@
+require 'active_support/core_ext/module/delegation'
+
module ActiveSupport
+ # NOTE: This approach has been deprecated for end-user code in favor of thread_mattr_accessor and friends.
+ # Please use that approach instead.
+ #
# This module is used to encapsulate access to thread local variables.
#
# Instead of polluting the thread locals namespace:
diff --git a/activesupport/lib/active_support/values/time_zone.rb b/activesupport/lib/active_support/values/time_zone.rb
index 6404f65612..7ca3592520 100644
--- a/activesupport/lib/active_support/values/time_zone.rb
+++ b/activesupport/lib/active_support/values/time_zone.rb
@@ -86,7 +86,8 @@ module ActiveSupport
"Paris" => "Europe/Paris",
"Amsterdam" => "Europe/Amsterdam",
"Berlin" => "Europe/Berlin",
- "Bern" => "Europe/Berlin",
+ "Bern" => "Europe/Zurich",
+ "Zurich" => "Europe/Zurich",
"Rome" => "Europe/Rome",
"Stockholm" => "Europe/Stockholm",
"Vienna" => "Europe/Vienna",
diff --git a/activesupport/test/broadcast_logger_test.rb b/activesupport/test/broadcast_logger_test.rb
index 6d4e3b74f7..e7d56c80c3 100644
--- a/activesupport/test/broadcast_logger_test.rb
+++ b/activesupport/test/broadcast_logger_test.rb
@@ -2,56 +2,69 @@ require 'abstract_unit'
module ActiveSupport
class BroadcastLoggerTest < TestCase
- attr_reader :logger, :log1, :log2
+ attr_reader :logger, :receiving_logger
def setup
- @log1 = FakeLogger.new
- @log2 = FakeLogger.new
- @log1.extend Logger.broadcast @log2
- @logger = @log1
+ @logger = FakeLogger.new
+ @receiving_logger = FakeLogger.new
+ @logger.extend Logger.broadcast @receiving_logger
end
def test_debug
logger.debug "foo"
- assert_equal 'foo', log1.adds.first[2]
- assert_equal 'foo', log2.adds.first[2]
+ assert_equal 'foo', logger.adds.first[2]
+ assert_equal 'foo', receiving_logger.adds.first[2]
+ end
+
+ def test_debug_without_message_broadcasts
+ logger.broadcast_messages = false
+ logger.debug "foo"
+ assert_equal 'foo', logger.adds.first[2]
+ assert_equal [], receiving_logger.adds
end
def test_close
logger.close
- assert log1.closed, 'should be closed'
- assert log2.closed, 'should be closed'
+ assert logger.closed, 'should be closed'
+ assert receiving_logger.closed, 'should be closed'
end
def test_chevrons
logger << "foo"
- assert_equal %w{ foo }, log1.chevrons
- assert_equal %w{ foo }, log2.chevrons
+ assert_equal %w{ foo }, logger.chevrons
+ assert_equal %w{ foo }, receiving_logger.chevrons
+ end
+
+ def test_chevrons_without_message_broadcasts
+ logger.broadcast_messages = false
+ logger << "foo"
+ assert_equal %w{ foo }, logger.chevrons
+ assert_equal [], receiving_logger.chevrons
end
def test_level
assert_nil logger.level
logger.level = 10
- assert_equal 10, log1.level
- assert_equal 10, log2.level
+ assert_equal 10, logger.level
+ assert_equal 10, receiving_logger.level
end
def test_progname
assert_nil logger.progname
logger.progname = 10
- assert_equal 10, log1.progname
- assert_equal 10, log2.progname
+ assert_equal 10, logger.progname
+ assert_equal 10, receiving_logger.progname
end
def test_formatter
assert_nil logger.formatter
logger.formatter = 10
- assert_equal 10, log1.formatter
- assert_equal 10, log2.formatter
+ assert_equal 10, logger.formatter
+ assert_equal 10, receiving_logger.formatter
end
class FakeLogger
attr_reader :adds, :closed, :chevrons
- attr_accessor :level, :progname, :formatter
+ attr_accessor :level, :progname, :formatter, :broadcast_messages
def initialize
@adds = []
@@ -60,6 +73,7 @@ module ActiveSupport
@level = nil
@progname = nil
@formatter = nil
+ @broadcast_messages = true
end
def debug msg, &block
diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb
index 3629f5e64b..465b943173 100644
--- a/activesupport/test/caching_test.rb
+++ b/activesupport/test/caching_test.rb
@@ -416,7 +416,7 @@ module CacheStoreBehavior
def test_race_condition_protection_skipped_if_not_defined
@cache.write('foo', 'bar')
- time = @cache.send(:read_entry, 'foo', {}).expires_at
+ time = @cache.send(:read_entry, @cache.send(:normalize_key, 'foo', {}), {}).expires_at
Time.stub(:now, Time.at(time)) do
result = @cache.fetch('foo') do
@@ -493,31 +493,41 @@ module CacheStoreBehavior
def test_cache_hit_instrumentation
key = "test_key"
- subscribe_executed = false
- ActiveSupport::Notifications.subscribe "cache_read.active_support" do |name, start, finish, id, payload|
- subscribe_executed = true
- assert_equal :fetch, payload[:super_operation]
- assert payload[:hit]
+ @events = []
+ ActiveSupport::Notifications.subscribe "cache_read.active_support" do |*args|
+ @events << ActiveSupport::Notifications::Event.new(*args)
end
assert @cache.write(key, "1", :raw => true)
assert @cache.fetch(key) {}
- assert subscribe_executed
+ assert_equal 1, @events.length
+ assert_equal 'cache_read.active_support', @events[0].name
+ assert_equal :fetch, @events[0].payload[:super_operation]
+ assert @events[0].payload[:hit]
ensure
ActiveSupport::Notifications.unsubscribe "cache_read.active_support"
end
def test_cache_miss_instrumentation
- subscribe_executed = false
- ActiveSupport::Notifications.subscribe "cache_read.active_support" do |name, start, finish, id, payload|
- subscribe_executed = true
- assert_equal :fetch, payload[:super_operation]
- assert_not payload[:hit]
+ @events = []
+ ActiveSupport::Notifications.subscribe /^cache_(.*)\.active_support$/ do |*args|
+ @events << ActiveSupport::Notifications::Event.new(*args)
end
assert_not @cache.fetch("bad_key") {}
- assert subscribe_executed
+ assert_equal 3, @events.length
+ assert_equal 'cache_read.active_support', @events[0].name
+ assert_equal 'cache_generate.active_support', @events[1].name
+ assert_equal 'cache_write.active_support', @events[2].name
+ assert_equal :fetch, @events[0].payload[:super_operation]
+ assert_not @events[0].payload[:hit]
ensure
ActiveSupport::Notifications.unsubscribe "cache_read.active_support"
end
+
+ def test_can_call_deprecated_namesaced_key
+ assert_deprecated "`namespaced_key` is deprecated" do
+ @cache.send(:namespaced_key, 111, {})
+ end
+ end
end
# https://rails.lighthouseapp.com/projects/8994/tickets/6225-memcachestore-cant-deal-with-umlauts-and-special-characters
@@ -693,6 +703,15 @@ module LocalCacheBehavior
app = @cache.middleware.new(app)
app.call({})
end
+
+ def test_can_call_deprecated_set_cache_value
+ @cache.with_local_cache do
+ assert_deprecated "`set_cache_value` is deprecated" do
+ @cache.send(:set_cache_value, 1, 'foo', :ignored, {})
+ end
+ assert_equal 1, @cache.read('foo')
+ end
+ end
end
module AutoloadingCacheBehavior
@@ -783,13 +802,13 @@ class FileStoreTest < ActiveSupport::TestCase
end
def test_key_transformation
- key = @cache.send(:key_file_path, "views/index?id=1")
+ key = @cache.send(:normalize_key, "views/index?id=1", {})
assert_equal "views/index?id=1", @cache.send(:file_path_key, key)
end
def test_key_transformation_with_pathname
FileUtils.touch(File.join(cache_dir, "foo"))
- key = @cache_with_pathname.send(:key_file_path, "views/index?id=1")
+ key = @cache_with_pathname.send(:normalize_key, "views/index?id=1", {})
assert_equal "views/index?id=1", @cache_with_pathname.send(:file_path_key, key)
end
@@ -797,7 +816,7 @@ class FileStoreTest < ActiveSupport::TestCase
# remain valid
def test_filename_max_size
key = "#{'A' * ActiveSupport::Cache::FileStore::FILENAME_MAX_SIZE}"
- path = @cache.send(:key_file_path, key)
+ path = @cache.send(:normalize_key, key, {})
Dir::Tmpname.create(path) do |tmpname, n, opts|
assert File.basename(tmpname+'.lock').length <= 255, "Temp filename too long: #{File.basename(tmpname+'.lock').length}"
end
@@ -807,7 +826,7 @@ class FileStoreTest < ActiveSupport::TestCase
# If filename is 'AAAAB', where max size is 4, the returned path should be AAAA/B
def test_key_transformation_max_filename_size
key = "#{'A' * ActiveSupport::Cache::FileStore::FILENAME_MAX_SIZE}B"
- path = @cache.send(:key_file_path, key)
+ path = @cache.send(:normalize_key, key, {})
assert path.split('/').all? { |dir_name| dir_name.size <= ActiveSupport::Cache::FileStore::FILENAME_MAX_SIZE}
assert_equal 'B', File.basename(path)
end
@@ -858,6 +877,12 @@ class FileStoreTest < ActiveSupport::TestCase
@cache.write(1, nil)
assert_equal false, @cache.write(1, "aaaaaaaaaa", unless_exist: true)
end
+
+ def test_can_call_deprecated_key_file_path
+ assert_deprecated "`key_file_path` is deprecated" do
+ assert_equal 111, @cache.send(:key_file_path, 111)
+ end
+ end
end
class MemoryStoreTest < ActiveSupport::TestCase
@@ -1032,6 +1057,12 @@ class MemCacheStoreTest < ActiveSupport::TestCase
value << 'bingo'
assert_not_equal value, @cache.read('foo')
end
+
+ def test_can_call_deprecated_escape_key
+ assert_deprecated "`escape_key` is deprecated" do
+ assert_equal 111, @cache.send(:escape_key, 111)
+ end
+ end
end
class NullStoreTest < ActiveSupport::TestCase
diff --git a/activesupport/test/callbacks_test.rb b/activesupport/test/callbacks_test.rb
index 3b00ff87a0..a624473f46 100644
--- a/activesupport/test/callbacks_test.rb
+++ b/activesupport/test/callbacks_test.rb
@@ -59,7 +59,7 @@ module CallbacksTest
[:before_save, :after_save].each do |callback_method|
callback_method_sym = callback_method.to_sym
send(callback_method, callback_symbol(callback_method_sym))
- send(callback_method, callback_string(callback_method_sym))
+ ActiveSupport::Deprecation.silence { send(callback_method, callback_string(callback_method_sym)) }
send(callback_method, callback_proc(callback_method_sym))
send(callback_method, callback_object(callback_method_sym.to_s.gsub(/_save/, '')))
send(callback_method, CallbackClass)
@@ -228,7 +228,7 @@ module CallbacksTest
set_callback :save, :before, :nope, :if => :no
set_callback :save, :before, :nope, :unless => :yes
set_callback :save, :after, :tweedle
- set_callback :save, :before, "tweedle_dee"
+ ActiveSupport::Deprecation.silence { set_callback :save, :before, "tweedle_dee" }
set_callback :save, :before, proc {|m| m.history << "yup" }
set_callback :save, :before, :nope, :if => proc { false }
set_callback :save, :before, :nope, :unless => proc { true }
@@ -1046,7 +1046,7 @@ module CallbacksTest
def test_add_eval
calls = []
- klass = build_class("bar")
+ klass = ActiveSupport::Deprecation.silence { build_class("bar") }
klass.class_eval { define_method(:bar) { calls << klass } }
klass.new.run
assert_equal 1, calls.length
@@ -1086,7 +1086,7 @@ module CallbacksTest
def test_skip_string # raises error
calls = []
- klass = build_class("bar")
+ klass = ActiveSupport::Deprecation.silence { build_class("bar") }
klass.class_eval { define_method(:bar) { calls << klass } }
assert_raises(ArgumentError) { klass.skip "bar" }
klass.new.run
@@ -1111,4 +1111,14 @@ module CallbacksTest
assert_equal 1, calls.length
end
end
+
+ class DeprecatedWarningTest < ActiveSupport::TestCase
+ def test_deprecate_string_callback
+ klass = Class.new(Record)
+
+ assert_deprecated do
+ klass.send :before_save, "tweedle_dee"
+ end
+ end
+ end
end
diff --git a/activesupport/test/core_ext/module/attribute_accessor_per_thread_test.rb b/activesupport/test/core_ext/module/attribute_accessor_per_thread_test.rb
new file mode 100644
index 0000000000..65fadc5c20
--- /dev/null
+++ b/activesupport/test/core_ext/module/attribute_accessor_per_thread_test.rb
@@ -0,0 +1,109 @@
+require 'abstract_unit'
+require 'active_support/core_ext/module/attribute_accessors_per_thread'
+
+class ModuleAttributeAccessorPerThreadTest < ActiveSupport::TestCase
+ def setup
+ @class = Class.new do
+ thread_mattr_accessor :foo
+ thread_mattr_accessor :bar, instance_writer: false
+ thread_mattr_reader :shaq, instance_reader: false
+ thread_mattr_accessor :camp, instance_accessor: false
+ end
+
+ @object = @class.new
+ end
+
+ def test_should_use_mattr_default
+ Thread.new do
+ assert_nil @class.foo
+ assert_nil @object.foo
+ end.join
+ end
+
+ def test_should_set_mattr_value
+ Thread.new do
+ @class.foo = :test
+ assert_equal :test, @class.foo
+
+ @class.foo = :test2
+ assert_equal :test2, @class.foo
+ end.join
+ end
+
+ def test_should_not_create_instance_writer
+ Thread.new do
+ assert_respond_to @class, :foo
+ assert_respond_to @class, :foo=
+ assert_respond_to @object, :bar
+ assert !@object.respond_to?(:bar=)
+ end.join
+ end
+
+ def test_should_not_create_instance_reader
+ Thread.new do
+ assert_respond_to @class, :shaq
+ assert !@object.respond_to?(:shaq)
+ end.join
+ end
+
+ def test_should_not_create_instance_accessors
+ Thread.new do
+ assert_respond_to @class, :camp
+ assert !@object.respond_to?(:camp)
+ assert !@object.respond_to?(:camp=)
+ end.join
+ end
+
+ def test_values_should_not_bleed_between_threads
+ threads = []
+ threads << Thread.new do
+ @class.foo = 'things'
+ sleep 1
+ assert_equal 'things', @class.foo
+ end
+
+ threads << Thread.new do
+ @class.foo = 'other things'
+ sleep 1
+ assert_equal 'other things', @class.foo
+ end
+
+ threads << Thread.new do
+ @class.foo = 'really other things'
+ sleep 1
+ assert_equal 'really other things', @class.foo
+ end
+
+ threads.each { |t| t.join }
+ end
+
+ def test_should_raise_name_error_if_attribute_name_is_invalid
+ exception = assert_raises NameError do
+ Class.new do
+ thread_cattr_reader "1nvalid"
+ end
+ end
+ assert_equal "invalid attribute name: 1nvalid", exception.message
+
+ exception = assert_raises NameError do
+ Class.new do
+ thread_cattr_writer "1nvalid"
+ end
+ end
+ assert_equal "invalid attribute name: 1nvalid", exception.message
+
+ exception = assert_raises NameError do
+ Class.new do
+ thread_mattr_reader "1valid_part"
+ end
+ end
+ assert_equal "invalid attribute name: 1valid_part", exception.message
+
+ exception = assert_raises NameError do
+ Class.new do
+ thread_mattr_writer "2valid_part"
+ end
+ end
+ assert_equal "invalid attribute name: 2valid_part", exception.message
+ end
+end
diff --git a/activesupport/test/core_ext/module/qualified_const_test.rb b/activesupport/test/core_ext/module/qualified_const_test.rb
index 37c9228a64..a3146cabe1 100644
--- a/activesupport/test/core_ext/module/qualified_const_test.rb
+++ b/activesupport/test/core_ext/module/qualified_const_test.rb
@@ -19,84 +19,94 @@ end
class QualifiedConstTest < ActiveSupport::TestCase
test "Object.qualified_const_defined?" do
- assert Object.qualified_const_defined?("QualifiedConstTestMod")
- assert !Object.qualified_const_defined?("NonExistingQualifiedConstTestMod")
-
- assert Object.qualified_const_defined?("QualifiedConstTestMod::X")
- assert !Object.qualified_const_defined?("QualifiedConstTestMod::Y")
-
- assert Object.qualified_const_defined?("QualifiedConstTestMod::M::X")
- assert !Object.qualified_const_defined?("QualifiedConstTestMod::M::Y")
-
- if Module.method(:const_defined?).arity == 1
- assert !Object.qualified_const_defined?("QualifiedConstTestMod::N::X")
- else
- assert Object.qualified_const_defined?("QualifiedConstTestMod::N::X")
- assert !Object.qualified_const_defined?("QualifiedConstTestMod::N::X", false)
- assert Object.qualified_const_defined?("QualifiedConstTestMod::N::X", true)
+ assert_deprecated do
+ assert Object.qualified_const_defined?("QualifiedConstTestMod")
+ assert !Object.qualified_const_defined?("NonExistingQualifiedConstTestMod")
+
+ assert Object.qualified_const_defined?("QualifiedConstTestMod::X")
+ assert !Object.qualified_const_defined?("QualifiedConstTestMod::Y")
+
+ assert Object.qualified_const_defined?("QualifiedConstTestMod::M::X")
+ assert !Object.qualified_const_defined?("QualifiedConstTestMod::M::Y")
+
+ if Module.method(:const_defined?).arity == 1
+ assert !Object.qualified_const_defined?("QualifiedConstTestMod::N::X")
+ else
+ assert Object.qualified_const_defined?("QualifiedConstTestMod::N::X")
+ assert !Object.qualified_const_defined?("QualifiedConstTestMod::N::X", false)
+ assert Object.qualified_const_defined?("QualifiedConstTestMod::N::X", true)
+ end
end
end
test "mod.qualified_const_defined?" do
- assert QualifiedConstTestMod.qualified_const_defined?("M")
- assert !QualifiedConstTestMod.qualified_const_defined?("NonExistingM")
-
- assert QualifiedConstTestMod.qualified_const_defined?("M::X")
- assert !QualifiedConstTestMod.qualified_const_defined?("M::Y")
-
- assert QualifiedConstTestMod.qualified_const_defined?("M::C::X")
- assert !QualifiedConstTestMod.qualified_const_defined?("M::C::Y")
-
- if Module.method(:const_defined?).arity == 1
- assert !QualifiedConstTestMod.qualified_const_defined?("QualifiedConstTestMod::N::X")
- else
- assert QualifiedConstTestMod.qualified_const_defined?("N::X")
- assert !QualifiedConstTestMod.qualified_const_defined?("N::X", false)
- assert QualifiedConstTestMod.qualified_const_defined?("N::X", true)
+ assert_deprecated do
+ assert QualifiedConstTestMod.qualified_const_defined?("M")
+ assert !QualifiedConstTestMod.qualified_const_defined?("NonExistingM")
+
+ assert QualifiedConstTestMod.qualified_const_defined?("M::X")
+ assert !QualifiedConstTestMod.qualified_const_defined?("M::Y")
+
+ assert QualifiedConstTestMod.qualified_const_defined?("M::C::X")
+ assert !QualifiedConstTestMod.qualified_const_defined?("M::C::Y")
+
+ if Module.method(:const_defined?).arity == 1
+ assert !QualifiedConstTestMod.qualified_const_defined?("QualifiedConstTestMod::N::X")
+ else
+ assert QualifiedConstTestMod.qualified_const_defined?("N::X")
+ assert !QualifiedConstTestMod.qualified_const_defined?("N::X", false)
+ assert QualifiedConstTestMod.qualified_const_defined?("N::X", true)
+ end
end
end
test "qualified_const_get" do
- assert_equal false, Object.qualified_const_get("QualifiedConstTestMod::X")
- assert_equal false, QualifiedConstTestMod.qualified_const_get("X")
- assert_equal 1, QualifiedConstTestMod.qualified_const_get("M::X")
- assert_equal 1, QualifiedConstTestMod.qualified_const_get("N::X")
- assert_equal 2, QualifiedConstTestMod.qualified_const_get("M::C::X")
-
- assert_raise(NameError) { QualifiedConstTestMod.qualified_const_get("M::C::Y")}
+ assert_deprecated do
+ assert_equal false, Object.qualified_const_get("QualifiedConstTestMod::X")
+ assert_equal false, QualifiedConstTestMod.qualified_const_get("X")
+ assert_equal 1, QualifiedConstTestMod.qualified_const_get("M::X")
+ assert_equal 1, QualifiedConstTestMod.qualified_const_get("N::X")
+ assert_equal 2, QualifiedConstTestMod.qualified_const_get("M::C::X")
+
+ assert_raise(NameError) { QualifiedConstTestMod.qualified_const_get("M::C::Y")}
+ end
end
test "qualified_const_set" do
- begin
- m = Module.new
- assert_equal m, Object.qualified_const_set("QualifiedConstTestMod2", m)
- assert_equal m, ::QualifiedConstTestMod2
-
- # We are going to assign to existing constants on purpose, so silence warnings.
- silence_warnings do
- assert_equal true, QualifiedConstTestMod.qualified_const_set("QualifiedConstTestMod::X", true)
- assert_equal true, QualifiedConstTestMod::X
-
- assert_equal 10, QualifiedConstTestMod::M.qualified_const_set("X", 10)
- assert_equal 10, QualifiedConstTestMod::M::X
- end
- ensure
- silence_warnings do
- QualifiedConstTestMod.qualified_const_set('QualifiedConstTestMod::X', false)
- QualifiedConstTestMod::M.qualified_const_set('X', 1)
+ assert_deprecated do
+ begin
+ m = Module.new
+ assert_equal m, Object.qualified_const_set("QualifiedConstTestMod2", m)
+ assert_equal m, ::QualifiedConstTestMod2
+
+ # We are going to assign to existing constants on purpose, so silence warnings.
+ silence_warnings do
+ assert_equal true, QualifiedConstTestMod.qualified_const_set("QualifiedConstTestMod::X", true)
+ assert_equal true, QualifiedConstTestMod::X
+
+ assert_equal 10, QualifiedConstTestMod::M.qualified_const_set("X", 10)
+ assert_equal 10, QualifiedConstTestMod::M::X
+ end
+ ensure
+ silence_warnings do
+ QualifiedConstTestMod.qualified_const_set('QualifiedConstTestMod::X', false)
+ QualifiedConstTestMod::M.qualified_const_set('X', 1)
+ end
end
end
end
test "reject absolute paths" do
- assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_defined?("::X")}
- assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_defined?("::X::Y")}
+ assert_deprecated do
+ assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_defined?("::X")}
+ assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_defined?("::X::Y")}
- assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_get("::X")}
- assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_get("::X::Y")}
+ assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_get("::X")}
+ assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_get("::X::Y")}
- assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_set("::X", nil)}
- assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_set("::X::Y", nil)}
+ assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_set("::X", nil)}
+ assert_raise_with_message(NameError, "wrong constant name ::X") { Object.qualified_const_set("::X::Y", nil)}
+ end
end
private
diff --git a/activesupport/test/deprecation_test.rb b/activesupport/test/deprecation_test.rb
index cd02ad3f3f..58a0a3964d 100644
--- a/activesupport/test/deprecation_test.rb
+++ b/activesupport/test/deprecation_test.rb
@@ -199,7 +199,7 @@ class DeprecationTest < ActiveSupport::TestCase
end
def test_assert_deprecated_warn_work_with_default_behavior
- ActiveSupport::Deprecation.instance_variable_set('@behavior' , nil)
+ ActiveSupport::Deprecation.instance_variable_set('@behavior', nil)
assert_deprecated('abc') do
ActiveSupport::Deprecation.warn 'abc'
end
@@ -340,6 +340,10 @@ class DeprecationTest < ActiveSupport::TestCase
assert_match(/You are calling deprecated method/, object.last_message)
end
+ def test_default_deprecation_horizon_should_always_bigger_than_current_rails_version
+ assert ActiveSupport::Deprecation.new.deprecation_horizon > ActiveSupport::VERSION::STRING
+ end
+
def test_default_gem_name
deprecator = ActiveSupport::Deprecation.new
diff --git a/activesupport/test/file_evented_update_checker_test.rb b/activesupport/test/evented_file_update_checker_test.rb
index 071449d399..bc3f77bd54 100644
--- a/activesupport/test/file_evented_update_checker_test.rb
+++ b/activesupport/test/evented_file_update_checker_test.rb
@@ -2,11 +2,16 @@ require 'abstract_unit'
require 'pathname'
require 'file_update_checker_shared_tests'
-class FileEventedUpdateCheckerTest < ActiveSupport::TestCase
+class EventedFileUpdateCheckerTest < ActiveSupport::TestCase
include FileUpdateCheckerSharedTests
+ def setup
+ skip if ENV['LISTEN'] == '0'
+ super
+ end
+
def new_checker(files = [], dirs = {}, &block)
- ActiveSupport::FileEventedUpdateChecker.new(files, dirs, &block).tap do
+ ActiveSupport::EventedFileUpdateChecker.new(files, dirs, &block).tap do
wait
end
end
@@ -31,13 +36,13 @@ class FileEventedUpdateCheckerTest < ActiveSupport::TestCase
end
end
-class FileEventedUpdateCheckerPathHelperTest < ActiveSupport::TestCase
+class EventedFileUpdateCheckerPathHelperTest < ActiveSupport::TestCase
def pn(path)
Pathname.new(path)
end
setup do
- @ph = ActiveSupport::FileEventedUpdateChecker::PathHelper.new
+ @ph = ActiveSupport::EventedFileUpdateChecker::PathHelper.new
end
test '#xpath returns the expanded path as a Pathname object' do
diff --git a/activesupport/test/file_update_checker_shared_tests.rb b/activesupport/test/file_update_checker_shared_tests.rb
index 100cbc9756..9c07e38fe5 100644
--- a/activesupport/test/file_update_checker_shared_tests.rb
+++ b/activesupport/test/file_update_checker_shared_tests.rb
@@ -21,6 +21,7 @@ module FileUpdateCheckerSharedTests
end
test 'should not execute the block if no paths are given' do
+ silence_warnings { require 'listen' }
i = 0
checker = new_checker { i += 1 }
diff --git a/activesupport/test/multibyte_conformance_test.rb b/activesupport/test/multibyte_conformance_test.rb
index 2a885e32bf..d493a48fe4 100644
--- a/activesupport/test/multibyte_conformance_test.rb
+++ b/activesupport/test/multibyte_conformance_test.rb
@@ -104,11 +104,8 @@ class MultibyteConformanceTest < ActiveSupport::TestCase
protected
def each_line_of_norm_tests(&block)
- lines = 0
- max_test_lines = 0 # Don't limit below 38, because that's the header of the testfile
File.open(File.join(CACHE_DIR, UNIDATA_FILE), 'r') do | f |
- until f.eof? || (max_test_lines > 38 and lines > max_test_lines)
- lines += 1
+ until f.eof?
line = f.gets.chomp!
next if (line.empty? || line =~ /^\#/)
diff --git a/activesupport/test/notifications_test.rb b/activesupport/test/notifications_test.rb
index f729f0a95b..d9cc392ac9 100644
--- a/activesupport/test/notifications_test.rb
+++ b/activesupport/test/notifications_test.rb
@@ -42,6 +42,21 @@ module Notifications
ActiveSupport::Notifications.instrument(name)
assert_equal expected, events
end
+
+ def test_subsribing_to_instrumentation_while_inside_it
+ # the repro requires that there are no evented subscribers for the "foo" event,
+ # so we have to duplicate some of the setup code
+ old_notifier = ActiveSupport::Notifications.notifier
+ ActiveSupport::Notifications.notifier = ActiveSupport::Notifications::Fanout.new
+
+ ActiveSupport::Notifications.subscribe('foo', TestSubscriber.new)
+
+ ActiveSupport::Notifications.instrument('foo') do
+ ActiveSupport::Notifications.subscribe('foo') {}
+ end
+ ensure
+ ActiveSupport::Notifications.notifier = old_notifier
+ end
end
class UnsubscribeTest < TestCase
diff --git a/ci/travis.rb b/ci/travis.rb
index 52fef05fbf..608a6f578e 100755
--- a/ci/travis.rb
+++ b/ci/travis.rb
@@ -23,6 +23,7 @@ class Build
'ar' => 'activerecord',
'av' => 'actionview',
'aj' => 'activejob',
+ 'ac' => 'actioncable',
'guides' => 'guides'
}
@@ -72,6 +73,10 @@ class Build
key.join(':')
end
+ def activesupport?
+ gem == 'activesupport'
+ end
+
def activerecord?
gem == 'activerecord'
end
@@ -101,11 +106,22 @@ class Build
tasks.each do |task|
cmd = "bundle exec rake #{task}"
puts "Running command: #{cmd}"
- return false unless system(cmd)
+ return false unless system(env, cmd)
end
true
end
+ def env
+ if activesupport? && !isolated?
+ # There is a known issue with the listen tests that casuses files to be
+ # incorrectly GC'ed even when they are still in-use. The current is to
+ # only run them in isolation to avoid randomly failing our test suite.
+ { 'LISTEN' => '0' }
+ else
+ {}
+ end
+ end
+
def run_bug_report_templates
Dir.glob('bug_report_templates/*.rb').all? do |file|
system(Gem.ruby, '-w', file)
@@ -124,6 +140,7 @@ ENV['GEM'].split(',').each do |gem|
[false, true].each do |isolated|
next if ENV['TRAVIS_PULL_REQUEST'] && ENV['TRAVIS_PULL_REQUEST'] != 'false' && isolated
next if gem == 'railties' && isolated
+ next if gem == 'ac' && isolated
next if gem == 'aj:integration' && isolated
next if gem == 'guides' && isolated
diff --git a/guides/CHANGELOG.md b/guides/CHANGELOG.md
index 09fb7b1a0e..16919784ad 100644
--- a/guides/CHANGELOG.md
+++ b/guides/CHANGELOG.md
@@ -1,3 +1,8 @@
+## Rails 5.0.0.beta1 (December 18, 2015) ##
+
+* No changes.
+
+
* Add code of conduct to contributing guide
*Jon Moss*
diff --git a/guides/rails_guides/generator.rb b/guides/rails_guides/generator.rb
index b7a94f144c..7618fce2c8 100644
--- a/guides/rails_guides/generator.rb
+++ b/guides/rails_guides/generator.rb
@@ -162,7 +162,7 @@ module RailsGuides
def select_only(guides)
prefixes = ENV['ONLY'].split(",").map(&:strip)
guides.select do |guide|
- prefixes.any? { |p| guide.start_with?(p) || guide.start_with?("kindle") }
+ guide.start_with?('kindle'.freeze, *prefixes)
end
end
diff --git a/guides/rails_guides/kindle.rb b/guides/rails_guides/kindle.rb
index 32926622e3..081afcb09f 100644
--- a/guides/rails_guides/kindle.rb
+++ b/guides/rails_guides/kindle.rb
@@ -27,7 +27,7 @@ module Kindle
generate_document_metadata(mobi_outfile)
- puts "Creating MOBI document with kindlegen. This make take a while."
+ puts "Creating MOBI document with kindlegen. This may take a while."
cmd = "kindlerb . > #{File.absolute_path logfile} 2>&1"
puts cmd
system(cmd)
diff --git a/guides/source/action_controller_overview.md b/guides/source/action_controller_overview.md
index 7e43ba375a..d2e2d27737 100644
--- a/guides/source/action_controller_overview.md
+++ b/guides/source/action_controller_overview.md
@@ -394,7 +394,7 @@ Rails sets up (for the CookieStore) a secret key used for signing the session da
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
-# You can use `rake secret` to generate a secure secret key.
+# You can use `rails secret` to generate a secure secret key.
# Make sure the secrets in this file are kept private
# if you're sharing your code publicly.
@@ -1150,7 +1150,7 @@ class ApplicationController < ActionController::Base
def user_not_authorized
flash[:error] = "You don't have access to this section."
- redirect_to :back
+ redirect_back(fallback_location: root_path)
end
end
diff --git a/guides/source/action_mailer_basics.md b/guides/source/action_mailer_basics.md
index 4800cece82..cd2c13e8c1 100644
--- a/guides/source/action_mailer_basics.md
+++ b/guides/source/action_mailer_basics.md
@@ -170,7 +170,7 @@ First, let's create a simple `User` scaffold:
```bash
$ bin/rails generate scaffold user name email login
-$ bin/rake db:migrate
+$ bin/rails db:migrate
```
Now that we have a user model to play with, we will just edit the
diff --git a/guides/source/action_view_overview.md b/guides/source/action_view_overview.md
index 4b0e9bff7c..d9037674ca 100644
--- a/guides/source/action_view_overview.md
+++ b/guides/source/action_view_overview.md
@@ -990,11 +990,11 @@ Returns `select` and `option` tags for the collection of existing return values
Example object structure for use with this method:
```ruby
-class Article < ActiveRecord::Base
+class Article < ApplicationRecord
belongs_to :author
end
-class Author < ActiveRecord::Base
+class Author < ApplicationRecord
has_many :articles
def name_with_initial
"#{first_name.first}. #{last_name}"
@@ -1026,11 +1026,11 @@ Returns `radio_button` tags for the collection of existing return values of `met
Example object structure for use with this method:
```ruby
-class Article < ActiveRecord::Base
+class Article < ApplicationRecord
belongs_to :author
end
-class Author < ActiveRecord::Base
+class Author < ApplicationRecord
has_many :articles
def name_with_initial
"#{first_name.first}. #{last_name}"
@@ -1062,11 +1062,11 @@ Returns `check_box` tags for the collection of existing return values of `method
Example object structure for use with this method:
```ruby
-class Article < ActiveRecord::Base
+class Article < ApplicationRecord
has_and_belongs_to_many :authors
end
-class Author < ActiveRecord::Base
+class Author < ApplicationRecord
has_and_belongs_to_many :articles
def name_with_initial
"#{first_name.first}. #{last_name}"
@@ -1099,12 +1099,12 @@ Returns a string of `option` tags, like `options_from_collection_for_select`, bu
Example object structure for use with this method:
```ruby
-class Continent < ActiveRecord::Base
+class Continent < ApplicationRecord
has_many :countries
# attribs: id, name
end
-class Country < ActiveRecord::Base
+class Country < ApplicationRecord
belongs_to :continent
# attribs: id, name, continent_id
end
diff --git a/guides/source/active_model_basics.md b/guides/source/active_model_basics.md
index 8f8256c983..c05e20aceb 100644
--- a/guides/source/active_model_basics.md
+++ b/guides/source/active_model_basics.md
@@ -435,7 +435,7 @@ the Active Model API.
```
```bash
-$ rake test
+$ rails test
Run options: --seed 14596
diff --git a/guides/source/active_record_basics.md b/guides/source/active_record_basics.md
index dafbe17bbd..fba89f9d13 100644
--- a/guides/source/active_record_basics.md
+++ b/guides/source/active_record_basics.md
@@ -132,10 +132,10 @@ Creating Active Record Models
-----------------------------
It is very easy to create Active Record models. All you have to do is to
-subclass the `ActiveRecord::Base` class and you're good to go:
+subclass the `ApplicationRecord` class and you're good to go:
```ruby
-class Product < ActiveRecord::Base
+class Product < ApplicationRecord
end
```
@@ -168,11 +168,12 @@ What if you need to follow a different naming convention or need to use your
Rails application with a legacy database? No problem, you can easily override
the default conventions.
-You can use the `ActiveRecord::Base.table_name=` method to specify the table
-name that should be used:
+`ApplicationRecord` inherits from `ActiveRecord::Base`, which defines a
+number of helpful methods. You can use the `ActiveRecord::Base.table_name=`
+method to specify the table name that should be used:
```ruby
-class Product < ActiveRecord::Base
+class Product < ApplicationRecord
self.table_name = "my_products"
end
```
@@ -193,7 +194,7 @@ It's also possible to override the column that should be used as the table's
primary key using the `ActiveRecord::Base.primary_key=` method:
```ruby
-class Product < ActiveRecord::Base
+class Product < ApplicationRecord
self.primary_key = "product_id"
end
```
@@ -320,7 +321,7 @@ they raise the exception `ActiveRecord::RecordInvalid` if validation fails.
A quick example to illustrate:
```ruby
-class User < ActiveRecord::Base
+class User < ApplicationRecord
validates :name, presence: true
end
@@ -350,7 +351,7 @@ database that Active Record supports using `rake`. Here's a migration that
creates a table:
```ruby
-class CreatePublications < ActiveRecord::Migration
+class CreatePublications < ActiveRecord::Migration[5.0]
def change
create_table :publications do |t|
t.string :title
@@ -368,8 +369,8 @@ end
```
Rails keeps track of which files have been committed to the database and
-provides rollback features. To actually create the table, you'd run `rake db:migrate`
-and to roll it back, `rake db:rollback`.
+provides rollback features. To actually create the table, you'd run `rails db:migrate`
+and to roll it back, `rails db:rollback`.
Note that the above code is database-agnostic: it will run in MySQL,
PostgreSQL, Oracle and others. You can learn more about migrations in the
diff --git a/guides/source/active_record_callbacks.md b/guides/source/active_record_callbacks.md
index 13989a3b33..d95c6c0e78 100644
--- a/guides/source/active_record_callbacks.md
+++ b/guides/source/active_record_callbacks.md
@@ -31,7 +31,7 @@ Callbacks are methods that get called at certain moments of an object's life cyc
In order to use the available callbacks, you need to register them. You can implement the callbacks as ordinary methods and use a macro-style class method to register them as callbacks:
```ruby
-class User < ActiveRecord::Base
+class User < ApplicationRecord
validates :login, :email, presence: true
before_validation :ensure_login_has_a_value
@@ -48,7 +48,7 @@ end
The macro-style class methods can also receive a block. Consider using this style if the code inside your block is so short that it fits in a single line:
```ruby
-class User < ActiveRecord::Base
+class User < ApplicationRecord
validates :login, :email, presence: true
before_create do
@@ -60,7 +60,7 @@ end
Callbacks can also be registered to only fire on certain life cycle events:
```ruby
-class User < ActiveRecord::Base
+class User < ApplicationRecord
before_validation :normalize_name, on: :create
# :on takes an array as well
@@ -126,7 +126,7 @@ The `after_find` callback will be called whenever Active Record loads a record f
The `after_initialize` and `after_find` callbacks have no `before_*` counterparts, but they can be registered just like the other Active Record callbacks.
```ruby
-class User < ActiveRecord::Base
+class User < ApplicationRecord
after_initialize do |user|
puts "You have initialized an object!"
end
@@ -151,7 +151,7 @@ You have initialized an object!
The `after_touch` callback will be called whenever an Active Record object is touched.
```ruby
-class User < ActiveRecord::Base
+class User < ApplicationRecord
after_touch do |user|
puts "You have touched an object"
end
@@ -168,14 +168,14 @@ You have touched an object
It can be used along with `belongs_to`:
```ruby
-class Employee < ActiveRecord::Base
+class Employee < ApplicationRecord
belongs_to :company, touch: true
after_touch do
puts 'An Employee was touched'
end
end
-class Company < ActiveRecord::Base
+class Company < ApplicationRecord
has_many :employees
after_touch :log_when_employees_or_company_touched
@@ -266,11 +266,11 @@ Relational Callbacks
Callbacks work through model relationships, and can even be defined by them. Suppose an example where a user has many articles. A user's articles should be destroyed if the user is destroyed. Let's add an `after_destroy` callback to the `User` model by way of its relationship to the `Article` model:
```ruby
-class User < ActiveRecord::Base
+class User < ApplicationRecord
has_many :articles, dependent: :destroy
end
-class Article < ActiveRecord::Base
+class Article < ApplicationRecord
after_destroy :log_destroy_action
def log_destroy_action
@@ -297,7 +297,7 @@ As with validations, we can also make the calling of a callback method condition
You can associate the `:if` and `:unless` options with a symbol corresponding to the name of a predicate method that will get called right before the callback. When using the `:if` option, the callback won't be executed if the predicate method returns false; when using the `:unless` option, the callback won't be executed if the predicate method returns true. This is the most common option. Using this form of registration it is also possible to register several different predicates that should be called to check if the callback should be executed.
```ruby
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
before_save :normalize_card_number, if: :paid_with_card?
end
```
@@ -307,7 +307,7 @@ end
You can also use a string that will be evaluated using `eval` and hence needs to contain valid Ruby code. You should use this option only when the string represents a really short condition:
```ruby
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
before_save :normalize_card_number, if: "paid_with_card?"
end
```
@@ -317,7 +317,7 @@ end
Finally, it is possible to associate `:if` and `:unless` with a `Proc` object. This option is best suited when writing short validation methods, usually one-liners:
```ruby
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
before_save :normalize_card_number,
if: Proc.new { |order| order.paid_with_card? }
end
@@ -328,7 +328,7 @@ end
When writing conditional callbacks, it is possible to mix both `:if` and `:unless` in the same callback declaration:
```ruby
-class Comment < ActiveRecord::Base
+class Comment < ApplicationRecord
after_create :send_email_to_author, if: :author_wants_emails?,
unless: Proc.new { |comment| comment.article.ignore_comments? }
end
@@ -354,7 +354,7 @@ end
When declared inside a class, as above, the callback methods will receive the model object as a parameter. We can now use the callback class in the model:
```ruby
-class PictureFile < ActiveRecord::Base
+class PictureFile < ApplicationRecord
after_destroy PictureFileCallbacks.new
end
```
@@ -374,7 +374,7 @@ end
If the callback method is declared this way, it won't be necessary to instantiate a `PictureFileCallbacks` object.
```ruby
-class PictureFile < ActiveRecord::Base
+class PictureFile < ApplicationRecord
after_destroy PictureFileCallbacks
end
```
@@ -398,7 +398,7 @@ end
By using the `after_commit` callback we can account for this case.
```ruby
-class PictureFile < ActiveRecord::Base
+class PictureFile < ApplicationRecord
after_commit :delete_picture_file_from_disk, on: [:destroy]
def delete_picture_file_from_disk
@@ -412,4 +412,23 @@ end
NOTE: the `:on` option specifies when a callback will be fired. If you
don't supply the `:on` option the callback will fire for every action.
+Since using `after_commit` callback only on create, update or delete is
+common, there are aliases for those operations:
+
+* `after_create_commit`
+* `after_update_commit`
+* `after_destroy_commit`
+
+```ruby
+class PictureFile < ApplicationRecord
+ after_destroy_commit :delete_picture_file_from_disk
+
+ def delete_picture_file_from_disk
+ if File.exist?(filepath)
+ File.delete(filepath)
+ end
+ end
+end
+```
+
WARNING. The `after_commit` and `after_rollback` callbacks are guaranteed to be called for all models created, updated, or destroyed within a transaction block. If any exceptions are raised within one of these callbacks, they will be ignored so that they don't interfere with the other callbacks. As such, if your callback code could raise an exception, you'll need to rescue it and handle it appropriately within the callback.
diff --git a/guides/source/active_record_migrations.md b/guides/source/active_record_migrations.md
index 5aa5dc4f60..a4a23395fb 100644
--- a/guides/source/active_record_migrations.md
+++ b/guides/source/active_record_migrations.md
@@ -35,7 +35,7 @@ history to the latest version. Active Record will also update your
Here's an example of a migration:
```ruby
-class CreateProducts < ActiveRecord::Migration
+class CreateProducts < ActiveRecord::Migration[5.0]
def change
create_table :products do |t|
t.string :name
@@ -72,7 +72,7 @@ If you wish for a migration to do something that Active Record doesn't know how
to reverse, you can use `reversible`:
```ruby
-class ChangeProductsPrice < ActiveRecord::Migration
+class ChangeProductsPrice < ActiveRecord::Migration[5.0]
def change
reversible do |dir|
change_table :products do |t|
@@ -87,7 +87,7 @@ end
Alternatively, you can use `up` and `down` instead of `change`:
```ruby
-class ChangeProductsPrice < ActiveRecord::Migration
+class ChangeProductsPrice < ActiveRecord::Migration[5.0]
def up
change_table :products do |t|
t.change :price, :string
@@ -129,7 +129,7 @@ $ bin/rails generate migration AddPartNumberToProducts
This will create an empty but appropriately named migration:
```ruby
-class AddPartNumberToProducts < ActiveRecord::Migration
+class AddPartNumberToProducts < ActiveRecord::Migration[5.0]
def change
end
end
@@ -146,7 +146,7 @@ $ bin/rails generate migration AddPartNumberToProducts part_number:string
will generate
```ruby
-class AddPartNumberToProducts < ActiveRecord::Migration
+class AddPartNumberToProducts < ActiveRecord::Migration[5.0]
def change
add_column :products, :part_number, :string
end
@@ -162,7 +162,7 @@ $ bin/rails generate migration AddPartNumberToProducts part_number:string:index
will generate
```ruby
-class AddPartNumberToProducts < ActiveRecord::Migration
+class AddPartNumberToProducts < ActiveRecord::Migration[5.0]
def change
add_column :products, :part_number, :string
add_index :products, :part_number
@@ -180,7 +180,7 @@ $ bin/rails generate migration RemovePartNumberFromProducts part_number:string
generates
```ruby
-class RemovePartNumberFromProducts < ActiveRecord::Migration
+class RemovePartNumberFromProducts < ActiveRecord::Migration[5.0]
def change
remove_column :products, :part_number, :string
end
@@ -196,7 +196,7 @@ $ bin/rails generate migration AddDetailsToProducts part_number:string price:dec
generates
```ruby
-class AddDetailsToProducts < ActiveRecord::Migration
+class AddDetailsToProducts < ActiveRecord::Migration[5.0]
def change
add_column :products, :part_number, :string
add_column :products, :price, :decimal
@@ -215,7 +215,7 @@ $ bin/rails generate migration CreateProducts name:string part_number:string
generates
```ruby
-class CreateProducts < ActiveRecord::Migration
+class CreateProducts < ActiveRecord::Migration[5.0]
def change
create_table :products do |t|
t.string :name
@@ -239,7 +239,7 @@ $ bin/rails generate migration AddUserRefToProducts user:references
generates
```ruby
-class AddUserRefToProducts < ActiveRecord::Migration
+class AddUserRefToProducts < ActiveRecord::Migration[5.0]
def change
add_reference :products, :user, index: true, foreign_key: true
end
@@ -257,7 +257,7 @@ $ bin/rails g migration CreateJoinTableCustomerProduct customer product
will produce the following migration:
```ruby
-class CreateJoinTableCustomerProduct < ActiveRecord::Migration
+class CreateJoinTableCustomerProduct < ActiveRecord::Migration[5.0]
def change
create_join_table :customers, :products do |t|
# t.index [:customer_id, :product_id]
@@ -281,7 +281,7 @@ $ bin/rails generate model Product name:string description:text
will create a migration that looks like this
```ruby
-class CreateProducts < ActiveRecord::Migration
+class CreateProducts < ActiveRecord::Migration[5.0]
def change
create_table :products do |t|
t.string :name
@@ -309,7 +309,7 @@ $ bin/rails generate migration AddDetailsToProducts 'price:decimal{5,2}' supplie
will produce a migration that looks like this
```ruby
-class AddDetailsToProducts < ActiveRecord::Migration
+class AddDetailsToProducts < ActiveRecord::Migration[5.0]
def change
add_column :products, :price, :decimal, precision: 5, scale: 2
add_reference :products, :supplier, polymorphic: true, index: true
@@ -563,7 +563,7 @@ to reverse. You can use `reversible` to specify what to do when running a
migration and what else to do when reverting it. For example:
```ruby
-class ExampleMigration < ActiveRecord::Migration
+class ExampleMigration < ActiveRecord::Migration[5.0]
def change
create_table :distributors do |t|
t.string :zipcode
@@ -616,7 +616,7 @@ is wise to perform the transformations in precisely the reverse order they were
made in the `up` method. The example in the `reversible` section is equivalent to:
```ruby
-class ExampleMigration < ActiveRecord::Migration
+class ExampleMigration < ActiveRecord::Migration[5.0]
def up
create_table :distributors do |t|
t.string :zipcode
@@ -659,7 +659,7 @@ You can use Active Record's ability to rollback migrations using the `revert` me
```ruby
require_relative '20121212123456_example_migration'
-class FixupExampleMigration < ActiveRecord::Migration
+class FixupExampleMigration < ActiveRecord::Migration[5.0]
def change
revert ExampleMigration
@@ -677,7 +677,7 @@ is later decided it would be best to use Active Record validations,
in place of the `CHECK` constraint, to verify the zipcode.
```ruby
-class DontUseConstraintForZipcodeValidationMigration < ActiveRecord::Migration
+class DontUseConstraintForZipcodeValidationMigration < ActiveRecord::Migration[5.0]
def change
revert do
# copy-pasted code from ExampleMigration
@@ -720,7 +720,7 @@ Running Migrations
Rails provides a set of Rake tasks to run certain sets of migrations.
The very first migration related Rake task you will use will probably be
-`rake db:migrate`. In its most basic form it just runs the `change` or `up`
+`rails db:migrate`. In its most basic form it just runs the `change` or `up`
method for all the migrations that have not yet been run. If there are
no such migrations, it exits. It will run these migrations in order based
on the date of the migration.
@@ -734,7 +734,7 @@ is the numerical prefix on the migration's filename. For example, to migrate
to version 20080906120000 run:
```bash
-$ bin/rake db:migrate VERSION=20080906120000
+$ bin/rails db:migrate VERSION=20080906120000
```
If version 20080906120000 is greater than the current version (i.e., it is
@@ -751,7 +751,7 @@ mistake in it and wish to correct it. Rather than tracking down the version
number associated with the previous migration you can run:
```bash
-$ bin/rake db:rollback
+$ bin/rails db:rollback
```
This will rollback the latest migration, either by reverting the `change`
@@ -759,7 +759,7 @@ method or by running the `down` method. If you need to undo
several migrations you can provide a `STEP` parameter:
```bash
-$ bin/rake db:rollback STEP=3
+$ bin/rails db:rollback STEP=3
```
will revert the last 3 migrations.
@@ -769,7 +769,7 @@ back up again. As with the `db:rollback` task, you can use the `STEP` parameter
if you need to go more than one version back, for example:
```bash
-$ bin/rake db:migrate:redo STEP=3
+$ bin/rails db:migrate:redo STEP=3
```
Neither of these Rake tasks do anything you could not do with `db:migrate`. They
@@ -778,17 +778,17 @@ version to migrate to.
### Setup the Database
-The `rake db:setup` task will create the database, load the schema and initialize
+The `rails db:setup` task will create the database, load the schema and initialize
it with the seed data.
### Resetting the Database
-The `rake db:reset` task will drop the database and set it up again. This is
+The `rails db:reset` task will drop the database and set it up again. This is
functionally equivalent to `rake db:drop db:setup`.
NOTE: This is not the same as running all the migrations. It will only use the
contents of the current `db/schema.rb` or `db/structure.sql` file. If a migration can't be rolled back,
-`rake db:reset` may not help you. To find out more about dumping the schema see
+`rails db:reset` may not help you. To find out more about dumping the schema see
[Schema Dumping and You](#schema-dumping-and-you) section.
### Running Specific Migrations
@@ -799,7 +799,7 @@ the corresponding migration will have its `change`, `up` or `down` method
invoked, for example:
```bash
-$ bin/rake db:migrate:up VERSION=20080906120000
+$ bin/rails db:migrate:up VERSION=20080906120000
```
will run the 20080906120000 migration by running the `change` method (or the
@@ -815,7 +815,7 @@ To run migrations against another environment you can specify it using the
migrations against the `test` environment you could run:
```bash
-$ bin/rake db:migrate RAILS_ENV=test
+$ bin/rails db:migrate RAILS_ENV=test
```
### Changing the Output of Running Migrations
@@ -841,7 +841,7 @@ Several methods are provided in migrations that allow you to control all this:
For example, this migration:
```ruby
-class CreateProducts < ActiveRecord::Migration
+class CreateProducts < ActiveRecord::Migration[5.0]
def change
suppress_messages do
create_table :products do |t|
@@ -876,7 +876,7 @@ generates the following output
== CreateProducts: migrated (10.0054s) =======================================
```
-If you want Active Record to not output anything, then running `rake db:migrate
+If you want Active Record to not output anything, then running `rails db:migrate
VERBOSE=false` will suppress all output.
Changing Existing Migrations
@@ -885,9 +885,9 @@ Changing Existing Migrations
Occasionally you will make a mistake when writing a migration. If you have
already run the migration then you cannot just edit the migration and run the
migration again: Rails thinks it has already run the migration and so will do
-nothing when you run `rake db:migrate`. You must rollback the migration (for
+nothing when you run `rails db:migrate`. You must rollback the migration (for
example with `rake db:rollback`), edit your migration and then run
-`rake db:migrate` to run the corrected version.
+`rails db:migrate` to run the corrected version.
In general, editing existing migrations is not a good idea. You will be
creating extra work for yourself and your co-workers and cause major headaches
@@ -969,7 +969,7 @@ this, then you should set the schema format to `:sql`.
Instead of using Active Record's schema dumper, the database's structure will
be dumped using a tool specific to the database (via the `db:structure:dump`
-Rake task) into `db/structure.sql`. For example, for PostgreSQL, the `pg_dump`
+rails task) into `db/structure.sql`. For example, for PostgreSQL, the `pg_dump`
utility is used. For MySQL, this file will contain the output of
`SHOW CREATE TABLE` for the various tables.
@@ -1015,7 +1015,7 @@ to add or modify data. This is useful in an existing database that can't be dest
and recreated, such as a production database.
```ruby
-class AddInitialProducts < ActiveRecord::Migration
+class AddInitialProducts < ActiveRecord::Migration[5.0]
def up
5.times do |i|
Product.create(name: "Product ##{i}", description: "A product.")
@@ -1032,7 +1032,7 @@ To add initial data after a database is created, Rails has a built-in
'seeds' feature that makes the process quick and easy. This is especially
useful when reloading the database frequently in development and test environments.
It's easy to get started with this feature: just fill up `db/seeds.rb` with some
-Ruby code, and run `rake db:seed`:
+Ruby code, and run `rails db:seed`:
```ruby
5.times do |i|
diff --git a/guides/source/active_record_postgresql.md b/guides/source/active_record_postgresql.md
index 742db7be32..b592209d4b 100644
--- a/guides/source/active_record_postgresql.md
+++ b/guides/source/active_record_postgresql.md
@@ -39,7 +39,7 @@ create_table :documents do |t|
end
# app/models/document.rb
-class Document < ActiveRecord::Base
+class Document < ApplicationRecord
end
# Usage
@@ -63,7 +63,7 @@ add_index :books, :tags, using: 'gin'
add_index :books, :ratings, using: 'gin'
# app/models/book.rb
-class Book < ActiveRecord::Base
+class Book < ApplicationRecord
end
# Usage
@@ -97,7 +97,7 @@ ActiveRecord::Schema.define do
end
# app/models/profile.rb
-class Profile < ActiveRecord::Base
+class Profile < ApplicationRecord
end
# Usage
@@ -122,7 +122,7 @@ create_table :events do |t|
end
# app/models/event.rb
-class Event < ActiveRecord::Base
+class Event < ApplicationRecord
end
# Usage
@@ -150,7 +150,7 @@ create_table :events do |t|
end
# app/models/event.rb
-class Event < ActiveRecord::Base
+class Event < ApplicationRecord
end
# Usage
@@ -200,7 +200,7 @@ create_table :contacts do |t|
end
# app/models/contact.rb
-class Contact < ActiveRecord::Base
+class Contact < ApplicationRecord
end
# Usage
@@ -239,7 +239,7 @@ def down
end
# app/models/article.rb
-class Article < ActiveRecord::Base
+class Article < ApplicationRecord
end
# Usage
@@ -294,7 +294,7 @@ create_table :revisions do |t|
end
# app/models/revision.rb
-class Revision < ActiveRecord::Base
+class Revision < ApplicationRecord
end
# Usage
@@ -317,12 +317,12 @@ create_table :comments, id: :uuid, default: 'gen_random_uuid()' do |t|
end
# app/models/post.rb
-class Post < ActiveRecord::Base
+class Post < ApplicationRecord
has_many :comments
end
# app/models/comment.rb
-class Comment < ActiveRecord::Base
+class Comment < ApplicationRecord
belongs_to :post
end
```
@@ -341,7 +341,7 @@ create_table :users, force: true do |t|
end
# app/models/device.rb
-class User < ActiveRecord::Base
+class User < ApplicationRecord
end
# Usage
@@ -370,7 +370,7 @@ create_table(:devices, force: true) do |t|
end
# app/models/device.rb
-class Device < ActiveRecord::Base
+class Device < ApplicationRecord
end
# Usage
@@ -410,7 +410,7 @@ create_table :devices, id: :uuid, default: 'gen_random_uuid()' do |t|
end
# app/models/device.rb
-class Device < ActiveRecord::Base
+class Device < ApplicationRecord
end
# Usage
@@ -434,7 +434,7 @@ end
execute "CREATE INDEX documents_idx ON documents USING gin(to_tsvector('english', title || ' ' || body));"
# app/models/document.rb
-class Document < ActiveRecord::Base
+class Document < ApplicationRecord
end
# Usage
@@ -484,7 +484,7 @@ CREATE VIEW articles AS
SQL
# app/models/article.rb
-class Article < ActiveRecord::Base
+class Article < ApplicationRecord
self.primary_key = "id"
def archive!
update_attribute :archived, true
diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md
index ec31fa9d67..4606ac4683 100644
--- a/guides/source/active_record_querying.md
+++ b/guides/source/active_record_querying.md
@@ -25,7 +25,7 @@ Code examples throughout this guide will refer to one or more of the following m
TIP: All of the following models use `id` as the primary key, unless specified otherwise.
```ruby
-class Client < ActiveRecord::Base
+class Client < ApplicationRecord
has_one :address
has_many :orders
has_and_belongs_to_many :roles
@@ -33,19 +33,19 @@ end
```
```ruby
-class Address < ActiveRecord::Base
+class Address < ApplicationRecord
belongs_to :client
end
```
```ruby
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
belongs_to :client, counter_cache: true
end
```
```ruby
-class Role < ActiveRecord::Base
+class Role < ApplicationRecord
has_and_belongs_to_many :clients
end
```
@@ -740,7 +740,7 @@ SELECT "articles".* FROM "articles" WHERE (id > 10) ORDER BY id desc LIMIT 20
The `reorder` method overrides the default scope order. For example:
```ruby
-class Article < ActiveRecord::Base
+class Article < ApplicationRecord
has_many :comments, -> { order('posted_at DESC') }
end
@@ -889,7 +889,7 @@ This behavior can be turned off by setting `ActiveRecord::Base.lock_optimistical
To override the name of the `lock_version` column, `ActiveRecord::Base` provides a class attribute called `locking_column`:
```ruby
-class Client < ActiveRecord::Base
+class Client < ApplicationRecord
self.locking_column = :lock_client_column
end
```
@@ -970,26 +970,26 @@ Active Record lets you use the names of the [associations](association_basics.ht
For example, consider the following `Category`, `Article`, `Comment`, `Guest` and `Tag` models:
```ruby
-class Category < ActiveRecord::Base
+class Category < ApplicationRecord
has_many :articles
end
-class Article < ActiveRecord::Base
+class Article < ApplicationRecord
belongs_to :category
has_many :comments
has_many :tags
end
-class Comment < ActiveRecord::Base
+class Comment < ApplicationRecord
belongs_to :article
has_one :guest
end
-class Guest < ActiveRecord::Base
+class Guest < ApplicationRecord
belongs_to :comment
end
-class Tag < ActiveRecord::Base
+class Tag < ApplicationRecord
belongs_to :article
end
```
@@ -1199,7 +1199,7 @@ Scoping allows you to specify commonly-used queries which can be referenced as m
To define a simple scope, we use the `scope` method inside the class, passing the query that we'd like to run when this scope is called:
```ruby
-class Article < ActiveRecord::Base
+class Article < ApplicationRecord
scope :published, -> { where(published: true) }
end
```
@@ -1207,7 +1207,7 @@ end
This is exactly the same as defining a class method, and which you use is a matter of personal preference:
```ruby
-class Article < ActiveRecord::Base
+class Article < ApplicationRecord
def self.published
where(published: true)
end
@@ -1217,7 +1217,7 @@ end
Scopes are also chainable within scopes:
```ruby
-class Article < ActiveRecord::Base
+class Article < ApplicationRecord
scope :published, -> { where(published: true) }
scope :published_and_commented, -> { published.where("comments_count > 0") }
end
@@ -1241,7 +1241,7 @@ category.articles.published # => [published articles belonging to this category]
Your scope can take arguments:
```ruby
-class Article < ActiveRecord::Base
+class Article < ApplicationRecord
scope :created_before, ->(time) { where("created_at < ?", time) }
end
```
@@ -1255,7 +1255,7 @@ Article.created_before(Time.zone.now)
However, this is just duplicating the functionality that would be provided to you by a class method.
```ruby
-class Article < ActiveRecord::Base
+class Article < ApplicationRecord
def self.created_before(time)
where("created_at < ?", time)
end
@@ -1274,7 +1274,7 @@ If we wish for a scope to be applied across all queries to the model we can use
`default_scope` method within the model itself.
```ruby
-class Client < ActiveRecord::Base
+class Client < ApplicationRecord
default_scope { where("removed_at IS NULL") }
end
```
@@ -1290,7 +1290,7 @@ If you need to do more complex things with a default scope, you can alternativel
define it as a class method:
```ruby
-class Client < ActiveRecord::Base
+class Client < ApplicationRecord
def self.default_scope
# Should return an ActiveRecord::Relation.
end
@@ -1301,7 +1301,7 @@ NOTE: The `default_scope` is also applied while creating/building a record.
It is not applied while updating a record. E.g.:
```ruby
-class Client < ActiveRecord::Base
+class Client < ApplicationRecord
default_scope { where(active: true) }
end
@@ -1314,7 +1314,7 @@ Client.unscoped.new # => #<Client id: nil, active: nil>
Just like `where` clauses scopes are merged using `AND` conditions.
```ruby
-class User < ActiveRecord::Base
+class User < ApplicationRecord
scope :active, -> { where state: 'active' }
scope :inactive, -> { where state: 'inactive' }
end
@@ -1343,7 +1343,7 @@ One important caveat is that `default_scope` will be prepended in
`scope` and `where` conditions.
```ruby
-class User < ActiveRecord::Base
+class User < ApplicationRecord
default_scope { where state: 'pending' }
scope :active, -> { where state: 'active' }
scope :inactive, -> { where state: 'inactive' }
@@ -1374,8 +1374,15 @@ Client.unscoped.load
This method removes all scoping and will do a normal query on the table.
-Note that chaining `unscoped` with a `scope` does not work. In these cases, it is
-recommended that you use the block form of `unscoped`:
+```ruby
+Client.unscoped.all
+# SELECT "clients".* FROM "clients"
+
+Client.where(published: false).unscoped.all
+# SELECT "clients".* FROM "clients"
+```
+
+`unscoped` can also accept a block.
```ruby
Client.unscoped {
@@ -1392,6 +1399,36 @@ You can specify an exclamation point (`!`) on the end of the dynamic finders to
If you want to find both by name and locked, you can chain these finders together by simply typing "`and`" between the fields. For example, `Client.find_by_first_name_and_locked("Ryan", true)`.
+Enums
+-----
+
+The `enum` macro maps an integer column to a set of possible values.
+
+```ruby
+class Book < ApplicationRecord
+ enum availability: [:available, :unavailable]
+end
+```
+
+This will automatically create the corresponding [scopes](#scopes) to query the
+model. Methods to transition between states and query the current state are also
+added.
+
+```ruby
+# Both examples below query just available books.
+Book.available
+# or
+Book.where(availability: :available)
+
+book = Book.new(availability: :available)
+book.available? # => true
+book.unavailable! # => true
+book.available? # => false
+```
+
+Read the full documentation about enums
+[in the Rails API docs](http://api.rubyonrails.org/classes/ActiveRecord/Enum.html).
+
Understanding The Method Chaining
---------------------------------
@@ -1620,7 +1657,7 @@ a large or often-running query. However, any model method overrides will
not be available. For example:
```ruby
-class Client < ActiveRecord::Base
+class Client < ApplicationRecord
def name
"I am #{super}"
end
@@ -1655,7 +1692,7 @@ Person.ids
```
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
self.primary_key = "person_id"
end
diff --git a/guides/source/active_record_validations.md b/guides/source/active_record_validations.md
index fe42cec158..dd7adf09a2 100644
--- a/guides/source/active_record_validations.md
+++ b/guides/source/active_record_validations.md
@@ -20,7 +20,7 @@ Validations Overview
Here's an example of a very simple validation:
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validates :name, presence: true
end
@@ -80,7 +80,7 @@ method to determine whether an object is already in the database or not.
Consider the following simple Active Record class:
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
end
```
@@ -157,7 +157,7 @@ and returns true if no errors were found in the object, and false otherwise.
As you saw above:
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validates :name, presence: true
end
@@ -175,7 +175,7 @@ even if it's technically invalid, because validations are automatically run
only when the object is saved, such as with the `create` or `save` methods.
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validates :name, presence: true
end
@@ -221,7 +221,7 @@ it doesn't verify the validity of the object as a whole. It only checks to see
whether there are errors found on an individual attribute of the object.
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validates :name, presence: true
end
@@ -239,7 +239,7 @@ To check which validations failed on an invalid attribute, you can use
key to get the symbol of the validator:
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validates :name, presence: true
end
@@ -285,7 +285,7 @@ the field does exist in your database, the `accept` option must be set to
`true` or else the validation will not run.
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validates :terms_of_service, acceptance: true
end
```
@@ -297,7 +297,7 @@ It can receive an `:accept` option, which determines the value that will be
considered acceptance. It defaults to "1" and can be easily changed.
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validates :terms_of_service, acceptance: { accept: 'yes' }
end
```
@@ -309,7 +309,7 @@ and they also need to be validated. When you try to save your object, `valid?`
will be called upon each one of the associated objects.
```ruby
-class Library < ActiveRecord::Base
+class Library < ApplicationRecord
has_many :books
validates_associated :books
end
@@ -332,7 +332,7 @@ or a password. This validation creates a virtual attribute whose name is the
name of the field that has to be confirmed with "_confirmation" appended.
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validates :email, confirmation: true
end
```
@@ -349,7 +349,7 @@ confirmation, make sure to add a presence check for the confirmation attribute
(we'll take a look at `presence` later on in this guide):
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validates :email, confirmation: true
validates :email_confirmation, presence: true
end
@@ -360,7 +360,7 @@ confirmation constraint will be case sensitive or not. This option defaults to
true.
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validates :email, confirmation: { case_sensitive: false }
end
```
@@ -373,7 +373,7 @@ This helper validates that the attributes' values are not included in a given
set. In fact, this set can be any enumerable object.
```ruby
-class Account < ActiveRecord::Base
+class Account < ApplicationRecord
validates :subdomain, exclusion: { in: %w(www us ca jp),
message: "%{value} is reserved." }
end
@@ -393,7 +393,7 @@ This helper validates the attributes' values by testing whether they match a
given regular expression, which is specified using the `:with` option.
```ruby
-class Product < ActiveRecord::Base
+class Product < ApplicationRecord
validates :legacy_code, format: { with: /\A[a-zA-Z]+\z/,
message: "only allows letters" }
end
@@ -409,7 +409,7 @@ This helper validates that the attributes' values are included in a given set.
In fact, this set can be any enumerable object.
```ruby
-class Coffee < ActiveRecord::Base
+class Coffee < ApplicationRecord
validates :size, inclusion: { in: %w(small medium large),
message: "%{value} is not a valid size" }
end
@@ -428,7 +428,7 @@ This helper validates the length of the attributes' values. It provides a
variety of options, so you can specify length constraints in different ways:
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validates :name, length: { minimum: 2 }
validates :bio, length: { maximum: 500 }
validates :password, length: { in: 6..20 }
@@ -451,7 +451,7 @@ number corresponding to the length constraint being used. You can still use the
`:message` option to specify an error message.
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validates :bio, length: { maximum: 1000,
too_long: "%{count} characters is the maximum allowed" }
end
@@ -483,7 +483,7 @@ WARNING. Note that the regular expression above allows a trailing newline
character.
```ruby
-class Player < ActiveRecord::Base
+class Player < ApplicationRecord
validates :points, numericality: true
validates :games_played, numericality: { only_integer: true }
end
@@ -521,7 +521,7 @@ This helper validates that the specified attributes are not empty. It uses the
is, a string that is either empty or consists of whitespace.
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validates :name, :login, :email, presence: true
end
```
@@ -531,7 +531,7 @@ whether the associated object itself is present, and not the foreign key used
to map the association.
```ruby
-class LineItem < ActiveRecord::Base
+class LineItem < ApplicationRecord
belongs_to :order
validates :order, presence: true
end
@@ -541,7 +541,7 @@ In order to validate associated records whose presence is required, you must
specify the `:inverse_of` option for the association:
```ruby
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
has_many :line_items, inverse_of: :order
end
```
@@ -568,7 +568,7 @@ This helper validates that the specified attributes are absent. It uses the
is, a string that is either empty or consists of whitespace.
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validates :name, :login, :email, absence: true
end
```
@@ -578,7 +578,7 @@ whether the associated object itself is absent, and not the foreign key used
to map the association.
```ruby
-class LineItem < ActiveRecord::Base
+class LineItem < ApplicationRecord
belongs_to :order
validates :order, absence: true
end
@@ -588,7 +588,7 @@ In order to validate associated records whose absence is required, you must
specify the `:inverse_of` option for the association:
```ruby
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
has_many :line_items, inverse_of: :order
end
```
@@ -611,7 +611,7 @@ with the same value for a column that you intend to be unique. To avoid that,
you must create a unique index on that column in your database.
```ruby
-class Account < ActiveRecord::Base
+class Account < ApplicationRecord
validates :email, uniqueness: true
end
```
@@ -623,7 +623,7 @@ There is a `:scope` option that you can use to specify one or more attributes th
are used to limit the uniqueness check:
```ruby
-class Holiday < ActiveRecord::Base
+class Holiday < ApplicationRecord
validates :name, uniqueness: { scope: :year,
message: "should happen once per year" }
end
@@ -635,7 +635,7 @@ uniqueness constraint will be case sensitive or not. This option defaults to
true.
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validates :name, uniqueness: { case_sensitive: false }
end
```
@@ -658,7 +658,7 @@ class GoodnessValidator < ActiveModel::Validator
end
end
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validates_with GoodnessValidator
end
```
@@ -686,7 +686,7 @@ class GoodnessValidator < ActiveModel::Validator
end
end
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validates_with GoodnessValidator, fields: [:first_name, :last_name]
end
```
@@ -699,7 +699,7 @@ If your validator is complex enough that you want instance variables, you can
easily use a plain old Ruby object instead:
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validate do |person|
GoodnessValidator.new(person).validate
end
@@ -728,7 +728,7 @@ passed to `validates_each` will be tested against it. In the following example,
we don't want names and surnames to begin with lower case.
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validates_each :name, :surname do |record, attr, value|
record.errors.add(attr, 'must start with upper case') if value =~ /\A[[:lower:]]/
end
@@ -751,7 +751,7 @@ The `:allow_nil` option skips the validation when the value being validated is
`nil`.
```ruby
-class Coffee < ActiveRecord::Base
+class Coffee < ApplicationRecord
validates :size, inclusion: { in: %w(small medium large),
message: "%{value} is not a valid size" }, allow_nil: true
end
@@ -764,7 +764,7 @@ will let validation pass if the attribute's value is `blank?`, like `nil` or an
empty string for example.
```ruby
-class Topic < ActiveRecord::Base
+class Topic < ApplicationRecord
validates :title, length: { is: 5 }, allow_blank: true
end
@@ -777,7 +777,36 @@ Topic.create(title: nil).valid? # => true
As you've already seen, the `:message` option lets you specify the message that
will be added to the `errors` collection when validation fails. When this
option is not used, Active Record will use the respective default error message
-for each validation helper.
+for each validation helper. The `:message` option accepts a `String` or `Proc`.
+
+A `String` `:message` value can optionally contain any/all of `%{value}`,
+`%{attribute}`, and `%{model}` which will be dynamically replaced when
+validation fails.
+
+A `Proc` `:message` value is given two arguments: a message key for i18n, and
+a hash with `:model`, `:attribute`, and `:value` key-value pairs.
+
+```ruby
+class Person < ApplicationRecord
+ # Hard-coded message
+ validates :name, presence: { message: "must be given please" }
+
+ # Message with dynamic attribute value. %{value} will be replaced with
+ # the actual value of the attribute. %{attribute} and %{model} also
+ # available.
+ validates :age, numericality: { message: "%{value} seems wrong" }
+
+ # Proc
+ validates :username,
+ uniqueness: {
+ # key = "activerecord.errors.models.person.attributes.username.taken"
+ # data = { model: "Person", attribute: "Username", value: <username> }
+ message: ->(key, data) do
+ "#{data[:value]} taken! Try again #{Time.zone.tomorrow}"
+ end
+ }
+end
+```
### `:on`
@@ -789,7 +818,7 @@ new record is created or `on: :update` to run the validation only when a record
is updated.
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
# it will be possible to update email with a duplicated value
validates :email, uniqueness: true, on: :create
@@ -808,7 +837,7 @@ You can also specify validations to be strict and raise
`ActiveModel::StrictValidationFailed` when the object is invalid.
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validates :name, presence: { strict: true }
end
@@ -818,7 +847,7 @@ Person.new.valid? # => ActiveModel::StrictValidationFailed: Name can't be blank
There is also the ability to pass a custom exception to the `:strict` option.
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validates :token, presence: true, uniqueness: true, strict: TokenGenerationException
end
@@ -842,7 +871,7 @@ to the name of a method that will get called right before validation happens.
This is the most commonly used option.
```ruby
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
validates :card_number, presence: true, if: :paid_with_card?
def paid_with_card?
@@ -858,7 +887,7 @@ contain valid Ruby code. You should use this option only when the string
represents a really short condition.
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validates :surname, presence: true, if: "name.nil?"
end
```
@@ -871,7 +900,7 @@ inline condition instead of a separate method. This option is best suited for
one-liners.
```ruby
-class Account < ActiveRecord::Base
+class Account < ApplicationRecord
validates :password, confirmation: true,
unless: Proc.new { |a| a.password.blank? }
end
@@ -883,7 +912,7 @@ Sometimes it is useful to have multiple validations use one condition. It can
be easily achieved using `with_options`.
```ruby
-class User < ActiveRecord::Base
+class User < ApplicationRecord
with_options if: :is_admin? do |admin|
admin.validates :password, length: { minimum: 10 }
admin.validates :email, presence: true
@@ -901,7 +930,7 @@ should happen, an `Array` can be used. Moreover, you can apply both `:if` and
`:unless` to the same validation.
```ruby
-class Computer < ActiveRecord::Base
+class Computer < ApplicationRecord
validates :mouse, presence: true,
if: ["market.retail?", :desktop?],
unless: Proc.new { |c| c.trackpad.present? }
@@ -955,7 +984,7 @@ class EmailValidator < ActiveModel::EachValidator
end
end
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validates :email, presence: true, email: true
end
```
@@ -979,7 +1008,7 @@ so your custom validation methods should add errors to it when you
wish validation to fail:
```ruby
-class Invoice < ActiveRecord::Base
+class Invoice < ApplicationRecord
validate :expiration_date_cannot_be_in_the_past,
:discount_cannot_be_greater_than_total_value
@@ -1003,7 +1032,7 @@ custom validations by giving an `:on` option to the `validate` method,
with either: `:create` or `:update`.
```ruby
-class Invoice < ActiveRecord::Base
+class Invoice < ApplicationRecord
validate :active_customer, on: :create
def active_customer
@@ -1024,7 +1053,7 @@ The following is a list of the most commonly used methods. Please refer to the `
Returns an instance of the class `ActiveModel::Errors` containing all errors. Each key is the attribute name and the value is an array of strings with all errors.
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validates :name, presence: true, length: { minimum: 3 }
end
@@ -1043,7 +1072,7 @@ person.errors.messages # => {}
`errors[]` is used when you want to check the error messages for a specific attribute. It returns an array of strings with all error messages for the given attribute, each string with one error message. If there are no errors related to the attribute, it returns an empty array.
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validates :name, presence: true, length: { minimum: 3 }
end
@@ -1068,7 +1097,7 @@ The `add` method lets you add an error message related to a particular attribute
The `errors.full_messages` method (or its equivalent, `errors.to_a`) returns the error messages in a user-friendly format, with the capitalized attribute name prepended to each message, as shown in the examples below.
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
def a_method_used_for_validation_purposes
errors.add(:name, "cannot contain the characters !@#%*()_-+=")
end
@@ -1086,7 +1115,7 @@ person.errors.full_messages
An equivalent to `errors#add` is to use `<<` to append a message to the `errors.messages` array for an attribute:
```ruby
- class Person < ActiveRecord::Base
+ class Person < ApplicationRecord
def a_method_used_for_validation_purposes
errors.messages[:name] << "cannot contain the characters !@#%*()_-+="
end
@@ -1107,7 +1136,7 @@ You can specify a validator type to the returned error details hash using the
`errors.add` method.
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
def a_method_used_for_validation_purposes
errors.add(:name, :invalid_characters)
end
@@ -1123,7 +1152,7 @@ To improve the error details to contain the unallowed characters set for instanc
you can pass additional keys to `errors.add`.
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
def a_method_used_for_validation_purposes
errors.add(:name, :invalid_characters, not_allowed: "!@#%*()_-+=")
end
@@ -1143,7 +1172,7 @@ validator type.
You can add error messages that are related to the object's state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of its attributes. Since `errors[:base]` is an array, you can simply add a string to it and it will be used as an error message.
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
def a_method_used_for_validation_purposes
errors[:base] << "This person is invalid because ..."
end
@@ -1155,7 +1184,7 @@ end
The `clear` method is used when you intentionally want to clear all the messages in the `errors` collection. Of course, calling `errors.clear` upon an invalid object won't actually make it valid: the `errors` collection will now be empty, but the next time you call `valid?` or any method that tries to save this object to the database, the validations will run again. If any of the validations fail, the `errors` collection will be filled again.
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validates :name, presence: true, length: { minimum: 3 }
end
@@ -1178,7 +1207,7 @@ p.errors[:name]
The `size` method returns the total number of error messages for the object.
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
validates :name, presence: true, length: { minimum: 3 }
end
diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md
index 181dca4b71..0cb34aa8bc 100644
--- a/guides/source/active_support_core_extensions.md
+++ b/guides/source/active_support_core_extensions.md
@@ -397,7 +397,7 @@ The method `with_options` provides a way to factor out common options in a serie
Given a default options hash, `with_options` yields a proxy object to a block. Within the block, methods called on the proxy are forwarded to the receiver with their options merged. For example, you get rid of the duplication in:
```ruby
-class Account < ActiveRecord::Base
+class Account < ApplicationRecord
has_many :customers, dependent: :destroy
has_many :products, dependent: :destroy
has_many :invoices, dependent: :destroy
@@ -408,7 +408,7 @@ end
this way:
```ruby
-class Account < ActiveRecord::Base
+class Account < ApplicationRecord
with_options dependent: :destroy do |assoc|
assoc.has_many :customers
assoc.has_many :products
@@ -517,17 +517,17 @@ Extensions to `Module`
Using plain Ruby you can wrap methods with other methods, that's called _alias chaining_.
-For example, let's say you'd like params to be strings in functional tests, as they are in real requests, but still want the convenience of assigning integers and other kind of values. To accomplish that you could wrap `ActionController::TestCase#process` this way in `test/test_helper.rb`:
+For example, let's say you'd like params to be strings in functional tests, as they are in real requests, but still want the convenience of assigning integers and other kind of values. To accomplish that you could wrap `ActionDispatch::IntegrationTest#process` this way in `test/test_helper.rb`:
```ruby
-ActionController::TestCase.class_eval do
+ActionDispatch::IntegrationTest.class_eval do
# save a reference to the original process method
alias_method :original_process, :process
# now redefine process and delegate to original_process
- def process(action, params=nil, session=nil, flash=nil, http_method='GET')
+ def process('GET', path, params: nil, headers: nil, env: nil, xhr: false)
params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten]
- original_process(action, params, session, flash, http_method)
+ original_process('GET', path, params: params)
end
end
```
@@ -537,10 +537,10 @@ That's the method `get`, `post`, etc., delegate the work to.
That technique has a risk, it could be the case that `:original_process` was taken. To try to avoid collisions people choose some label that characterizes what the chaining is about:
```ruby
-ActionController::TestCase.class_eval do
+ActionDispatch::IntegrationTest.class_eval do
def process_with_stringified_params(...)
params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten]
- process_without_stringified_params(action, params, session, flash, http_method)
+ process_without_stringified_params(method, path, params: params)
end
alias_method :process_without_stringified_params, :process
alias_method :process, :process_with_stringified_params
@@ -550,10 +550,10 @@ end
The method `alias_method_chain` provides a shortcut for that pattern:
```ruby
-ActionController::TestCase.class_eval do
+ActionDispatch::IntegrationTest.class_eval do
def process_with_stringified_params(...)
params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten]
- process_without_stringified_params(action, params, session, flash, http_method)
+ process_without_stringified_params(method, path, params: params)
end
alias_method_chain :process, :stringified_params
end
@@ -568,7 +568,7 @@ NOTE: Defined in `active_support/core_ext/module/aliasing.rb`.
Model attributes have a reader, a writer, and a predicate. You can alias a model attribute having the corresponding three methods defined for you in one shot. As in other aliasing methods, the new name is the first argument, and the old name is the second (one mnemonic is that they go in the same order as if you did an assignment):
```ruby
-class User < ActiveRecord::Base
+class User < ApplicationRecord
# You can refer to the email column as "login".
# This can be meaningful for authentication code.
alias_attribute :login, :email
@@ -876,7 +876,7 @@ The macro `delegate` offers an easy way to forward methods.
Let's imagine that users in some application have login information in the `User` model but name and other data in a separate `Profile` model:
```ruby
-class User < ActiveRecord::Base
+class User < ApplicationRecord
has_one :profile
end
```
@@ -884,7 +884,7 @@ end
With that configuration you get a user's name via their profile, `user.profile.name`, but it could be handy to still be able to access such attribute directly:
```ruby
-class User < ActiveRecord::Base
+class User < ApplicationRecord
has_one :profile
def name
@@ -896,7 +896,7 @@ end
That is what `delegate` does for you:
```ruby
-class User < ActiveRecord::Base
+class User < ApplicationRecord
has_one :profile
delegate :name, to: :profile
diff --git a/guides/source/api_app.md b/guides/source/api_app.md
index feaaff166a..86baa9ee84 100644
--- a/guides/source/api_app.md
+++ b/guides/source/api_app.md
@@ -163,6 +163,14 @@ class definition:
config.api_only = true
```
+Optionally, in `config/environments/development.rb` add the following line
+to render error responses using the API format (JSON by default) when it
+is a local request:
+
+```ruby
+config.debug_exception_response_format = :api
+```
+
Finally, inside `app/controllers/application_controller.rb`, instead of:
```ruby
@@ -208,7 +216,7 @@ building, and make sense in an API-only Rails application.
You can get a list of all middlewares in your application via:
```bash
-$ rake middleware
+$ rails middleware
```
### Using the Cache Middleware
@@ -221,7 +229,7 @@ For instance, using the `stale?` method:
```ruby
def show
- @post = Post.find(params[:id])
+ @post = Post.find(params[:id])
if stale?(last_modified: @post.updated_at)
render json: @post
@@ -240,7 +248,7 @@ cross-client caching in the call to `stale?`:
```ruby
def show
- @post = Post.find(params[:id])
+ @post = Post.find(params[:id])
if stale?(last_modified: @post.updated_at, public: true)
render json: @post
diff --git a/guides/source/api_documentation_guidelines.md b/guides/source/api_documentation_guidelines.md
index 73e62eb6d9..cd208c2e13 100644
--- a/guides/source/api_documentation_guidelines.md
+++ b/guides/source/api_documentation_guidelines.md
@@ -20,7 +20,7 @@ The [Rails API documentation](http://api.rubyonrails.org) is generated with
in the rails root directory, run `bundle install` and execute:
```bash
- bundle exec rake rdoc
+ ./bin/rails rdoc
```
Resulting HTML files can be found in the ./doc/rdoc directory.
diff --git a/guides/source/asset_pipeline.md b/guides/source/asset_pipeline.md
index 0f2283318a..0083fc0e6c 100644
--- a/guides/source/asset_pipeline.md
+++ b/guides/source/asset_pipeline.md
@@ -676,7 +676,7 @@ content changes.
### Precompiling Assets
-Rails comes bundled with a rake task to compile the asset manifests and other
+Rails comes bundled with a task to compile the asset manifests and other
files in the pipeline.
Compiled assets are written to the location specified in `config.assets.prefix`.
@@ -686,10 +686,10 @@ You can call this task on the server during deployment to create compiled
versions of your assets directly on the server. See the next section for
information on compiling locally.
-The rake task is:
+The task is:
```bash
-$ RAILS_ENV=production bin/rake assets:precompile
+$ RAILS_ENV=production bin/rails assets:precompile
```
Capistrano (v2.15.1 and above) includes a recipe to handle this in deployment.
@@ -731,7 +731,7 @@ Rails.application.config.assets.precompile += ['admin.js', 'admin.css', 'swfObje
NOTE. Always specify an expected compiled filename that ends with .js or .css,
even if you want to add Sass or CoffeeScript files to the precompile array.
-The rake task also generates a `manifest-md5hash.json` that contains a list with
+The task also generates a `manifest-md5hash.json` that contains a list with
all your assets and their respective fingerprints. This is used by the Rails
helper methods to avoid handing the mapping requests back to Sprockets. A
typical manifest file looks like:
diff --git a/guides/source/association_basics.md b/guides/source/association_basics.md
index c272daac28..d83dda7228 100644
--- a/guides/source/association_basics.md
+++ b/guides/source/association_basics.md
@@ -19,10 +19,10 @@ Why Associations?
In Rails, an _association_ is a connection between two Active Record models. Why do we need associations between models? Because they make common operations simpler and easier in your code. For example, consider a simple Rails application that includes a model for customers and a model for orders. Each customer can have many orders. Without associations, the model declarations would look like this:
```ruby
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
end
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
end
```
@@ -45,11 +45,11 @@ end
With Active Record associations, we can streamline these - and other - operations by declaratively telling Rails that there is a connection between the two models. Here's the revised code for setting up customers and orders:
```ruby
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :orders, dependent: :destroy
end
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
belongs_to :customer
end
```
@@ -89,7 +89,7 @@ In the remainder of this guide, you'll learn how to declare and use the various
A `belongs_to` association sets up a one-to-one connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model. For example, if your application includes customers and orders, and each order can be assigned to exactly one customer, you'd declare the order model this way:
```ruby
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
belongs_to :customer
end
```
@@ -101,7 +101,7 @@ NOTE: `belongs_to` associations _must_ use the singular term. If you used the pl
The corresponding migration might look like this:
```ruby
-class CreateOrders < ActiveRecord::Migration
+class CreateOrders < ActiveRecord::Migration[5.0]
def change
create_table :customers do |t|
t.string :name
@@ -122,7 +122,7 @@ end
A `has_one` association also sets up a one-to-one connection with another model, but with somewhat different semantics (and consequences). This association indicates that each instance of a model contains or possesses one instance of another model. For example, if each supplier in your application has only one account, you'd declare the supplier model like this:
```ruby
-class Supplier < ActiveRecord::Base
+class Supplier < ApplicationRecord
has_one :account
end
```
@@ -132,7 +132,7 @@ end
The corresponding migration might look like this:
```ruby
-class CreateSuppliers < ActiveRecord::Migration
+class CreateSuppliers < ActiveRecord::Migration[5.0]
def change
create_table :suppliers do |t|
t.string :name
@@ -164,7 +164,7 @@ end
A `has_many` association indicates a one-to-many connection with another model. You'll often find this association on the "other side" of a `belongs_to` association. This association indicates that each instance of the model has zero or more instances of another model. For example, in an application containing customers and orders, the customer model could be declared like this:
```ruby
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :orders
end
```
@@ -176,7 +176,7 @@ NOTE: The name of the other model is pluralized when declaring a `has_many` asso
The corresponding migration might look like this:
```ruby
-class CreateCustomers < ActiveRecord::Migration
+class CreateCustomers < ActiveRecord::Migration[5.0]
def change
create_table :customers do |t|
t.string :name
@@ -197,17 +197,17 @@ end
A `has_many :through` association is often used to set up a many-to-many connection with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding _through_ a third model. For example, consider a medical practice where patients make appointments to see physicians. The relevant association declarations could look like this:
```ruby
-class Physician < ActiveRecord::Base
+class Physician < ApplicationRecord
has_many :appointments
has_many :patients, through: :appointments
end
-class Appointment < ActiveRecord::Base
+class Appointment < ApplicationRecord
belongs_to :physician
belongs_to :patient
end
-class Patient < ActiveRecord::Base
+class Patient < ApplicationRecord
has_many :appointments
has_many :physicians, through: :appointments
end
@@ -218,7 +218,7 @@ end
The corresponding migration might look like this:
```ruby
-class CreateAppointments < ActiveRecord::Migration
+class CreateAppointments < ActiveRecord::Migration[5.0]
def change
create_table :physicians do |t|
t.string :name
@@ -255,17 +255,17 @@ WARNING: Automatic deletion of join models is direct, no destroy callbacks are t
The `has_many :through` association is also useful for setting up "shortcuts" through nested `has_many` associations. For example, if a document has many sections, and a section has many paragraphs, you may sometimes want to get a simple collection of all paragraphs in the document. You could set that up this way:
```ruby
-class Document < ActiveRecord::Base
+class Document < ApplicationRecord
has_many :sections
has_many :paragraphs, through: :sections
end
-class Section < ActiveRecord::Base
+class Section < ApplicationRecord
belongs_to :document
has_many :paragraphs
end
-class Paragraph < ActiveRecord::Base
+class Paragraph < ApplicationRecord
belongs_to :section
end
```
@@ -284,17 +284,17 @@ For example, if each supplier has one account, and each account is associated wi
supplier model could look like this:
```ruby
-class Supplier < ActiveRecord::Base
+class Supplier < ApplicationRecord
has_one :account
has_one :account_history, through: :account
end
-class Account < ActiveRecord::Base
+class Account < ApplicationRecord
belongs_to :supplier
has_one :account_history
end
-class AccountHistory < ActiveRecord::Base
+class AccountHistory < ApplicationRecord
belongs_to :account
end
```
@@ -304,7 +304,7 @@ end
The corresponding migration might look like this:
```ruby
-class CreateAccountHistories < ActiveRecord::Migration
+class CreateAccountHistories < ActiveRecord::Migration[5.0]
def change
create_table :suppliers do |t|
t.string :name
@@ -331,11 +331,11 @@ end
A `has_and_belongs_to_many` association creates a direct many-to-many connection with another model, with no intervening model. For example, if your application includes assemblies and parts, with each assembly having many parts and each part appearing in many assemblies, you could declare the models this way:
```ruby
-class Assembly < ActiveRecord::Base
+class Assembly < ApplicationRecord
has_and_belongs_to_many :parts
end
-class Part < ActiveRecord::Base
+class Part < ApplicationRecord
has_and_belongs_to_many :assemblies
end
```
@@ -345,7 +345,7 @@ end
The corresponding migration might look like this:
```ruby
-class CreateAssembliesAndParts < ActiveRecord::Migration
+class CreateAssembliesAndParts < ActiveRecord::Migration[5.0]
def change
create_table :assemblies do |t|
t.string :name
@@ -372,11 +372,11 @@ If you want to set up a one-to-one relationship between two models, you'll need
The distinction is in where you place the foreign key (it goes on the table for the class declaring the `belongs_to` association), but you should give some thought to the actual meaning of the data as well. The `has_one` relationship says that one of something is yours - that is, that something points back to you. For example, it makes more sense to say that a supplier owns an account than that an account owns a supplier. This suggests that the correct relationships are like this:
```ruby
-class Supplier < ActiveRecord::Base
+class Supplier < ApplicationRecord
has_one :account
end
-class Account < ActiveRecord::Base
+class Account < ApplicationRecord
belongs_to :supplier
end
```
@@ -384,7 +384,7 @@ end
The corresponding migration might look like this:
```ruby
-class CreateSuppliers < ActiveRecord::Migration
+class CreateSuppliers < ActiveRecord::Migration[5.0]
def change
create_table :suppliers do |t|
t.string :name
@@ -409,11 +409,11 @@ NOTE: Using `t.integer :supplier_id` makes the foreign key naming obvious and ex
Rails offers two different ways to declare a many-to-many relationship between models. The simpler way is to use `has_and_belongs_to_many`, which allows you to make the association directly:
```ruby
-class Assembly < ActiveRecord::Base
+class Assembly < ApplicationRecord
has_and_belongs_to_many :parts
end
-class Part < ActiveRecord::Base
+class Part < ApplicationRecord
has_and_belongs_to_many :assemblies
end
```
@@ -421,17 +421,17 @@ end
The second way to declare a many-to-many relationship is to use `has_many :through`. This makes the association indirectly, through a join model:
```ruby
-class Assembly < ActiveRecord::Base
+class Assembly < ApplicationRecord
has_many :manifests
has_many :parts, through: :manifests
end
-class Manifest < ActiveRecord::Base
+class Manifest < ApplicationRecord
belongs_to :assembly
belongs_to :part
end
-class Part < ActiveRecord::Base
+class Part < ApplicationRecord
has_many :manifests
has_many :assemblies, through: :manifests
end
@@ -446,15 +446,15 @@ You should use `has_many :through` if you need validations, callbacks or extra a
A slightly more advanced twist on associations is the _polymorphic association_. With polymorphic associations, a model can belong to more than one other model, on a single association. For example, you might have a picture model that belongs to either an employee model or a product model. Here's how this could be declared:
```ruby
-class Picture < ActiveRecord::Base
+class Picture < ApplicationRecord
belongs_to :imageable, polymorphic: true
end
-class Employee < ActiveRecord::Base
+class Employee < ApplicationRecord
has_many :pictures, as: :imageable
end
-class Product < ActiveRecord::Base
+class Product < ApplicationRecord
has_many :pictures, as: :imageable
end
```
@@ -466,7 +466,7 @@ Similarly, you can retrieve `@product.pictures`.
If you have an instance of the `Picture` model, you can get to its parent via `@picture.imageable`. To make this work, you need to declare both a foreign key column and a type column in the model that declares the polymorphic interface:
```ruby
-class CreatePictures < ActiveRecord::Migration
+class CreatePictures < ActiveRecord::Migration[5.0]
def change
create_table :pictures do |t|
t.string :name
@@ -483,7 +483,7 @@ end
This migration can be simplified by using the `t.references` form:
```ruby
-class CreatePictures < ActiveRecord::Migration
+class CreatePictures < ActiveRecord::Migration[5.0]
def change
create_table :pictures do |t|
t.string :name
@@ -501,7 +501,7 @@ end
In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as between manager and subordinates. This situation can be modeled with self-joining associations:
```ruby
-class Employee < ActiveRecord::Base
+class Employee < ApplicationRecord
has_many :subordinates, class_name: "Employee",
foreign_key: "manager_id"
@@ -514,7 +514,7 @@ With this setup, you can retrieve `@employee.subordinates` and `@employee.manage
In your migrations/schema, you will add a references column to the model itself.
```ruby
-class CreateEmployees < ActiveRecord::Migration
+class CreateEmployees < ActiveRecord::Migration[5.0]
def change
create_table :employees do |t|
t.references :manager, index: true
@@ -567,7 +567,7 @@ Associations are extremely useful, but they are not magic. You are responsible f
When you declare a `belongs_to` association, you need to create foreign keys as appropriate. For example, consider this model:
```ruby
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
belongs_to :customer
end
```
@@ -575,7 +575,7 @@ end
This declaration needs to be backed up by the proper foreign key declaration on the orders table:
```ruby
-class CreateOrders < ActiveRecord::Migration
+class CreateOrders < ActiveRecord::Migration[5.0]
def change
create_table :orders do |t|
t.datetime :order_date
@@ -599,11 +599,11 @@ WARNING: The precedence between model names is calculated using the `<=>` operat
Whatever the name, you must manually generate the join table with an appropriate migration. For example, consider these associations:
```ruby
-class Assembly < ActiveRecord::Base
+class Assembly < ApplicationRecord
has_and_belongs_to_many :parts
end
-class Part < ActiveRecord::Base
+class Part < ApplicationRecord
has_and_belongs_to_many :assemblies
end
```
@@ -611,7 +611,7 @@ end
These need to be backed up by a migration to create the `assemblies_parts` table. This table should be created without a primary key:
```ruby
-class CreateAssembliesPartsJoinTable < ActiveRecord::Migration
+class CreateAssembliesPartsJoinTable < ActiveRecord::Migration[5.0]
def change
create_table :assemblies_parts, id: false do |t|
t.integer :assembly_id
@@ -629,7 +629,7 @@ We pass `id: false` to `create_table` because that table does not represent a mo
You can also use the method `create_join_table`
```ruby
-class CreateAssembliesPartsJoinTable < ActiveRecord::Migration
+class CreateAssembliesPartsJoinTable < ActiveRecord::Migration[5.0]
def change
create_join_table :assemblies, :parts do |t|
t.index :assembly_id
@@ -646,11 +646,11 @@ By default, associations look for objects only within the current module's scope
```ruby
module MyApplication
module Business
- class Supplier < ActiveRecord::Base
+ class Supplier < ApplicationRecord
has_one :account
end
- class Account < ActiveRecord::Base
+ class Account < ApplicationRecord
belongs_to :supplier
end
end
@@ -662,13 +662,13 @@ This will work fine, because both the `Supplier` and the `Account` class are def
```ruby
module MyApplication
module Business
- class Supplier < ActiveRecord::Base
+ class Supplier < ApplicationRecord
has_one :account
end
end
module Billing
- class Account < ActiveRecord::Base
+ class Account < ApplicationRecord
belongs_to :supplier
end
end
@@ -680,14 +680,14 @@ To associate a model with a model in a different namespace, you must specify the
```ruby
module MyApplication
module Business
- class Supplier < ActiveRecord::Base
+ class Supplier < ApplicationRecord
has_one :account,
class_name: "MyApplication::Billing::Account"
end
end
module Billing
- class Account < ActiveRecord::Base
+ class Account < ApplicationRecord
belongs_to :supplier,
class_name: "MyApplication::Business::Supplier"
end
@@ -700,11 +700,11 @@ end
It's normal for associations to work in two directions, requiring declaration on two different models:
```ruby
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :orders
end
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
belongs_to :customer
end
```
@@ -722,11 +722,11 @@ c.first_name == o.customer.first_name # => false
This happens because `c` and `o.customer` are two different in-memory representations of the same data, and neither one is automatically refreshed from changes to the other. Active Record provides the `:inverse_of` option so that you can inform it of these relations:
```ruby
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :orders, inverse_of: :customer
end
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
belongs_to :customer, inverse_of: :orders
end
```
@@ -781,7 +781,7 @@ When you declare a `belongs_to` association, the declaring class automatically g
In all of these methods, `association` is replaced with the symbol passed as the first argument to `belongs_to`. For example, given the declaration:
```ruby
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
belongs_to :customer
end
```
@@ -848,7 +848,7 @@ Does the same as `create_association` above, but raises `ActiveRecord::RecordInv
While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the `belongs_to` association reference. Such customizations can easily be accomplished by passing options and scope blocks when you create the association. For example, this association uses two such options:
```ruby
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
belongs_to :customer, dependent: :destroy,
counter_cache: true
end
@@ -877,7 +877,7 @@ If you set the `:autosave` option to `true`, Rails will save any loaded members
If the name of the other model cannot be derived from the association name, you can use the `:class_name` option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is `Patron`, you'd set things up this way:
```ruby
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
belongs_to :customer, class_name: "Patron"
end
```
@@ -887,10 +887,10 @@ end
The `:counter_cache` option can be used to make finding the number of belonging objects more efficient. Consider these models:
```ruby
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
belongs_to :customer
end
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :orders
end
```
@@ -898,10 +898,10 @@ end
With these declarations, asking for the value of `@customer.orders.size` requires making a call to the database to perform a `COUNT(*)` query. To avoid this call, you can add a counter cache to the _belonging_ model:
```ruby
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
belongs_to :customer, counter_cache: true
end
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :orders
end
```
@@ -918,10 +918,10 @@ the `counter_cache` declaration instead of `true`. For example, to use
`count_of_orders` instead of `orders_count`:
```ruby
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
belongs_to :customer, counter_cache: :count_of_orders
end
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :orders
end
```
@@ -949,7 +949,7 @@ WARNING: You should not specify this option on a `belongs_to` association that i
By convention, Rails assumes that the column used to hold the foreign key on this model is the name of the association with the suffix `_id` added. The `:foreign_key` option lets you set the name of the foreign key directly:
```ruby
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
belongs_to :customer, class_name: "Patron",
foreign_key: "patron_id"
end
@@ -965,11 +965,11 @@ of its tables. The `:primary_key` option allows you to specify a different colum
For example, given we have a `users` table with `guid` as the primary key. If we want a separate `todos` table to hold the foreign key `user_id` in the `guid` column, then we can use `primary_key` to achieve this like so:
```ruby
-class User < ActiveRecord::Base
+class User < ApplicationRecord
self.primary_key = 'guid' # primary key is guid and not id
end
-class Todo < ActiveRecord::Base
+class Todo < ApplicationRecord
belongs_to :user, primary_key: 'guid'
end
```
@@ -982,11 +982,11 @@ When we execute `@user.todos.create` then the `@todo` record will have its
The `:inverse_of` option specifies the name of the `has_many` or `has_one` association that is the inverse of this association. Does not work in combination with the `:polymorphic` options.
```ruby
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :orders, inverse_of: :customer
end
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
belongs_to :customer, inverse_of: :orders
end
```
@@ -1000,11 +1000,11 @@ Passing `true` to the `:polymorphic` option indicates that this is a polymorphic
If you set the `:touch` option to `true`, then the `updated_at` or `updated_on` timestamp on the associated object will be set to the current time whenever this object is saved or destroyed:
```ruby
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
belongs_to :customer, touch: true
end
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :orders
end
```
@@ -1012,7 +1012,7 @@ end
In this case, saving or destroying an order will update the timestamp on the associated customer. You can also specify a particular timestamp attribute to update:
```ruby
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
belongs_to :customer, touch: :orders_updated_at
end
```
@@ -1031,7 +1031,7 @@ object won't be validated. By default, this option is set to `false`.
There may be times when you wish to customize the query used by `belongs_to`. Such customizations can be achieved via a scope block. For example:
```ruby
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
belongs_to :customer, -> { where active: true },
dependent: :destroy
end
@@ -1049,7 +1049,7 @@ You can use any of the standard [querying methods](active_record_querying.html)
The `where` method lets you specify the conditions that the associated object must meet.
```ruby
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
belongs_to :customer, -> { where active: true }
end
```
@@ -1059,16 +1059,16 @@ end
You can use the `includes` method to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
```ruby
-class LineItem < ActiveRecord::Base
+class LineItem < ApplicationRecord
belongs_to :order
end
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
belongs_to :customer
has_many :line_items
end
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :orders
end
```
@@ -1076,16 +1076,16 @@ end
If you frequently retrieve customers directly from line items (`@line_item.order.customer`), then you can make your code somewhat more efficient by including customers in the association from line items to orders:
```ruby
-class LineItem < ActiveRecord::Base
+class LineItem < ApplicationRecord
belongs_to :order, -> { includes :customer }
end
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
belongs_to :customer
has_many :line_items
end
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :orders
end
```
@@ -1133,7 +1133,7 @@ When you declare a `has_one` association, the declaring class automatically gain
In all of these methods, `association` is replaced with the symbol passed as the first argument to `has_one`. For example, given the declaration:
```ruby
-class Supplier < ActiveRecord::Base
+class Supplier < ApplicationRecord
has_one :account
end
```
@@ -1197,7 +1197,7 @@ Does the same as `create_association` above, but raises `ActiveRecord::RecordInv
While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the `has_one` association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this association uses two such options:
```ruby
-class Supplier < ActiveRecord::Base
+class Supplier < ApplicationRecord
has_one :account, class_name: "Billing", dependent: :nullify
end
```
@@ -1229,7 +1229,7 @@ If you set the `:autosave` option to `true`, Rails will save any loaded members
If the name of the other model cannot be derived from the association name, you can use the `:class_name` option to supply the model name. For example, if a supplier has an account, but the actual name of the model containing accounts is `Billing`, you'd set things up this way:
```ruby
-class Supplier < ActiveRecord::Base
+class Supplier < ApplicationRecord
has_one :account, class_name: "Billing"
end
```
@@ -1255,7 +1255,7 @@ unallowed `NULL` value.
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:
```ruby
-class Supplier < ActiveRecord::Base
+class Supplier < ApplicationRecord
has_one :account, foreign_key: "supp_id"
end
```
@@ -1267,11 +1267,11 @@ TIP: In any case, Rails will not create foreign key columns for you. You need to
The `:inverse_of` option specifies the name of the `belongs_to` association that is the inverse of this association. Does not work in combination with the `:through` or `:as` options.
```ruby
-class Supplier < ActiveRecord::Base
+class Supplier < ApplicationRecord
has_one :account, inverse_of: :supplier
end
-class Account < ActiveRecord::Base
+class Account < ApplicationRecord
belongs_to :supplier, inverse_of: :account
end
```
@@ -1301,7 +1301,7 @@ If you set the `:validate` option to `true`, then associated objects will be val
There may be times when you wish to customize the query used by `has_one`. Such customizations can be achieved via a scope block. For example:
```ruby
-class Supplier < ActiveRecord::Base
+class Supplier < ApplicationRecord
has_one :account, -> { where active: true }
end
```
@@ -1318,7 +1318,7 @@ You can use any of the standard [querying methods](active_record_querying.html)
The `where` method lets you specify the conditions that the associated object must meet.
```ruby
-class Supplier < ActiveRecord::Base
+class Supplier < ApplicationRecord
has_one :account, -> { where "confirmed = 1" }
end
```
@@ -1328,16 +1328,16 @@ end
You can use the `includes` method to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
```ruby
-class Supplier < ActiveRecord::Base
+class Supplier < ApplicationRecord
has_one :account
end
-class Account < ActiveRecord::Base
+class Account < ApplicationRecord
belongs_to :supplier
belongs_to :representative
end
-class Representative < ActiveRecord::Base
+class Representative < ApplicationRecord
has_many :accounts
end
```
@@ -1345,16 +1345,16 @@ end
If you frequently retrieve representatives directly from suppliers (`@supplier.account.representative`), then you can make your code somewhat more efficient by including representatives in the association from suppliers to accounts:
```ruby
-class Supplier < ActiveRecord::Base
+class Supplier < ApplicationRecord
has_one :account, -> { includes :representative }
end
-class Account < ActiveRecord::Base
+class Account < ApplicationRecord
belongs_to :supplier
belongs_to :representative
end
-class Representative < ActiveRecord::Base
+class Representative < ApplicationRecord
has_many :accounts
end
```
@@ -1415,7 +1415,7 @@ When you declare a `has_many` association, the declaring class automatically gai
In all of these methods, `collection` is replaced with the symbol passed as the first argument to `has_many`, and `collection_singular` is replaced with the singularized version of that symbol. For example, given the declaration:
```ruby
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :orders
end
```
@@ -1582,7 +1582,7 @@ Does the same as `collection.create` above, but raises `ActiveRecord::RecordInva
While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the `has_many` association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this association uses two such options:
```ruby
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :orders, dependent: :delete_all, validate: false
end
```
@@ -1615,7 +1615,7 @@ If you set the `:autosave` option to `true`, Rails will save any loaded members
If the name of the other model cannot be derived from the association name, you can use the `:class_name` option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is `Transaction`, you'd set things up this way:
```ruby
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :orders, class_name: "Transaction"
end
```
@@ -1639,7 +1639,7 @@ Controls what happens to the associated objects when their owner is destroyed:
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:
```ruby
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :orders, foreign_key: "cust_id"
end
```
@@ -1651,11 +1651,11 @@ TIP: In any case, Rails will not create foreign key columns for you. You need to
The `:inverse_of` option specifies the name of the `belongs_to` association that is the inverse of this association. Does not work in combination with the `:through` or `:as` options.
```ruby
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :orders, inverse_of: :customer
end
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
belongs_to :customer, inverse_of: :orders
end
```
@@ -1670,7 +1670,7 @@ hold the `guid` column value as the foreign key and not `id`
value. This can be achieved like this:
```ruby
-class User < ActiveRecord::Base
+class User < ApplicationRecord
has_many :todos, primary_key: :guid
end
```
@@ -1700,7 +1700,7 @@ If you set the `:validate` option to `false`, then associated objects will not b
There may be times when you wish to customize the query used by `has_many`. Such customizations can be achieved via a scope block. For example:
```ruby
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :orders, -> { where processed: true }
end
```
@@ -1723,7 +1723,7 @@ You can use any of the standard [querying methods](active_record_querying.html)
The `where` method lets you specify the conditions that the associated object must meet.
```ruby
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :confirmed_orders, -> { where "confirmed = 1" },
class_name: "Order"
end
@@ -1732,7 +1732,7 @@ end
You can also set conditions via a hash:
```ruby
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :confirmed_orders, -> { where confirmed: true },
class_name: "Order"
end
@@ -1749,7 +1749,7 @@ The `extending` method specifies a named module to extend the association proxy.
The `group` method supplies an attribute name to group the result set by, using a `GROUP BY` clause in the finder SQL.
```ruby
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :line_items, -> { group 'orders.id' },
through: :orders
end
@@ -1760,16 +1760,16 @@ end
You can use the `includes` method to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
```ruby
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :orders
end
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
belongs_to :customer
has_many :line_items
end
-class LineItem < ActiveRecord::Base
+class LineItem < ApplicationRecord
belongs_to :order
end
```
@@ -1777,16 +1777,16 @@ end
If you frequently retrieve line items directly from customers (`@customer.orders.line_items`), then you can make your code somewhat more efficient by including line items in the association from customers to orders:
```ruby
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :orders, -> { includes :line_items }
end
-class Order < ActiveRecord::Base
+class Order < ApplicationRecord
belongs_to :customer
has_many :line_items
end
-class LineItem < ActiveRecord::Base
+class LineItem < ApplicationRecord
belongs_to :order
end
```
@@ -1796,7 +1796,7 @@ end
The `limit` method lets you restrict the total number of objects that will be fetched through an association.
```ruby
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :recent_orders,
-> { order('order_date desc').limit(100) },
class_name: "Order",
@@ -1812,7 +1812,7 @@ The `offset` method lets you specify the starting offset for fetching objects vi
The `order` method dictates the order in which associated objects will be received (in the syntax used by an SQL `ORDER BY` clause).
```ruby
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :orders, -> { order "date_confirmed DESC" }
end
```
@@ -1833,7 +1833,7 @@ Use the `distinct` method to keep the collection free of duplicates. This is
mostly useful together with the `:through` option.
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
has_many :readings
has_many :articles, through: :readings
end
@@ -1927,7 +1927,7 @@ When you declare a `has_and_belongs_to_many` association, the declaring class au
In all of these methods, `collection` is replaced with the symbol passed as the first argument to `has_and_belongs_to_many`, and `collection_singular` is replaced with the singularized version of that symbol. For example, given the declaration:
```ruby
-class Part < ActiveRecord::Base
+class Part < ApplicationRecord
has_and_belongs_to_many :assemblies
end
```
@@ -2081,7 +2081,7 @@ Does the same as `collection.create`, but raises `ActiveRecord::RecordInvalid` i
While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the `has_and_belongs_to_many` association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this association uses two such options:
```ruby
-class Parts < ActiveRecord::Base
+class Parts < ApplicationRecord
has_and_belongs_to_many :assemblies, -> { readonly },
autosave: true
end
@@ -2103,7 +2103,7 @@ By convention, Rails assumes that the column in the join table used to hold the
TIP: The `:foreign_key` and `:association_foreign_key` options are useful when setting up a many-to-many self-join. For example:
```ruby
-class User < ActiveRecord::Base
+class User < ApplicationRecord
has_and_belongs_to_many :friends,
class_name: "User",
foreign_key: "this_user_id",
@@ -2120,7 +2120,7 @@ If you set the `:autosave` option to `true`, Rails will save any loaded members
If the name of the other model cannot be derived from the association name, you can use the `:class_name` option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is `Gadget`, you'd set things up this way:
```ruby
-class Parts < ActiveRecord::Base
+class Parts < ApplicationRecord
has_and_belongs_to_many :assemblies, class_name: "Gadget"
end
```
@@ -2130,7 +2130,7 @@ end
By convention, Rails assumes that the column in the join table used to hold the foreign key pointing to this 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:
```ruby
-class User < ActiveRecord::Base
+class User < ApplicationRecord
has_and_belongs_to_many :friends,
class_name: "User",
foreign_key: "this_user_id",
@@ -2151,7 +2151,7 @@ If you set the `:validate` option to `false`, then associated objects will not b
There may be times when you wish to customize the query used by `has_and_belongs_to_many`. Such customizations can be achieved via a scope block. For example:
```ruby
-class Parts < ActiveRecord::Base
+class Parts < ApplicationRecord
has_and_belongs_to_many :assemblies, -> { where active: true }
end
```
@@ -2174,7 +2174,7 @@ You can use any of the standard [querying methods](active_record_querying.html)
The `where` method lets you specify the conditions that the associated object must meet.
```ruby
-class Parts < ActiveRecord::Base
+class Parts < ApplicationRecord
has_and_belongs_to_many :assemblies,
-> { where "factory = 'Seattle'" }
end
@@ -2183,7 +2183,7 @@ end
You can also set conditions via a hash:
```ruby
-class Parts < ActiveRecord::Base
+class Parts < ApplicationRecord
has_and_belongs_to_many :assemblies,
-> { where factory: 'Seattle' }
end
@@ -2200,7 +2200,7 @@ The `extending` method specifies a named module to extend the association proxy.
The `group` method supplies an attribute name to group the result set by, using a `GROUP BY` clause in the finder SQL.
```ruby
-class Parts < ActiveRecord::Base
+class Parts < ApplicationRecord
has_and_belongs_to_many :assemblies, -> { group "factory" }
end
```
@@ -2214,7 +2214,7 @@ You can use the `includes` method to specify second-order associations that shou
The `limit` method lets you restrict the total number of objects that will be fetched through an association.
```ruby
-class Parts < ActiveRecord::Base
+class Parts < ApplicationRecord
has_and_belongs_to_many :assemblies,
-> { order("created_at DESC").limit(50) }
end
@@ -2229,7 +2229,7 @@ The `offset` method lets you specify the starting offset for fetching objects vi
The `order` method dictates the order in which associated objects will be received (in the syntax used by an SQL `ORDER BY` clause).
```ruby
-class Parts < ActiveRecord::Base
+class Parts < ApplicationRecord
has_and_belongs_to_many :assemblies,
-> { order "assembly_name ASC" }
end
@@ -2271,7 +2271,7 @@ Association callbacks are similar to normal callbacks, but they are triggered by
You define association callbacks by adding options to the association declaration. For example:
```ruby
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :orders, before_add: :check_credit_limit
def check_credit_limit(order)
@@ -2285,7 +2285,7 @@ Rails passes the object being added or removed to the callback.
You can stack callbacks on a single event by passing them as an array:
```ruby
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :orders,
before_add: [:check_credit_limit, :calculate_shipping_charges]
@@ -2306,7 +2306,7 @@ If a `before_add` callback throws an exception, the object does not get added to
You're not limited to the functionality that Rails automatically builds into association proxy objects. You can also extend these objects through anonymous modules, adding new finders, creators, or other methods. For example:
```ruby
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :orders do
def find_by_order_prefix(order_number)
find_by(region_id: order_number[0..2])
@@ -2324,11 +2324,11 @@ module FindRecentExtension
end
end
-class Customer < ActiveRecord::Base
+class Customer < ApplicationRecord
has_many :orders, -> { extending FindRecentExtension }
end
-class Supplier < ActiveRecord::Base
+class Supplier < ApplicationRecord
has_many :deliveries, -> { extending FindRecentExtension }
end
```
diff --git a/guides/source/autoloading_and_reloading_constants.md b/guides/source/autoloading_and_reloading_constants.md
index 5126d87bee..de0fa2fdc0 100644
--- a/guides/source/autoloading_and_reloading_constants.md
+++ b/guides/source/autoloading_and_reloading_constants.md
@@ -181,14 +181,14 @@ constant.
That is,
```ruby
-class Project < ActiveRecord::Base
+class Project < ApplicationRecord
end
```
performs a constant assignment equivalent to
```ruby
-Project = Class.new(ActiveRecord::Base)
+Project = Class.new(ApplicationRecord)
```
including setting the name of the class as a side-effect:
@@ -685,7 +685,7 @@ to trigger the heuristic is defined in the conflicting place.
### Automatic Modules
When a module acts as a namespace, Rails does not require the application to
-defines a file for it, a directory matching the namespace is enough.
+define a file for it, a directory matching the namespace is enough.
Suppose an application has a back office whose controllers are stored in
`app/controllers/admin`. If the `Admin` module is not yet loaded when
@@ -912,7 +912,7 @@ these classes:
```ruby
# app/models/polygon.rb
-class Polygon < ActiveRecord::Base
+class Polygon < ApplicationRecord
end
# app/models/triangle.rb
@@ -987,7 +987,7 @@ root class:
```ruby
# app/models/polygon.rb
-class Polygon < ActiveRecord::Base
+class Polygon < ApplicationRecord
end
require_dependency ‘square’
```
diff --git a/guides/source/caching_with_rails.md b/guides/source/caching_with_rails.md
index 9a56233e4a..3a1a1ccfe6 100644
--- a/guides/source/caching_with_rails.md
+++ b/guides/source/caching_with_rails.md
@@ -175,11 +175,11 @@ your app will serve stale data. To fix this, we tie the models together with
the `touch` method:
```ruby
-class Product < ActiveRecord::Base
+class Product < ApplicationRecord
has_many :games
end
-class Game < ActiveRecord::Base
+class Game < ApplicationRecord
belongs_to :product, touch: true
end
```
@@ -284,7 +284,7 @@ The most efficient way to implement low-level caching is using the `Rails.cache.
Consider the following example. An application has a `Product` model with an instance method that looks up the product’s price on a competing website. The data returned by this method would be perfect for low-level caching:
```ruby
-class Product < ActiveRecord::Base
+class Product < ApplicationRecord
def competing_price
Rails.cache.fetch("#{cache_key}/competing_price", expires_in: 12.hours) do
Competitor::API.find_price(id)
diff --git a/guides/source/configuring.md b/guides/source/configuring.md
index ee3f742367..5f4fd0f31b 100644
--- a/guides/source/configuring.md
+++ b/guides/source/configuring.md
@@ -35,7 +35,7 @@ In general, the work of configuring Rails means configuring the components of Ra
For example, the `config/application.rb` file includes this setting:
```ruby
-config.autoload_paths += %W(#{config.root}/extras)
+config.time_zone = 'Central Time (US & Canada)'
```
This is a setting for Rails itself. If you want to pass settings to individual Rails components, you can do so via the same `config` object in `config/application.rb`:
@@ -98,7 +98,7 @@ application. Accepts a valid week day symbol (e.g. `:monday`).
* `config.exceptions_app` sets the exceptions application invoked by the ShowException middleware when an exception happens. Defaults to `ActionDispatch::PublicExceptions.new(Rails.public_path)`.
-* `config.file_watcher` the class used to detect file updates in the filesystem when `config.reload_classes_only_on_change` is true. Must conform to `ActiveSupport::FileUpdateChecker` API.
+* `config.file_watcher` is the class used to detect file updates in the file system when `config.reload_classes_only_on_change` is true. Rails ships with `ActiveSupport::FileUpdateChecker`, the default, and `ActiveSupport::EventedFileUpdateChecker` (this one depends on the [listen](https://github.com/guard/listen) gem). Custom classes must conform to the `ActiveSupport::FileUpdateChecker` API.
* `config.filter_parameters` used for filtering out the parameters that
you don't want shown in the logs, such as passwords or credit card
@@ -199,7 +199,7 @@ The full set of methods that can be used in this block are as follows:
Every Rails application comes with a standard set of middleware which it uses in this order in the development environment:
* `ActionDispatch::SSL` forces every request to be under HTTPS protocol. Will be available if `config.force_ssl` is set to `true`. Options passed to this can be configured by using `config.ssl_options`.
-* `ActionDispatch::Static` is used to serve static assets. Disabled if `config.public_file_server.enabled` is `false`. Set `config.static_index` if you need to serve a static directory index file that is not named `index`. For example, to serve `main.html` instead of `index.html` for directory requests, set `config.static_index` to `"main"`.
+* `ActionDispatch::Static` is used to serve static assets. Disabled if `config.public_file_server.enabled` is `false`. Set `config.public_file_server.index_name` if you need to serve a static directory index file that is not named `index`. For example, to serve `main.html` instead of `index.html` for directory requests, set `config.public_file_server.index_name` to `"main"`.
* `Rack::Lock` wraps the app in mutex so it can only be called by a single thread at a time. Only enabled when `config.cache_classes` is `false`.
* `ActiveSupport::Cache::Strategy::LocalCache` serves as a basic memory backed cache. This cache is not thread safe and is intended only for serving as a temporary memory cache for a single thread.
* `Rack::Runtime` sets an `X-Runtime` header, containing the time (in seconds) taken to execute the request.
@@ -345,6 +345,8 @@ The schema dumper adds one additional configuration option:
* `config.action_controller.allow_forgery_protection` enables or disables CSRF protection. By default this is `false` in test mode and `true` in all other modes.
+* `config.action_controller.forgery_protection_origin_check` configures whether the HTTP `Origin` header should be checked against the site's origin as an additional CSRF defense.
+
* `config.action_controller.relative_url_root` can be used to tell Rails that you are [deploying to a subdirectory](configuring.html#deploy-to-a-subdirectory-relative-url-root). The default is `ENV['RAILS_RELATIVE_URL_ROOT']`.
* `config.action_controller.permit_all_parameters` sets all the parameters for mass assignment to be permitted by default. The default value is `false`.
@@ -459,6 +461,8 @@ encrypted cookies salt value. Defaults to `'signed encrypted cookie'`.
* `config.action_view.automatically_disable_submit_tag` determines whether
submit_tag should automatically disable on click, this defaults to true.
+* `config.action_view.debug_missing_translation` determins whether to wrap the missing translations key in a `<span>` tag or not. This defaults to true.
+
### Configuring Action Mailer
There are a number of settings available on `config.action_mailer`:
@@ -1043,9 +1047,9 @@ Below is a comprehensive list of all the initializers found in Rails in the orde
* `action_mailer.compile_config_methods` Initializes methods for the config settings specified so that they are quicker to access.
-* `set_load_path` This initializer runs before `bootstrap_hook`. Adds the `vendor`, `lib`, all directories of `app` and any paths specified by `config.load_paths` to `$LOAD_PATH`.
+* `set_load_path` This initializer runs before `bootstrap_hook`. Adds paths specified by `config.load_paths` and all autoload paths to `$LOAD_PATH`.
-* `set_autoload_paths` This initializer runs before `bootstrap_hook`. Adds all sub-directories of `app` and paths specified by `config.autoload_paths` to `ActiveSupport::Dependencies.autoload_paths`.
+* `set_autoload_paths` This initializer runs before `bootstrap_hook`. Adds all sub-directories of `app` and paths specified by `config.autoload_paths`, `config.eager_load_paths` and `config.autoload_once_paths` to `ActiveSupport::Dependencies.autoload_paths`.
* `add_routing_paths` Loads (by default) all `config/routes.rb` files (in the application and railties, including engines) and sets up the routes for the application.
diff --git a/guides/source/contributing_to_ruby_on_rails.md b/guides/source/contributing_to_ruby_on_rails.md
index 53c3cbf80b..ed88ecf6ac 100644
--- a/guides/source/contributing_to_ruby_on_rails.md
+++ b/guides/source/contributing_to_ruby_on_rails.md
@@ -16,7 +16,7 @@ After reading this guide, you will know:
Ruby on Rails is not "someone else's framework." Over the years, hundreds of people have contributed to Ruby on Rails ranging from a single character to massive architectural changes or significant documentation - all with the goal of making Ruby on Rails better for everyone. Even if you don't feel up to writing code or documentation yet, there are a variety of other ways that you can contribute, from reporting issues to testing patches.
As mentioned in [Rails
-README](https://github.com/rails/rails/blob/master/README.md), everyone interacting in Rails and its sub-projects' codebases, issue trackers, chat rooms, and mailing lists is expected to follow the Rails [code of conduct](https://github.com/rails/rails/blob/master/CODE_OF_CONDUCT.md).
+README](https://github.com/rails/rails/blob/master/README.md), everyone interacting in Rails and its sub-projects' codebases, issue trackers, chat rooms, and mailing lists is expected to follow the Rails [code of conduct](http://rubyonrails.org/conduct/).
--------------------------------------------------------------------------------
@@ -148,6 +148,42 @@ NOTE: To help our CI servers you should add [ci skip] to your documentation comm
WARNING: Docrails has a very strict policy: no code can be touched whatsoever, no matter how trivial or small the change. Only RDoc and guides can be edited via docrails. Also, CHANGELOGs should never be edited in docrails.
+Translating Rails Guides
+------------------------
+
+We are happy to have people volunteer to translate the Rails guides into their own language.
+If you want to translate the Rails guides in your own language, follows these steps:
+
+* Fork the project (rails/rails).
+* Add a source folder for your own language, for example: *guides/source/it-IT* for Italian.
+* Copy the contents of *guides/source* into your own language directory and translate them.
+* Do NOT translate the HTML files, as they are automatically generated.
+
+To generate the guides in HTML format cd into the *guides* direcotry then run (eg. for it-IT):
+
+```bash
+$ bundle install
+$ bundle exec rake guides:generate:html GUIDES_LANGUAGE=it-IT
+```
+
+This will generate the guides in an *output* directory.
+
+NOTE: The instructions are for Rails > 4. The Redcarpet Gem doesn't work with JRuby.
+
+Translation efforts we know about (various versions):
+
+* **Italian**: [https://github.com/rixlabs/docrails](https://github.com/rixlabs/docrails)
+* **Spanish**: [http://wiki.github.com/gramos/docrails](http://wiki.github.com/gramos/docrails)
+* **Polish**: [http://github.com/apohllo/docrails/tree/master](http://github.com/apohllo/docrails/tree/master)
+* **French** : [http://github.com/railsfrance/docrails](http://github.com/railsfrance/docrails)
+* **Czech** : [https://github.com/rubyonrails-cz/docrails/tree/czech](https://github.com/rubyonrails-cz/docrails/tree/czech)
+* **Turkish** : [https://github.com/ujk/docrails/tree/master](https://github.com/ujk/docrails/tree/master)
+* **Korean** : [https://github.com/rorlakr/rails-guides](https://github.com/rorlakr/rails-guides)
+* **Simplified Chinese** : [https://github.com/ruby-china/guides](https://github.com/ruby-china/guides)
+* **Traditional Chinese** : [https://github.com/docrails-tw/guides](https://github.com/docrails-tw/guides)
+* **Russian** : [https://github.com/morsbox/rusrails](https://github.com/morsbox/rusrails)
+* **Japanese** : [https://github.com/yasslab/railsguides.jp](https://github.com/yasslab/railsguides.jp)
+
Contributing to the Rails Code
------------------------------
diff --git a/guides/source/debugging_rails_applications.md b/guides/source/debugging_rails_applications.md
index a05abb61d6..0046ff7b4e 100644
--- a/guides/source/debugging_rails_applications.md
+++ b/guides/source/debugging_rails_applications.md
@@ -608,7 +608,7 @@ Started GET "/" for 127.0.0.1 at 2014-04-11 13:39:23 +0200
Processing by ArticlesController#index as HTML
[1, 8] in /home/davidr/Proyectos/test_app/app/models/article.rb
- 1: class Article < ActiveRecord::Base
+ 1: class Article < ApplicationRecord
2:
3: def self.find_recent(limit = 10)
4: byebug
@@ -862,8 +862,8 @@ such as Valgrind.
### Valgrind
-[Valgrind](http://valgrind.org/) is a Linux-only application for detecting
-C-based memory leaks and race conditions.
+[Valgrind](http://valgrind.org/) is an application for detecting C-based memory
+leaks and race conditions.
There are Valgrind tools that can automatically detect many memory management
and threading bugs, and profile your programs in detail. For example, if a C
diff --git a/guides/source/engines.md b/guides/source/engines.md
index 359796b1ff..8382bde4d3 100644
--- a/guides/source/engines.md
+++ b/guides/source/engines.md
@@ -508,7 +508,7 @@ Turning the model into this:
```ruby
module Blorgh
- class Article < ActiveRecord::Base
+ class Article < ApplicationRecord
has_many :comments
end
end
@@ -1033,9 +1033,9 @@ typical `GET` to a controller in a controller's functional test like this:
```ruby
module Blorgh
- class FooControllerTest < ActionController::TestCase
+ class FooControllerTest < ActionDispatch::IntegrationTest
def test_index
- get :index
+ get foos_url
...
end
end
@@ -1049,13 +1049,13 @@ in your setup code:
```ruby
module Blorgh
- class FooControllerTest < ActionController::TestCase
+ class FooControllerTest < ActionDispatch::IntegrationTest
setup do
@routes = Engine.routes
end
def test_index
- get :index
+ get foos_url
...
end
end
@@ -1129,7 +1129,7 @@ end
```ruby
# Blorgh/app/models/article.rb
-class Article < ActiveRecord::Base
+class Article < ApplicationRecord
has_many :comments
end
```
@@ -1150,7 +1150,7 @@ end
```ruby
# Blorgh/app/models/article.rb
-class Article < ActiveRecord::Base
+class Article < ApplicationRecord
has_many :comments
def summary
"#{title}"
@@ -1171,7 +1171,7 @@ classes at run time allowing you to significantly modularize your code.
```ruby
# MyApp/app/models/blorgh/article.rb
-class Blorgh::Article < ActiveRecord::Base
+class Blorgh::Article < ApplicationRecord
include Blorgh::Concerns::Models::Article
def time_since_created
@@ -1187,7 +1187,7 @@ end
```ruby
# Blorgh/app/models/article.rb
-class Article < ActiveRecord::Base
+class Article < ApplicationRecord
include Blorgh::Concerns::Models::Article
end
```
diff --git a/guides/source/form_helpers.md b/guides/source/form_helpers.md
index 93bb51557a..2a289dd33a 100644
--- a/guides/source/form_helpers.md
+++ b/guides/source/form_helpers.md
@@ -880,12 +880,12 @@ Many apps grow beyond simple forms editing a single object. For example, when cr
Active Record provides model level support via the `accepts_nested_attributes_for` method:
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
has_many :addresses
accepts_nested_attributes_for :addresses
end
-class Address < ActiveRecord::Base
+class Address < ApplicationRecord
belongs_to :person
end
```
@@ -973,7 +973,7 @@ private
You can allow users to delete associated objects by passing `allow_destroy: true` to `accepts_nested_attributes_for`
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
has_many :addresses
accepts_nested_attributes_for :addresses, allow_destroy: true
end
@@ -1014,7 +1014,7 @@ end
It is often useful to ignore sets of fields that the user has not filled in. You can control this by passing a `:reject_if` proc to `accepts_nested_attributes_for`. This proc will be called with each hash of attributes submitted by the form. If the proc returns `false` then Active Record will not build an associated object for that hash. The example below only tries to build an address if the `kind` attribute is set.
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
has_many :addresses
accepts_nested_attributes_for :addresses, reject_if: lambda {|attributes| attributes['kind'].blank?}
end
diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md
index 5700e71103..d8b590dba1 100644
--- a/guides/source/getting_started.md
+++ b/guides/source/getting_started.md
@@ -679,7 +679,7 @@ If you look in the `db/migrate/YYYYMMDDHHMMSS_create_articles.rb` file
(remember, yours will have a slightly different name), here's what you'll find:
```ruby
-class CreateArticles < ActiveRecord::Migration
+class CreateArticles < ActiveRecord::Migration[5.0]
def change
create_table :articles do |t|
t.string :title
@@ -990,21 +990,22 @@ and restart the web server when a change is made.
The model file, `app/models/article.rb` is about as simple as it can get:
```ruby
-class Article < ActiveRecord::Base
+class Article < ApplicationRecord
end
```
There isn't much to this file - but note that the `Article` class inherits from
-`ActiveRecord::Base`. Active Record supplies a great deal of functionality to
-your Rails models for free, including basic database CRUD (Create, Read, Update,
-Destroy) operations, data validation, as well as sophisticated search support
-and the ability to relate multiple models to one another.
+`ApplicationRecord`. `ApplicationRecord` inherits from `ActiveRecord::Base`
+which supplies a great deal of functionality to your Rails models for free,
+including basic database CRUD (Create, Read, Update, Destroy) operations, data
+validation, as well as sophisticated search support and the ability to relate
+multiple models to one another.
Rails includes methods to help you validate the data that you send to models.
Open the `app/models/article.rb` file and edit it:
```ruby
-class Article < ActiveRecord::Base
+class Article < ApplicationRecord
validates :title, presence: true,
length: { minimum: 5 }
end
@@ -1529,7 +1530,7 @@ This command will generate four files:
First, take a look at `app/models/comment.rb`:
```ruby
-class Comment < ActiveRecord::Base
+class Comment < ApplicationRecord
belongs_to :article
end
```
@@ -1542,7 +1543,7 @@ In addition to the model, Rails has also made a migration to create the
corresponding database table:
```ruby
-class CreateComments < ActiveRecord::Migration
+class CreateComments < ActiveRecord::Migration[5.0]
def change
create_table :comments do |t|
t.string :commenter
@@ -1587,7 +1588,7 @@ association. You've already seen the line of code inside the `Comment` model
(app/models/comment.rb) that makes each comment belong to an Article:
```ruby
-class Comment < ActiveRecord::Base
+class Comment < ApplicationRecord
belongs_to :article
end
```
@@ -1596,7 +1597,7 @@ You'll need to edit `app/models/article.rb` to add the other side of the
association:
```ruby
-class Article < ActiveRecord::Base
+class Article < ApplicationRecord
has_many :comments
validates :title, presence: true,
length: { minimum: 5 }
@@ -1962,7 +1963,7 @@ you to use the `dependent` option of an association to achieve this. Modify the
Article model, `app/models/article.rb`, as follows:
```ruby
-class Article < ActiveRecord::Base
+class Article < ApplicationRecord
has_many :comments, dependent: :destroy
validates :title, presence: true,
length: { minimum: 5 }
diff --git a/guides/source/i18n.md b/guides/source/i18n.md
index 8381636196..42589110b1 100644
--- a/guides/source/i18n.md
+++ b/guides/source/i18n.md
@@ -816,7 +816,7 @@ This gives you quite powerful means to flexibly adjust your messages to your app
Consider a User model with a validation for the name attribute like this:
```ruby
-class User < ActiveRecord::Base
+class User < ApplicationRecord
validates :name, presence: true
end
```
diff --git a/guides/source/initialization.md b/guides/source/initialization.md
index ebe1cb206a..7bf7eebb62 100644
--- a/guides/source/initialization.md
+++ b/guides/source/initialization.md
@@ -139,7 +139,8 @@ aliases = {
"c" => "console",
"s" => "server",
"db" => "dbconsole",
- "r" => "runner"
+ "r" => "runner",
+ "t" => "test"
}
command = ARGV.shift
@@ -158,19 +159,20 @@ defined here to find the matching command.
### `rails/commands/command_tasks.rb`
-When one types an incorrect rails command, the `run_command` is responsible for
-throwing an error message. If the command is valid, a method of the same name
-is called.
+When one types a valid Rails command, `run_command!` a method of the same name
+is called. If Rails doesn't recognize the command, it tries to run a Rake task
+of the same name.
```ruby
COMMAND_WHITELIST = %w(plugin generate destroy console server dbconsole application runner new version help)
def run_command!(command)
command = parse_command(command)
+
if COMMAND_WHITELIST.include?(command)
send(command)
else
- write_error_message(command)
+ run_rake_task(command)
end
end
```
diff --git a/guides/source/layouts_and_rendering.md b/guides/source/layouts_and_rendering.md
index 71cc030f6a..4bb364c0f8 100644
--- a/guides/source/layouts_and_rendering.md
+++ b/guides/source/layouts_and_rendering.md
@@ -622,10 +622,13 @@ Another way to handle returning responses to an HTTP request is with `redirect_t
redirect_to photos_url
```
-You can use `redirect_to` with any arguments that you could use with `link_to` or `url_for`. There's also a special redirect that sends the user back to the page they just came from:
+You can use `redirect_back` to return the user to the page they just came from.
+This location is pulled from the `HTTP_REFERER` header which is not guaranteed
+to be set by the browser, so you must provide the `fallback_location`
+to use in this case.
```ruby
-redirect_to :back
+redirect_back(fallback_location: root_path)
```
#### Getting a Different Redirect Status Code
diff --git a/guides/source/nested_model_forms.md b/guides/source/nested_model_forms.md
index 121cf2b185..71efa4b0d0 100644
--- a/guides/source/nested_model_forms.md
+++ b/guides/source/nested_model_forms.md
@@ -32,7 +32,7 @@ For an ActiveRecord::Base model and association this writer method is commonly d
#### has_one
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
has_one :address
accepts_nested_attributes_for :address
end
@@ -41,7 +41,7 @@ end
#### belongs_to
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
belongs_to :firm
accepts_nested_attributes_for :firm
end
@@ -50,7 +50,7 @@ end
#### has_many / has_and_belongs_to_many
```ruby
-class Person < ActiveRecord::Base
+class Person < ApplicationRecord
has_many :projects
accepts_nested_attributes_for :projects
end
diff --git a/guides/source/plugins.md b/guides/source/plugins.md
index b94c26a1ae..ae8c30515a 100644
--- a/guides/source/plugins.md
+++ b/guides/source/plugins.md
@@ -17,7 +17,7 @@ After reading this guide, you will know:
This guide describes how to build a test-driven plugin that will:
* Extend core Ruby classes like Hash and String.
-* Add methods to `ActiveRecord::Base` in the tradition of the `acts_as` plugins.
+* Add methods to `ApplicationRecord` in the tradition of the `acts_as` plugins.
* Give you information about where to put generators in your plugin.
For the purpose of this guide pretend for a moment that you are an avid bird watcher.
@@ -182,7 +182,6 @@ To start out, write a failing test that shows the behavior you'd like:
require 'test_helper'
class ActsAsYaffleTest < ActiveSupport::TestCase
-
def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
assert_equal "last_squawk", Hickwall.yaffle_text_field
end
@@ -190,7 +189,6 @@ class ActsAsYaffleTest < ActiveSupport::TestCase
def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
assert_equal "last_tweet", Wickwall.yaffle_text_field
end
-
end
```
@@ -234,22 +232,22 @@ like yaffles.
```ruby
# test/dummy/app/models/hickwall.rb
-class Hickwall < ActiveRecord::Base
+class Hickwall < ApplicationRecord
acts_as_yaffle
end
# test/dummy/app/models/wickwall.rb
-class Wickwall < ActiveRecord::Base
+class Wickwall < ApplicationRecord
acts_as_yaffle yaffle_text_field: :last_tweet
end
-
```
We will also add code to define the `acts_as_yaffle` method.
```ruby
# yaffle/lib/yaffle/acts_as_yaffle.rb
+
module Yaffle
module ActsAsYaffle
extend ActiveSupport::Concern
@@ -265,7 +263,13 @@ module Yaffle
end
end
-ActiveRecord::Base.include(Yaffle::ActsAsYaffle)
+# test/dummy/app/models/application_record.rb
+
+class ApplicationRecord < ActiveRecord::Base
+ include Yaffle::ActsAsYaffle
+
+ self.abstract_class = true
+end
```
You can then return to the root directory (`cd ../..`) of your plugin and rerun the tests using `rake`.
@@ -294,7 +298,7 @@ Getting closer... Now we will implement the code of the `acts_as_yaffle` method
module Yaffle
module ActsAsYaffle
- extend ActiveSupport::Concern
+ extend ActiveSupport::Concern
included do
end
@@ -308,7 +312,13 @@ module Yaffle
end
end
-ActiveRecord::Base.include(Yaffle::ActsAsYaffle)
+# test/dummy/app/models/application_record.rb
+
+class ApplicationRecord < ActiveRecord::Base
+ include Yaffle::ActsAsYaffle
+
+ self.abstract_class = true
+end
```
When you run `rake`, you should see the tests all pass:
@@ -329,7 +339,6 @@ To start out, write a failing test that shows the behavior you'd like:
require 'test_helper'
class ActsAsYaffleTest < ActiveSupport::TestCase
-
def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
assert_equal "last_squawk", Hickwall.yaffle_text_field
end
@@ -382,7 +391,13 @@ module Yaffle
end
end
-ActiveRecord::Base.include(Yaffle::ActsAsYaffle)
+# test/dummy/app/models/application_record.rb
+
+class ApplicationRecord < ActiveRecord::Base
+ include Yaffle::ActsAsYaffle
+
+ self.abstract_class = true
+end
```
Run `rake` one final time and you should see:
diff --git a/guides/source/routing.md b/guides/source/routing.md
index 245689932b..2b1254f7a0 100644
--- a/guides/source/routing.md
+++ b/guides/source/routing.md
@@ -142,10 +142,10 @@ Sometimes, you have a resource that clients always look up without referencing a
get 'profile', to: 'users#show'
```
-Passing a `String` to `get` will expect a `controller#action` format, while passing a `Symbol` will map directly to an action:
+Passing a `String` to `get` will expect a `controller#action` format, while passing a `Symbol` will map directly to an action but you must also specify the `controller:` to use:
```ruby
-get 'profile', to: :show
+get 'profile', to: :show, controller: 'users'
```
This resourceful route:
@@ -252,11 +252,11 @@ TIP: _If you need to use a different controller namespace inside a `namespace` b
It's common to have resources that are logically children of other resources. For example, suppose your application includes these models:
```ruby
-class Magazine < ActiveRecord::Base
+class Magazine < ApplicationRecord
has_many :ads
end
-class Ad < ActiveRecord::Base
+class Ad < ApplicationRecord
belongs_to :magazine
end
```
@@ -1099,7 +1099,7 @@ You can override `ActiveRecord::Base#to_param` of a related model to construct
a URL:
```ruby
-class Video < ActiveRecord::Base
+class Video < ApplicationRecord
def to_param
identifier
end
diff --git a/guides/source/security.md b/guides/source/security.md
index df8c24864e..1d0e87d831 100644
--- a/guides/source/security.md
+++ b/guides/source/security.md
@@ -171,7 +171,7 @@ NOTE: _Sessions that never expire extend the time-frame for attacks such as cros
One possibility is to set the expiry time-stamp of the cookie with the session id. However the client can edit cookies that are stored in the web browser so expiring sessions on the server is safer. Here is an example of how to _expire sessions in a database table_. Call `Session.sweep("20 minutes")` to expire sessions that were used longer than 20 minutes ago.
```ruby
-class Session < ActiveRecord::Base
+class Session < ApplicationRecord
def self.sweep(time = 1.hour)
if time.is_a?(String)
time = time.split.inject { |count, unit| count.to_i.send(unit) }
@@ -381,9 +381,9 @@ 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/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.
+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 the user, 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.

+Another example changed Google Adsense's e-mail address and password. If the victim was logged into Google Adsense, the administration interface for Google advertisement campaigns, an attacker could change the credentials of the victim.

Another popular attack is to spam your web application, your blog or forum to propagate malicious XSS. Of course, the attacker has to know the URL structure, but most Rails URLs are quite straightforward or they will be easy to find out, if it is an open-source application's admin interface. The attacker may even do 1,000 lucky guesses by just including malicious IMG-tags which try every possible combination.
diff --git a/guides/source/testing.md b/guides/source/testing.md
index f63ea49955..a4b62955c5 100644
--- a/guides/source/testing.md
+++ b/guides/source/testing.md
@@ -54,10 +54,12 @@ NOTE: Your tests are run under `RAILS_ENV=test`.
### Rails meets Minitest
-If you remember when you used the `rails generate scaffold` command from the [Getting Started with Rails](getting_started.html) guide. We created our first resource among other things it created test stubs in the `test` directory:
+If you remember when you used the `rails generate model` command from the
+[Getting Started with Rails](getting_started.html) guide. We created our first
+model among other things it created test stubs in the `test` directory:
```bash
-$ bin/rails generate scaffold article title:string body:text
+$ bin/rails generate model article title:string body:text
...
create app/models/article.rb
create test/models/article_test.rb
@@ -175,7 +177,7 @@ Saved the article without a title
Now to get this test to pass we can add a model level validation for the _title_ field.
```ruby
-class Article < ActiveRecord::Base
+class Article < ApplicationRecord
validates :title, presence: true
end
```
@@ -328,7 +330,6 @@ You'll see the usage of some of these assertions in the next chapter.
All the basic assertions such as `assert_equal` defined in `Minitest::Assertions` are also available in the classes we use in our own test cases. In fact, Rails provides the following classes for you to inherit from:
* `ActiveSupport::TestCase`
-* `ActionController::TestCase`
* `ActionMailer::TestCase`
* `ActionView::TestCase`
* `ActionDispatch::IntegrationTest`
@@ -649,23 +650,40 @@ You should test for things such as:
* was the correct object stored in the response template?
* was the appropriate message displayed to the user in the view?
-Now that we have used Rails scaffold generator for our `Article` resource, it has already created the controller code and tests. You can take look at the file `articles_controller_test.rb` in the `test/controllers` directory.
+The easiest way to see functional tests in action is to generate a controller
+scaffold:
-The following command will generate a controller test case with a filled up
-test for each of the seven default actions.
+```bash
+$ bin/rails generate scaffold_controller article title:string body:test
+...
+create app/controllers/articles_controller.rb
+...
+invoke test_unit
+create test/controllers/articles_controller_test.rb
+...
+```
+
+This will generate the controller code and tests for an `Article` resource.
+You can take look at the file `articles_controller_test.rb` in the `test/controllers` directory.
+
+If you already have a controller and just want to generate the test scaffold code for
+each of the seven default actions, you can use the following command:
```bash
$ bin/rails generate test_unit:scaffold article
+...
+invoke test_unit
create test/controllers/articles_controller_test.rb
+...
```
Let me take you through one such test, `test_should_get_index` from the file `articles_controller_test.rb`.
```ruby
# articles_controller_test.rb
-class ArticlesControllerTest < ActionController::TestCase
+class ArticlesControllerTest < ActionDispatch::IntegrationTest
test "should get index" do
- get :index
+ get '/articles'
assert_response :success
assert_includes @response.body, 'Articles'
end
@@ -678,7 +696,7 @@ and also ensuring that the right response body has been generated.
The `get` method kicks off the web request and populates the results into the response. It accepts 4 arguments:
* The action of the controller you are requesting.
- This can be in the form of a string or a symbol.
+ This can be in the form of a string or a route (i.e. `articles_url`).
* `params`: option with a hash of request parameters to pass into the action
(e.g. query string parameters or article variables).
@@ -698,7 +716,7 @@ get(:show, params: { id: 12 }, session: { user_id: 5 })
Another example: Calling the `:view` action, passing an `id` of 12 as the `params`, this time with no session, but with a flash message.
```ruby
-get(:view, params: { id: 12 }, flash: { message: 'booya!' })
+get(view_url, params: { id: 12 }, flash: { message: 'booya!' })
```
NOTE: If you try running `test_should_create_article` test from `articles_controller_test.rb` it will fail on account of the newly added model level validation and rightly so.
@@ -708,7 +726,7 @@ Let us modify `test_should_create_article` test in `articles_controller_test.rb`
```ruby
test "should create article" do
assert_difference('Article.count') do
- post :create, params: { article: { title: 'Some title' } }
+ post '/article', params: { article: { title: 'Some title' } }
end
assert_redirected_to article_path(Article.last)
@@ -739,7 +757,8 @@ To test AJAX requests, you can specify the `xhr: true` option to `get`, `post`,
```ruby
test "ajax request" do
- get :show, params: { id: articles(:first).id }, xhr: true
+ article = articles(:first)
+ get article_url(article), xhr: true
assert_equal 'hello world', @response.body
assert_equal "text/javascript", @response.content_type
@@ -780,11 +799,11 @@ can be set directly on the `@request` instance variable:
```ruby
# setting a HTTP Header
@request.headers["Accept"] = "text/plain, text/html"
-get :index # simulate the request with custom header
+get articles_url # simulate the request with custom header
# setting a CGI variable
@request.headers["HTTP_REFERER"] = "http://example.com/home"
-post :create # simulate the request with custom env variable
+post article_url # simulate the request with custom env variable
```
### Testing `flash` notices
@@ -799,7 +818,7 @@ Let's start by adding this assertion to our `test_should_create_article` test:
```ruby
test "should create article" do
assert_difference('Article.count') do
- post :create, params: { article: { title: 'Some title' } }
+ post article_url, params: { article: { title: 'Some title' } }
end
assert_redirected_to article_path(Article.last)
@@ -869,7 +888,7 @@ Let's write a test for the `:show` action:
```ruby
test "should show article" do
article = articles(:one)
- get :show, params: { id: article.id }
+ get '/article', params: { id: article.id }
assert_response :success
end
```
@@ -882,7 +901,7 @@ How about deleting an existing Article?
test "should destroy article" do
article = articles(:one)
assert_difference('Article.count', -1) do
- delete :destroy, params: { id: article.id }
+ delete article_url(article)
end
assert_redirected_to articles_path
@@ -894,7 +913,7 @@ We can also add a test for updating an existing Article.
```ruby
test "should update article" do
article = articles(:one)
- patch :update, params: { id: article.id, article: { title: "updated" } }
+ patch '/article', params: { id: article.id, article: { title: "updated" } }
assert_redirected_to article_path(article)
end
```
@@ -906,7 +925,7 @@ Our test should now look something like this, disregard the other tests we're le
```ruby
require 'test_helper'
-class ArticlesControllerTest < ActionController::TestCase
+class ArticlesControllerTest < ActionDispatch::IntegrationTest
# called before every single test
setup do
@article = articles(:one)
@@ -920,20 +939,20 @@ class ArticlesControllerTest < ActionController::TestCase
test "should show article" do
# Reuse the @article instance variable from setup
- get :show, params: { id: @article.id }
+ get article_url(@article)
assert_response :success
end
test "should destroy article" do
assert_difference('Article.count', -1) do
- delete :destroy, params: { id: @article.id }
+ delete article_url(@article)
end
assert_redirected_to articles_path
end
test "should update article" do
- patch :update, params: { id: @article.id, article: { title: "updated" } }
+ patch article_url(@article), params: { article: { title: "updated" } }
assert_redirected_to article_path(@article)
end
end
@@ -955,7 +974,7 @@ module SignInHelper
end
end
-class ActionController::TestCase
+class ActionDispatch::IntegrationTest
include SignInHelper
end
```
@@ -963,13 +982,13 @@ end
```ruby
require 'test_helper'
-class ProfileControllerTest < ActionController::TestCase
+class ProfileControllerTest < ActionDispatch::IntegrationTest
test "should show profile" do
# helper is now reusable from any controller test case
sign_in users(:david)
- get :show
+ get profile_url
assert_response :success
end
end
@@ -1167,10 +1186,10 @@ Functional testing for mailers involves more than just checking that the email b
```ruby
require 'test_helper'
-class UserControllerTest < ActionController::TestCase
+class UserControllerTest < ActionDispatch::IntegrationTest
test "invite friend" do
assert_difference 'ActionMailer::Base.deliveries.size', +1 do
- post :invite_friend, params: { email: 'friend@example.com' }
+ post invite_friend_url, params: { email: 'friend@example.com' }
end
invite_email = ActionMailer::Base.deliveries.last
@@ -1253,4 +1272,3 @@ assert_equal Date.new(2004, 10, 24), user.activation_date # The change was visib
Please see [`ActiveSupport::TimeHelpers` API Documentation](http://api.rubyonrails.org/classes/ActiveSupport/Testing/TimeHelpers.html)
for in-depth information about the available time helpers.
-
diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md
index fa6a01671b..148890bf77 100644
--- a/guides/source/upgrading_ruby_on_rails.md
+++ b/guides/source/upgrading_ruby_on_rails.md
@@ -53,7 +53,26 @@ Don't forget to review the difference, to see if there were any unexpected chang
Upgrading from Rails 4.2 to Rails 5.0
-------------------------------------
-### Halting callback chains by returning `false`
+### Active Record models now inherit from ApplicationRecord by default
+
+In Rails 4.2 an Active Record model inherits from `ActiveRecord::Base`. In Rails 5.0,
+all models inherit from `ApplicationRecord`.
+
+`ApplicationRecord` is a new superclass for all app models, analogous to app
+controllers subclassing `ApplicationController` instead of
+`ActionController::Base`. This gives apps a single spot to configure app-wide
+model behavior
+
+When upgrading from Rails 4.2 to Rails 5.0 you need to create an
+`application_record.rb` file in `app/models/` and add the following content:
+
+```
+class ApplicationRecord < ActiveRecord::Base
+ self.abstract_class = true
+end
+```
+
+### Halting callback chains via `throw(:abort)`
In Rails 4.2, when a 'before' callback returns `false` in Active Record
and Active Model, then the entire callback chain is halted. In other words,
diff --git a/guides/source/working_with_javascript_in_rails.md b/guides/source/working_with_javascript_in_rails.md
index 1c42ff2914..48fc6bc9c0 100644
--- a/guides/source/working_with_javascript_in_rails.md
+++ b/guides/source/working_with_javascript_in_rails.md
@@ -81,7 +81,7 @@ Awkward, right? We could pull the function definition out of the click handler,
and turn it into CoffeeScript:
```coffeescript
-paintIt = (element, backgroundColor, textColor) ->
+@paintIt = (element, backgroundColor, textColor) ->
element.style.backgroundColor = backgroundColor
if textColor?
element.style.color = textColor
@@ -107,7 +107,7 @@ attribute to our link, and then bind a handler to the click event of every link
that has that attribute:
```coffeescript
-paintIt = (element, backgroundColor, textColor) ->
+@paintIt = (element, backgroundColor, textColor) ->
element.style.backgroundColor = backgroundColor
if textColor?
element.style.color = textColor
diff --git a/rails.gemspec b/rails.gemspec
index 0286af0a57..d4e78b6aa1 100644
--- a/rails.gemspec
+++ b/rails.gemspec
@@ -25,6 +25,7 @@ Gem::Specification.new do |s|
s.add_dependency 'activerecord', version
s.add_dependency 'actionmailer', version
s.add_dependency 'activejob', version
+ s.add_dependency 'actioncable', version
s.add_dependency 'railties', version
s.add_dependency 'bundler', '>= 1.3.0', '< 2.0'
diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md
index 2fedeac292..d9d0136ad8 100644
--- a/railties/CHANGELOG.md
+++ b/railties/CHANGELOG.md
@@ -1,7 +1,56 @@
-* Generated `Gemfile`s for new applications include a new dependency on
- [listen](https://github.com/guard/listen) commented out.
+## Rails 5.0.0.beta1 (December 18, 2015) ##
- *Puneet Agarwal* and *Xavier Noria*
+* No changes.
+
+
+* Newly generated plugins get a `README.md` in Markdown.
+
+ *Yuji Yaginuma*
+
+* The generated config file for the development environment includes a new
+ config line, commented out, showing how to enable the evented file watcher.
+
+ *Xavier Noria*
+
+* `config.debug_exception_response_format` configures the format used
+ in responses when errors occur in development mode.
+
+ Set `config.debug_exception_response_format` to render an HTML page with
+ debug info (using the value `:default`) or render debug info preserving
+ the response format (using the value `:api`).
+
+ *Jorge Bejar*
+
+* Fix setting exit status code for rake test tasks. The exit status code
+ was not set when tests were fired with `rake`. Now, it is being set and it matches
+ behavior of running tests via `rails` command (`rails test`), so no matter if
+ `rake test` or `rails test` command is used the exit code will be set.
+
+ *Arkadiusz Fal*
+
+* Add Command infrastructure to replace rake.
+
+ Also move `rake dev:cache` to new infrastructure. You'll need to use
+ `rails dev:cache` to toggle development caching from now on.
+
+ *Chuck Callebs*
+
+* Allow use of minitest-rails gem with Rails test runner.
+
+ Fixes #22455.
+
+ *Chris Kottom*
+
+* Add `bin/test` script to rails plugin.
+
+ `bin/test` can use the same API as `bin/rails test`.
+
+ *Yuji Yaginuma*
+
+* Make `static_index` part of the `config.public_file_server` config and
+ call it `public_file_server.index_name`.
+
+ *Yuki Nishijima*
* Deprecate `serve_static_files` in favor of `public_file_server.enabled`.
diff --git a/railties/Rakefile b/railties/Rakefile
index 73d881b318..cf130a5f14 100644
--- a/railties/Rakefile
+++ b/railties/Rakefile
@@ -5,33 +5,20 @@ task :default => :test
desc "Run all unit tests"
task :test => 'test:isolated'
-dash_i = [
- 'test',
- 'lib',
- "#{File.dirname(__FILE__)}/../activesupport/lib",
- "#{File.dirname(__FILE__)}/../actionpack/lib",
- "#{File.dirname(__FILE__)}/../activemodel/lib"
-]
-
-dash_i.reverse_each do |x|
- $:.unshift x unless $:.include? x
-end
-$-w = true
-
-require 'bundler/setup' unless defined?(Bundler)
-require 'active_support'
-
namespace :test do
task :isolated do
dirs = (ENV["TEST_DIR"] || ENV["TEST_DIRS"] || "**").split(",")
test_files = dirs.map { |dir| "test/#{dir}/*_test.rb" }
Dir[*test_files].each do |file|
next true if file.include?("fixtures")
- puts "#{FileUtils::RUBY} -w -I#{dash_i.join ':'} #{file}"
-
- # We could run these in parallel, but pretty much all of the
- # railties tests already run in parallel, so ¯\_(⊙︿⊙)_/¯
- Process.waitpid fork { ARGV.clear; load file }
+ dash_i = [
+ 'test',
+ 'lib',
+ "#{File.dirname(__FILE__)}/../activesupport/lib",
+ "#{File.dirname(__FILE__)}/../actionpack/lib",
+ "#{File.dirname(__FILE__)}/../activemodel/lib"
+ ]
+ ruby "-w", "-I#{dash_i.join ':'}", file
end
end
end
diff --git a/railties/lib/rails/all.rb b/railties/lib/rails/all.rb
index 45361fca83..11f4d5c4bc 100644
--- a/railties/lib/rails/all.rb
+++ b/railties/lib/rails/all.rb
@@ -1,16 +1,17 @@
require "rails"
%w(
- active_record
- action_controller
- action_view
- action_mailer
- active_job
- rails/test_unit
- sprockets
-).each do |framework|
+ active_record/railtie
+ action_controller/railtie
+ action_view/railtie
+ action_mailer/railtie
+ active_job/railtie
+ action_cable/engine
+ rails/test_unit/railtie
+ sprockets/railtie
+).each do |railtie|
begin
- require "#{framework}/railtie"
+ require "#{railtie}"
rescue LoadError
end
end
diff --git a/railties/lib/rails/api/task.rb b/railties/lib/rails/api/task.rb
index a082932632..d478bbf9e8 100644
--- a/railties/lib/rails/api/task.rb
+++ b/railties/lib/rails/api/task.rb
@@ -57,6 +57,13 @@ module Rails
)
},
+ 'actioncable' => {
+ :include => %w(
+ README.md
+ lib/action_cable/**/*.rb
+ )
+ },
+
'railties' => {
:include => %w(
README.rdoc
diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb
index 77efe3248d..cac31e1eed 100644
--- a/railties/lib/rails/application.rb
+++ b/railties/lib/rails/application.rb
@@ -219,7 +219,11 @@ module Rails
# config.middleware.use ExceptionNotifier, config_for(:exception_notification)
# end
def config_for(name, env: Rails.env)
- yaml = Pathname.new("#{paths["config"].existent.first}/#{name}.yml")
+ if name.is_a?(Pathname)
+ yaml = name
+ else
+ yaml = Pathname.new("#{paths["config"].existent.first}/#{name}.yml")
+ end
if yaml.exist?
require "erb"
diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb
index 6d89caf514..65cff1561a 100644
--- a/railties/lib/rails/application/configuration.rb
+++ b/railties/lib/rails/application/configuration.rb
@@ -14,7 +14,7 @@ module Rails
:eager_load, :exceptions_app, :file_watcher, :filter_parameters,
:force_ssl, :helpers_paths, :logger, :log_formatter, :log_tags,
:railties_order, :relative_url_root, :secret_key_base, :secret_token,
- :ssl_options, :static_index, :public_file_server,
+ :ssl_options, :public_file_server,
:session_options, :time_zone, :reload_classes_only_on_change,
:beginning_of_week, :filter_redirect, :x
@@ -24,35 +24,36 @@ module Rails
def initialize(*)
super
self.encoding = "utf-8"
- @allow_concurrency = nil
- @consider_all_requests_local = false
- @filter_parameters = []
- @filter_redirect = []
- @helpers_paths = []
- @static_index = "index"
- @public_file_server = ActiveSupport::OrderedOptions.new
- @public_file_server.enabled = true
- @force_ssl = false
- @ssl_options = {}
- @session_store = :cookie_store
- @session_options = {}
- @time_zone = "UTC"
- @beginning_of_week = :monday
- @log_level = nil
- @generators = app_generators
- @cache_store = [ :file_store, "#{root}/tmp/cache/" ]
- @railties_order = [:all]
- @relative_url_root = ENV["RAILS_RELATIVE_URL_ROOT"]
- @reload_classes_only_on_change = true
- @file_watcher = file_update_checker
- @exceptions_app = nil
- @autoflush_log = true
- @log_formatter = ActiveSupport::Logger::SimpleFormatter.new
- @eager_load = nil
- @secret_token = nil
- @secret_key_base = nil
- @api_only = false
- @x = Custom.new
+ @allow_concurrency = nil
+ @consider_all_requests_local = false
+ @filter_parameters = []
+ @filter_redirect = []
+ @helpers_paths = []
+ @public_file_server = ActiveSupport::OrderedOptions.new
+ @public_file_server.enabled = true
+ @public_file_server.index_name = "index"
+ @force_ssl = false
+ @ssl_options = {}
+ @session_store = :cookie_store
+ @session_options = {}
+ @time_zone = "UTC"
+ @beginning_of_week = :monday
+ @log_level = nil
+ @generators = app_generators
+ @cache_store = [ :file_store, "#{root}/tmp/cache/" ]
+ @railties_order = [:all]
+ @relative_url_root = ENV["RAILS_RELATIVE_URL_ROOT"]
+ @reload_classes_only_on_change = true
+ @file_watcher = ActiveSupport::FileUpdateChecker
+ @exceptions_app = nil
+ @autoflush_log = true
+ @log_formatter = ActiveSupport::Logger::SimpleFormatter.new
+ @eager_load = nil
+ @secret_token = nil
+ @secret_key_base = nil
+ @api_only = false
+ @debug_exception_response_format = nil
+ @x = Custom.new
end
def static_cache_control=(value)
@@ -95,6 +96,16 @@ module Rails
def api_only=(value)
@api_only = value
generators.api_only = value
+
+ @debug_exception_response_format ||= :api
+ end
+
+ def debug_exception_response_format
+ @debug_exception_response_format || :default
+ end
+
+ def debug_exception_response_format=(value)
+ @debug_exception_response_format = value
end
def paths
@@ -180,30 +191,21 @@ module Rails
SourceAnnotationExtractor::Annotation
end
- private
- def file_update_checker
- if defined?(Listen) && Listen::Adapter.select() != Listen::Adapter::Polling
- ActiveSupport::FileEventedUpdateChecker
- else
- ActiveSupport::FileUpdateChecker
- end
+ class Custom #:nodoc:
+ def initialize
+ @configurations = Hash.new
end
- class Custom #:nodoc:
- def initialize
- @configurations = Hash.new
- end
-
- def method_missing(method, *args)
- if method =~ /=$/
- @configurations[$`.to_sym] = args.first
- else
- @configurations.fetch(method) {
- @configurations[method] = ActiveSupport::OrderedOptions.new
- }
- end
+ def method_missing(method, *args)
+ if method =~ /=$/
+ @configurations[$`.to_sym] = args.first
+ else
+ @configurations.fetch(method) {
+ @configurations[method] = ActiveSupport::OrderedOptions.new
+ }
end
end
+ end
end
end
end
diff --git a/railties/lib/rails/application/default_middleware_stack.rb b/railties/lib/rails/application/default_middleware_stack.rb
index b0d481c21a..ed6a1f82d3 100644
--- a/railties/lib/rails/application/default_middleware_stack.rb
+++ b/railties/lib/rails/application/default_middleware_stack.rb
@@ -21,7 +21,7 @@ module Rails
headers = config.public_file_server.headers || {}
headers['Cache-Control'.freeze] = config.static_cache_control if config.static_cache_control
- middleware.use ::ActionDispatch::Static, paths["public"].first, index: config.static_index, headers: headers
+ middleware.use ::ActionDispatch::Static, paths["public"].first, index: config.public_file_server.index_name, headers: headers
end
if rack_cache = load_rack_cache
@@ -57,7 +57,7 @@ module Rails
# Must come after Rack::MethodOverride to properly log overridden methods
middleware.use ::Rails::Rack::Logger, config.log_tags
middleware.use ::ActionDispatch::ShowExceptions, show_exceptions_app
- middleware.use ::ActionDispatch::DebugExceptions, app
+ middleware.use ::ActionDispatch::DebugExceptions, app, config.debug_exception_response_format
middleware.use ::ActionDispatch::RemoteIp, config.action_dispatch.ip_spoofing_check, config.action_dispatch.trusted_proxies
unless config.cache_classes
diff --git a/railties/lib/rails/command.rb b/railties/lib/rails/command.rb
new file mode 100644
index 0000000000..f7753cbb83
--- /dev/null
+++ b/railties/lib/rails/command.rb
@@ -0,0 +1,70 @@
+require 'rails/commands/commands_tasks'
+
+module Rails
+ class Command #:nodoc:
+ attr_reader :argv
+
+ def initialize(argv = [])
+ @argv = argv
+
+ @option_parser = build_option_parser
+ @options = {}
+ end
+
+ def self.run(task_name, argv)
+ command_name = command_name_for(task_name)
+
+ if command = command_for(command_name)
+ command.new(argv).run(command_name)
+ else
+ Rails::CommandsTasks.new(argv).run_command!(task_name)
+ end
+ end
+
+ def run(command_name)
+ parse_options_for(command_name)
+ @option_parser.parse! @argv
+
+ public_send(command_name)
+ end
+
+ def self.options_for(command_name, &options_to_parse)
+ @@command_options[command_name] = options_to_parse
+ end
+
+ def self.set_banner(command_name, banner)
+ options_for(command_name) { |opts, _| opts.banner = banner }
+ end
+
+ private
+ @@commands = []
+ @@command_options = {}
+
+ def parse_options_for(command_name)
+ @@command_options.fetch(command_name, proc {}).call(@option_parser, @options)
+ end
+
+ def build_option_parser
+ OptionParser.new do |opts|
+ opts.on('-h', '--help', 'Show this help.') do
+ puts opts
+ exit
+ end
+ end
+ end
+
+ def self.inherited(command)
+ @@commands << command
+ end
+
+ def self.command_name_for(task_name)
+ task_name.gsub(':', '_').to_sym
+ end
+
+ def self.command_for(command_name)
+ @@commands.find do |command|
+ command.public_instance_methods.include?(command_name)
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/commands.rb b/railties/lib/rails/commands.rb
index 12bd73db24..7627fcf5a0 100644
--- a/railties/lib/rails/commands.rb
+++ b/railties/lib/rails/commands.rb
@@ -7,12 +7,13 @@ aliases = {
"s" => "server",
"db" => "dbconsole",
"r" => "runner",
- "t" => "test",
+ "t" => "test"
}
command = ARGV.shift
command = aliases[command] || command
-require 'rails/commands/commands_tasks'
+require 'rails/command'
+require 'rails/commands/dev_cache'
-Rails::CommandsTasks.new(ARGV).run_command!(command)
+Rails::Command.run(command, ARGV)
diff --git a/railties/lib/rails/commands/commands_tasks.rb b/railties/lib/rails/commands/commands_tasks.rb
index 685d55eea8..da3b9452d5 100644
--- a/railties/lib/rails/commands/commands_tasks.rb
+++ b/railties/lib/rails/commands/commands_tasks.rb
@@ -1,3 +1,5 @@
+require 'rails/commands/rake_proxy'
+
module Rails
# This is a class which takes in a rails command and initiates the appropriate
# initiation sequence.
@@ -5,6 +7,8 @@ module Rails
# Warning: This class mutates ARGV because some commands require manipulating
# it before they are run.
class CommandsTasks # :nodoc:
+ include Rails::RakeProxy
+
attr_reader :argv
HELP_MESSAGE = <<-EOT
@@ -20,14 +24,18 @@ The most common rails commands are:
new Create a new Rails application. "rails new my_app" creates a
new application called MyApp in "./my_app"
-In addition to those, there are:
- destroy Undo code generated with "generate" (short-cut alias: "d")
- plugin new Generates skeleton for developing a Rails plugin
- runner Run a piece of code in the application environment (short-cut alias: "r")
-
All commands can be run with -h (or --help) for more information.
+
+In addition to those commands, there are:
EOT
+ ADDITIONAL_COMMANDS = [
+ [ 'destroy', 'Undo code generated with "generate" (short-cut alias: "d")' ],
+ [ 'plugin new', 'Generates skeleton for developing a Rails plugin' ],
+ [ 'runner',
+ 'Run a piece of code in the application environment (short-cut alias: "r")' ]
+ ]
+
COMMAND_WHITELIST = %w(plugin generate destroy console server dbconsole runner new version help test)
def initialize(argv)
@@ -36,10 +44,11 @@ EOT
def run_command!(command)
command = parse_command(command)
+
if COMMAND_WHITELIST.include?(command)
send(command)
else
- write_error_message(command)
+ run_rake_task(command)
end
end
@@ -110,6 +119,7 @@ EOT
def help
write_help_message
+ write_commands ADDITIONAL_COMMANDS + formatted_rake_tasks
end
private
@@ -151,24 +161,9 @@ EOT
puts HELP_MESSAGE
end
- # Output an error message stating that the attempted command is not a valid rails command.
- # Run the attempted command as a rake command with the --dry-run flag. If successful, suggest
- # to the user that they possibly meant to run the given rails command as a rake command.
- # Append the help message.
- #
- # Example:
- # $ rails db:migrate
- # Error: Command 'db:migrate' not recognized
- # Did you mean: `$ rake db:migrate` ?
- # (Help message output)
- #
- def write_error_message(command)
- puts "Error: Command '#{command}' not recognized"
- if %x{rake #{command} --dry-run 2>&1 } && $?.success?
- puts "Did you mean: `$ rake #{command}` ?\n\n"
- end
- write_help_message
- exit(1)
+ def write_commands(commands)
+ width = commands.map { |name, _| name.size }.max || 10
+ commands.each { |command| printf(" %-#{width}s %s\n", *command) }
end
def parse_command(command)
diff --git a/railties/lib/rails/commands/dbconsole.rb b/railties/lib/rails/commands/dbconsole.rb
index dca60f948f..2c36edfa3f 100644
--- a/railties/lib/rails/commands/dbconsole.rb
+++ b/railties/lib/rails/commands/dbconsole.rb
@@ -65,7 +65,7 @@ module Rails
'sslca' => '--ssl-ca',
'sslcert' => '--ssl-cert',
'sslcapath' => '--ssl-capath',
- 'sslcipher' => '--ssh-cipher',
+ 'sslcipher' => '--ssl-cipher',
'sslkey' => '--ssl-key'
}.map { |opt, arg| "#{arg}=#{config[opt]}" if config[opt] }.compact
diff --git a/railties/lib/rails/commands/dev_cache.rb b/railties/lib/rails/commands/dev_cache.rb
new file mode 100644
index 0000000000..ec96e8f630
--- /dev/null
+++ b/railties/lib/rails/commands/dev_cache.rb
@@ -0,0 +1,21 @@
+require 'rails/command'
+
+module Rails
+ module Commands
+ # This is a wrapper around the Rails dev:cache command
+ class DevCache < Command
+ set_banner :dev_cache, 'Toggle development mode caching on/off'
+ def dev_cache
+ if File.exist? 'tmp/caching-dev.txt'
+ File.delete 'tmp/caching-dev.txt'
+ puts 'Development mode is no longer being cached.'
+ else
+ FileUtils.touch 'tmp/caching-dev.txt'
+ puts 'Development mode is now being cached.'
+ end
+
+ FileUtils.touch 'tmp/restart.txt'
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/commands/rake_proxy.rb b/railties/lib/rails/commands/rake_proxy.rb
new file mode 100644
index 0000000000..f7d5df6b2f
--- /dev/null
+++ b/railties/lib/rails/commands/rake_proxy.rb
@@ -0,0 +1,34 @@
+require 'rake'
+require 'active_support'
+
+module Rails
+ module RakeProxy #:nodoc:
+ private
+ def run_rake_task(command)
+ ARGV.unshift(command) # Prepend the command, so Rake knows how to run it.
+
+ Rake.application.standard_exception_handling do
+ Rake.application.init('rails')
+ Rake.application.load_rakefile
+ Rake.application.top_level
+ end
+ end
+
+ def rake_tasks
+ return @rake_tasks if defined?(@rake_tasks)
+
+ ActiveSupport::Deprecation.silence do
+ require_application_and_environment!
+ end
+
+ Rake::TaskManager.record_task_metadata = true
+ Rake.application.instance_variable_set(:@name, 'rails')
+ Rails.application.load_tasks
+ @rake_tasks = Rake.application.tasks.select(&:comment)
+ end
+
+ def formatted_rake_tasks
+ rake_tasks.map { |t| [ t.name_with_args, t.comment ] }
+ end
+ end
+end
diff --git a/railties/lib/rails/gem_version.rb b/railties/lib/rails/gem_version.rb
index 7d74b1bfe5..92230a74e4 100644
--- a/railties/lib/rails/gem_version.rb
+++ b/railties/lib/rails/gem_version.rb
@@ -8,7 +8,7 @@ module Rails
MAJOR = 5
MINOR = 0
TINY = 0
- PRE = "alpha"
+ PRE = "beta1"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb
index 2645102619..e3d79521e7 100644
--- a/railties/lib/rails/generators.rb
+++ b/railties/lib/rails/generators.rb
@@ -208,6 +208,7 @@ module Rails
"#{test}:model",
"#{test}:scaffold",
"#{test}:view",
+ "#{test}:job",
"#{template}:controller",
"#{template}:scaffold",
"#{template}:mailer",
diff --git a/railties/lib/rails/generators/actions/create_migration.rb b/railties/lib/rails/generators/actions/create_migration.rb
index cffdef6ec9..d664b07652 100644
--- a/railties/lib/rails/generators/actions/create_migration.rb
+++ b/railties/lib/rails/generators/actions/create_migration.rb
@@ -3,7 +3,7 @@ require 'thor/actions'
module Rails
module Generators
module Actions
- class CreateMigration < Thor::Actions::CreateFile
+ class CreateMigration < Thor::Actions::CreateFile #:nodoc:
def migration_dir
File.dirname(@destination)
diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb
index 56c9d3e354..2f18619e30 100644
--- a/railties/lib/rails/generators/app_base.rb
+++ b/railties/lib/rails/generators/app_base.rb
@@ -26,6 +26,12 @@ module Rails
class_option :template, type: :string, aliases: '-m',
desc: "Path to some #{name} template (can be a filesystem path or URL)"
+ class_option :database, type: :string, aliases: '-d', default: 'sqlite3',
+ desc: "Preconfigure for selected database (options: #{DATABASES.join('/')})"
+
+ class_option :javascript, type: :string, aliases: '-j', default: 'jquery',
+ desc: 'Preconfigure for selected JavaScript library'
+
class_option :skip_gemfile, type: :boolean, default: false,
desc: "Don't create a Gemfile"
@@ -45,33 +51,30 @@ module Rails
class_option :skip_active_record, type: :boolean, aliases: '-O', default: false,
desc: 'Skip Active Record files'
+ class_option :skip_action_cable, type: :boolean, aliases: '-C', default: false,
+ desc: 'Skip Action Cable files'
+
class_option :skip_sprockets, type: :boolean, aliases: '-S', default: false,
desc: 'Skip Sprockets files'
class_option :skip_spring, type: :boolean, default: false,
desc: "Don't install Spring application preloader"
- class_option :database, type: :string, aliases: '-d', default: 'sqlite3',
- desc: "Preconfigure for selected database (options: #{DATABASES.join('/')})"
-
- class_option :javascript, type: :string, aliases: '-j', default: 'jquery',
- desc: 'Preconfigure for selected JavaScript library'
-
class_option :skip_javascript, type: :boolean, aliases: '-J', default: false,
desc: 'Skip JavaScript files'
- class_option :dev, type: :boolean, default: false,
- desc: "Setup the #{name} with Gemfile pointing to your Rails checkout"
-
- class_option :edge, type: :boolean, default: false,
- desc: "Setup the #{name} with Gemfile pointing to Rails repository"
-
class_option :skip_turbolinks, type: :boolean, default: false,
desc: 'Skip turbolinks gem'
class_option :skip_test, type: :boolean, aliases: '-T', default: false,
desc: 'Skip test files'
+ class_option :dev, type: :boolean, default: false,
+ desc: "Setup the #{name} with Gemfile pointing to your Rails checkout"
+
+ class_option :edge, type: :boolean, default: false,
+ desc: "Setup the #{name} with Gemfile pointing to Rails repository"
+
class_option :rc, type: :string, default: false,
desc: "Path to file containing extra configuration options for rails command"
@@ -168,7 +171,7 @@ module Rails
end
def include_all_railties?
- options.values_at(:skip_active_record, :skip_action_mailer, :skip_test, :skip_sprockets).none?
+ options.values_at(:skip_active_record, :skip_action_mailer, :skip_test, :skip_sprockets, :skip_action_cable).none?
end
def comment_if(value)
@@ -217,12 +220,7 @@ module Rails
def rails_gemfile_entry
dev_edge_common = [
- GemfileEntry.github('sprockets-rails', 'rails/sprockets-rails'),
- GemfileEntry.github('sprockets', 'rails/sprockets'),
- GemfileEntry.github('sass-rails', 'rails/sass-rails'),
- GemfileEntry.github('arel', 'rails/arel'),
- GemfileEntry.github('rack', 'rack/rack')
- ]
+ ]
if options.dev?
[
GemfileEntry.path('rails', Rails::Generators::RAILS_DEV_PATH)
@@ -233,11 +231,25 @@ module Rails
] + dev_edge_common
else
[GemfileEntry.version('rails',
- Rails::VERSION::STRING,
+ rails_version_specifier,
"Bundle edge Rails instead: gem 'rails', github: 'rails/rails'")]
end
end
+ def rails_version_specifier(gem_version = Rails.gem_version)
+ if gem_version.prerelease?
+ next_series = gem_version
+ next_series = next_series.bump while next_series.segments.size > 2
+
+ [">= #{gem_version}", "< #{next_series}"]
+ elsif gem_version.segments.size == 3
+ "~> #{gem_version}"
+ else
+ patch = gem_version.segments[0, 3].join(".")
+ ["~> #{patch}", ">= #{gem_version}"]
+ end
+ end
+
def gem_for_database
# %w( mysql oracle postgresql sqlite3 frontbase ibm_db sqlserver jdbcmysql jdbcsqlite3 jdbcpostgresql )
case options[:database]
@@ -278,10 +290,8 @@ module Rails
end
def jbuilder_gemfile_entry
- return [] if options[:api]
-
comment = 'Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder'
- GemfileEntry.version('jbuilder', '~> 2.0', comment)
+ GemfileEntry.new 'jbuilder', '~> 2.0', comment, {}, options[:api]
end
def coffee_gemfile_entry
diff --git a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb
index 65563aa6db..bc249aa5e5 100644
--- a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb
+++ b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb
@@ -9,13 +9,6 @@ module Erb # :nodoc:
view_base_path = File.join("app/views", class_path, file_name + '_mailer')
empty_directory view_base_path
- if self.behavior == :invoke
- 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
- end
-
actions.each do |action|
@action = action
diff --git a/railties/lib/rails/generators/erb/mailer/templates/layout.html.erb b/railties/lib/rails/generators/erb/mailer/templates/layout.html.erb
deleted file mode 100644
index 93110e74ad..0000000000
--- a/railties/lib/rails/generators/erb/mailer/templates/layout.html.erb
+++ /dev/null
@@ -1,5 +0,0 @@
-<html>
- <body>
- <%%= yield %>
- </body>
-</html>
diff --git a/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb b/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb
index d99b27cb2d..519b6c8603 100644
--- a/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb
+++ b/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb
@@ -14,15 +14,15 @@
<% attributes.each do |attribute| -%>
<div class="field">
<% if attribute.password_digest? -%>
- <%%= f.label :password %><br>
+ <%%= f.label :password %>
<%%= f.password_field :password %>
</div>
<div class="field">
- <%%= f.label :password_confirmation %><br>
+ <%%= f.label :password_confirmation %>
<%%= f.password_field :password_confirmation %>
<% else -%>
- <%%= f.label :<%= attribute.column_name %> %><br>
+ <%%= f.label :<%= attribute.column_name %> %>
<%%= f.<%= attribute.field_type %> :<%= attribute.column_name %> %>
<% end -%>
</div>
diff --git a/railties/lib/rails/generators/named_base.rb b/railties/lib/rails/generators/named_base.rb
index 243694f38e..658d883883 100644
--- a/railties/lib/rails/generators/named_base.rb
+++ b/railties/lib/rails/generators/named_base.rb
@@ -129,6 +129,18 @@ module Rails
uncountable? ? "#{plural_table_name}_index" : plural_table_name
end
+ def show_helper
+ "#{singular_table_name}_url(@#{singular_table_name})"
+ end
+
+ def edit_helper
+ "edit_#{show_helper}"
+ end
+
+ def new_helper
+ "new_#{singular_table_name}_url"
+ end
+
def singular_table_name
@singular_table_name ||= (pluralize_table_names? ? table_name.singularize : table_name)
end
diff --git a/railties/lib/rails/generators/rails/app/USAGE b/railties/lib/rails/generators/rails/app/USAGE
index 691095f33f..28df6ebf44 100644
--- a/railties/lib/rails/generators/rails/app/USAGE
+++ b/railties/lib/rails/generators/rails/app/USAGE
@@ -12,4 +12,3 @@ Example:
rails new ~/Code/Ruby/weblog
This generates a skeletal Rails installation in ~/Code/Ruby/weblog.
- See the README in the newly created application to get going.
diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb
index b813b083f4..44bbc478d0 100644
--- a/railties/lib/rails/generators/rails/app/app_generator.rb
+++ b/railties/lib/rails/generators/rails/app/app_generator.rb
@@ -57,8 +57,7 @@ module Rails
directory 'app'
keep_file 'app/assets/images'
- keep_file 'app/mailers'
- keep_file 'app/models'
+ keep_file 'app/assets/javascripts/channels' unless options[:skip_action_cable]
keep_file 'app/controllers/concerns'
keep_file 'app/models/concerns'
@@ -83,6 +82,7 @@ module Rails
directory "environments"
directory "initializers"
directory "locales"
+ directory "redis" unless options[:skip_action_cable]
end
end
@@ -293,6 +293,20 @@ module Rails
end
end
+ def delete_application_record_skipping_active_record
+ if options[:skip_active_record]
+ remove_file 'app/models/application_record.rb'
+ end
+ end
+
+ def delete_action_mailer_files_skipping_action_mailer
+ if options[:skip_action_mailer]
+ remove_file 'app/mailers/application_mailer.rb'
+ remove_file 'app/views/layouts/mailer.html.erb'
+ remove_file 'app/views/layouts/mailer.text.erb'
+ end
+ end
+
def delete_active_record_initializers_skipping_active_record
if options[:skip_active_record]
remove_file 'config/initializers/active_record_belongs_to_required_by_default.rb'
@@ -303,6 +317,7 @@ module Rails
if options[:api]
remove_file 'config/initializers/session_store.rb'
remove_file 'config/initializers/cookies_serializer.rb'
+ remove_file 'config/initializers/request_forgery_protection.rb'
end
end
diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile
index 4f3f59cc22..da5af4eefc 100644
--- a/railties/lib/rails/generators/rails/app/templates/Gemfile
+++ b/railties/lib/rails/generators/rails/app/templates/Gemfile
@@ -12,19 +12,16 @@ source 'https://rubygems.org'
<% end -%>
<% end -%>
+# Use Puma as the app server
+gem 'puma'
+
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
-# Use Unicorn as the app server
-# gem 'unicorn'
-
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
<%- if options.api? -%>
-# Use ActiveModelSerializers to serialize JSON responses
-gem 'active_model_serializers', '~> 0.10.0.rc2'
-
# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible
# gem 'rack-cors'
@@ -41,17 +38,13 @@ group :development do
<%- if options.dev? || options.edge? -%>
gem 'web-console', github: 'rails/web-console'
<%- else -%>
- gem 'web-console', '~> 2.0'
+ gem 'web-console', '~> 3.0'
<%- end -%>
<%- end -%>
<% if spring_install? -%>
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
<% end -%>
-
- # Loading the listen gem enables an evented file system monitor. Check
- # https://github.com/guard/listen#listen-adapters if on Windows or *BSD.
- # gem 'listen', '~> 3.0.4'
end
<% end -%>
diff --git a/railties/lib/rails/generators/rails/app/templates/app/assets/config/manifest.js.tt b/railties/lib/rails/generators/rails/app/templates/app/assets/config/manifest.js.tt
index f80631bac6..f4ee1409af 100644
--- a/railties/lib/rails/generators/rails/app/templates/app/assets/config/manifest.js.tt
+++ b/railties/lib/rails/generators/rails/app/templates/app/assets/config/manifest.js.tt
@@ -1,4 +1,3 @@
-
<% unless options.api? -%>
//= link_tree ../images
<% end -%>
diff --git a/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/cable.coffee b/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/cable.coffee
new file mode 100644
index 0000000000..49a7cfa69b
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/cable.coffee
@@ -0,0 +1,11 @@
+# Action Cable provides the framework to deal with WebSockets in Rails.
+# You can generate new channels where WebSocket features live using the rails generate channel command.
+#
+# Turn on the cable connection by removing the comments after the require statements (and ensure it's also on in config/routes.rb).
+#
+#= require action_cable
+#= require_self
+#= require_tree ./channels
+#
+# @App ||= {}
+# App.cable = ActionCable.createConsumer()
diff --git a/railties/lib/rails/generators/rails/app/templates/app/channels/application_cable/channel.rb b/railties/lib/rails/generators/rails/app/templates/app/channels/application_cable/channel.rb
new file mode 100644
index 0000000000..438c84154d
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/app/channels/application_cable/channel.rb
@@ -0,0 +1,5 @@
+# Be sure to restart your server when you modify this file. Action Cable runs in an EventMachine loop that does not support auto reloading.
+module ApplicationCable
+ class Channel < ActionCable::Channel::Base
+ end
+end
diff --git a/railties/lib/rails/generators/rails/app/templates/app/channels/application_cable/connection.rb b/railties/lib/rails/generators/rails/app/templates/app/channels/application_cable/connection.rb
new file mode 100644
index 0000000000..965046f3c7
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/app/channels/application_cable/connection.rb
@@ -0,0 +1,5 @@
+# Be sure to restart your server when you modify this file. Action Cable runs in an EventMachine loop that does not support auto reloading.
+module ApplicationCable
+ class Connection < ActionCable::Connection::Base
+ end
+end
diff --git a/actionmailer/lib/rails/generators/mailer/templates/application_mailer.rb b/railties/lib/rails/generators/rails/app/templates/app/mailers/application_mailer.rb
index d25d8892dd..286b2239d1 100644
--- a/actionmailer/lib/rails/generators/mailer/templates/application_mailer.rb
+++ b/railties/lib/rails/generators/rails/app/templates/app/mailers/application_mailer.rb
@@ -1,4 +1,4 @@
class ApplicationMailer < ActionMailer::Base
- default from: "from@example.com"
+ default from: 'from@example.com'
layout 'mailer'
end
diff --git a/railties/lib/rails/generators/rails/app/templates/app/models/application_record.rb b/railties/lib/rails/generators/rails/app/templates/app/models/application_record.rb
new file mode 100644
index 0000000000..10a4cba84d
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/app/models/application_record.rb
@@ -0,0 +1,3 @@
+class ApplicationRecord < ActiveRecord::Base
+ self.abstract_class = true
+end
diff --git a/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt b/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt
index 8bb4440f55..68b5c051b2 100644
--- a/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt
@@ -2,6 +2,11 @@
<html>
<head>
<title><%= camelized %></title>
+ <%%= csrf_meta_tags %>
+ <%- unless options[:skip_action_cable] -%>
+ <%%= action_cable_meta_tag %>
+ <%- end -%>
+
<%- if options[:skip_javascript] -%>
<%%= stylesheet_link_tag 'application', media: 'all' %>
<%- else -%>
@@ -13,12 +18,9 @@
<%%= javascript_include_tag 'application' %>
<%- end -%>
<%- end -%>
- <%%= csrf_meta_tags %>
</head>
<body>
-
<%%= yield %>
-
</body>
</html>
diff --git a/railties/lib/rails/generators/rails/app/templates/app/views/layouts/mailer.html.erb.tt b/railties/lib/rails/generators/rails/app/templates/app/views/layouts/mailer.html.erb.tt
new file mode 100644
index 0000000000..55f3675d49
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/app/views/layouts/mailer.html.erb.tt
@@ -0,0 +1,13 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+ <style>
+ /* Email styles need to be inline */
+ </style>
+ </head>
+
+ <body>
+ <%%= yield %>
+ </body>
+</html>
diff --git a/railties/lib/rails/generators/erb/mailer/templates/layout.text.erb b/railties/lib/rails/generators/rails/app/templates/app/views/layouts/mailer.text.erb.tt
index 6363733e6e..6363733e6e 100644
--- a/railties/lib/rails/generators/erb/mailer/templates/layout.text.erb
+++ b/railties/lib/rails/generators/rails/app/templates/app/views/layouts/mailer.text.erb.tt
diff --git a/railties/lib/rails/generators/rails/app/templates/bin/setup b/railties/lib/rails/generators/rails/app/templates/bin/setup
index 0c8b179827..df88bfd3bc 100644
--- a/railties/lib/rails/generators/rails/app/templates/bin/setup
+++ b/railties/lib/rails/generators/rails/app/templates/bin/setup
@@ -23,11 +23,11 @@ chdir APP_ROOT do
# end
puts "\n== Preparing database =="
- system! 'ruby bin/rake db:setup'
+ system! 'bin/rails db:setup'
puts "\n== Removing old logs and tempfiles =="
- system! 'ruby bin/rake log:clear tmp:clear'
+ system! 'bin/rails log:clear tmp:clear'
puts "\n== Restarting application server =="
- system! 'ruby bin/rake restart'
+ system! 'bin/rails restart'
end
diff --git a/railties/lib/rails/generators/rails/app/templates/bin/update b/railties/lib/rails/generators/rails/app/templates/bin/update
index 9830e6b29a..c6ed3ae64b 100644
--- a/railties/lib/rails/generators/rails/app/templates/bin/update
+++ b/railties/lib/rails/generators/rails/app/templates/bin/update
@@ -18,11 +18,11 @@ chdir APP_ROOT do
system 'bundle check' or system! 'bundle install'
puts "\n== Updating database =="
- system! 'bin/rake db:migrate'
+ system! 'bin/rails db:migrate'
puts "\n== Removing old logs and tempfiles =="
- system! 'bin/rake log:clear tmp:clear'
+ system! 'bin/rails log:clear tmp:clear'
puts "\n== Restarting application server =="
- system! 'bin/rake restart'
+ system! 'bin/rails restart'
end
diff --git a/railties/lib/rails/generators/rails/app/templates/config.ru b/railties/lib/rails/generators/rails/app/templates/config.ru
deleted file mode 100644
index bd83b25412..0000000000
--- a/railties/lib/rails/generators/rails/app/templates/config.ru
+++ /dev/null
@@ -1,4 +0,0 @@
-# This file is used by Rack-based servers to start the application.
-
-require ::File.expand_path('../config/environment', __FILE__)
-run Rails.application
diff --git a/railties/lib/rails/generators/rails/app/templates/config.ru.tt b/railties/lib/rails/generators/rails/app/templates/config.ru.tt
new file mode 100644
index 0000000000..70556fcc99
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config.ru.tt
@@ -0,0 +1,11 @@
+# This file is used by Rack-based servers to start the application.
+
+require ::File.expand_path('../config/environment', __FILE__)
+<%- unless options[:skip_action_cable] -%>
+
+# Action Cable uses EventMachine which requires that all classes are loaded in advance
+Rails.application.eager_load!
+require 'action_cable/process/logging'
+<%- end -%>
+
+run Rails.application
diff --git a/railties/lib/rails/generators/rails/app/templates/config/application.rb b/railties/lib/rails/generators/rails/app/templates/config/application.rb
index ddd0fcade1..cb83364360 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/application.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/application.rb
@@ -11,6 +11,7 @@ require "active_job/railtie"
require "action_controller/railtie"
<%= comment_if :skip_action_mailer %>require "action_mailer/railtie"
require "action_view/railtie"
+<%= comment_if :skip_action_cable %>require "action_cable/engine"
<%= comment_if :skip_sprockets %>require "sprockets/railtie"
<%= comment_if :skip_test %>require "rails/test_unit/railtie"
<% end -%>
@@ -24,14 +25,6 @@ module <%= app_const_base %>
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
-
- # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
- # Run "rake time:zones:all" for a time zone names list. Default is UTC.
- # config.time_zone = 'Central Time (US & Canada)'
-
- # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
- # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
- # config.i18n.default_locale = :de
<%- if options[:api] -%>
# Only loads a smaller set of middleware suitable for API only apps.
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
index 4dd20a9d2e..fd41372d9c 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
@@ -10,7 +10,7 @@ Rails.application.configure do
config.eager_load = false
# Show full error reports.
- config.consider_all_requests_local = true
+ config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
if Rails.root.join('tmp/caching-dev.txt').exist?
@@ -23,7 +23,6 @@ Rails.application.configure do
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
-
<%- unless options.skip_action_mailer? -%>
# Don't care if the mailer can't send.
@@ -56,4 +55,8 @@ Rails.application.configure do
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
+
+ # Use an evented file watcher to asynchronously detect changes in source code,
+ # routes, locales, etc. This feature depends on the listen gem.
+ # config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end
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 a5302550fa..8d59a6fcf3 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
@@ -40,6 +40,12 @@ Rails.application.configure do
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
+ <%- unless options[:skip_action_cable] -%>
+ # Action Cable endpoint configuration
+ # config.action_cable.url = 'wss://example.com/cable'
+ # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
+ <%- end -%>
+
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/active_record_belongs_to_required_by_default.rb b/railties/lib/rails/generators/rails/app/templates/config/initializers/active_record_belongs_to_required_by_default.rb
index 30c4f89792..40c831ec58 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/initializers/active_record_belongs_to_required_by_default.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/active_record_belongs_to_required_by_default.rb
@@ -1,4 +1,5 @@
# Be sure to restart your server when you modify this file.
-# Require `belongs_to` associations by default.
+# Require `belongs_to` associations by default. This is a new Rails 5.0 default,
+# so introduced as a config to ensure apps made with earlier versions of Rails aren't affected when upgrading.
Rails.application.config.active_record.belongs_to_required_by_default = true
diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/application_controller_renderer.rb b/railties/lib/rails/generators/rails/app/templates/config/initializers/application_controller_renderer.rb
index ea930f54da..51639b67a0 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/initializers/application_controller_renderer.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/application_controller_renderer.rb
@@ -1,5 +1,5 @@
-## Change renderer defaults here.
-#
+# Be sure to restart your server when you modify this file.
+
# ApplicationController.renderer.defaults.merge!(
# http_host: 'example.org',
# https: false
diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/callback_terminator.rb b/railties/lib/rails/generators/rails/app/templates/config/initializers/callback_terminator.rb
index a70a1b9cde..43510c244b 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/initializers/callback_terminator.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/callback_terminator.rb
@@ -1,4 +1,5 @@
# Be sure to restart your server when you modify this file.
-# Do not halt callback chains when a callback returns false.
+# Do not halt callback chains when a callback returns false. This is a new Rails 5.0 default,
+# so introduced as a config to ensure apps made with earlier versions of Rails aren't affected when upgrading.
ActiveSupport.halt_callback_chains_on_return_false = false
diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/cookies_serializer.rb b/railties/lib/rails/generators/rails/app/templates/config/initializers/cookies_serializer.rb
index 7f70458dee..5a6a32d371 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/initializers/cookies_serializer.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/cookies_serializer.rb
@@ -1,3 +1,5 @@
# Be sure to restart your server when you modify this file.
+# Specify a serializer for the signed and encrypted cookie jars.
+# Valid options are :json, :marshal, and :hybrid.
Rails.application.config.action_dispatch.cookies_serializer = :json
diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/request_forgery_protection.rb b/railties/lib/rails/generators/rails/app/templates/config/initializers/request_forgery_protection.rb
new file mode 100644
index 0000000000..3eab78a885
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/request_forgery_protection.rb
@@ -0,0 +1,4 @@
+# Be sure to restart your server when you modify this file.
+
+# Enable origin-checking CSRF mitigation.
+Rails.application.config.action_controller.forgery_protection_origin_check = true
diff --git a/railties/lib/rails/generators/rails/app/templates/config/redis/cable.yml b/railties/lib/rails/generators/rails/app/templates/config/redis/cable.yml
new file mode 100644
index 0000000000..0176be24f9
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/redis/cable.yml
@@ -0,0 +1,9 @@
+# Action Cable uses Redis to administer connections, channels, and sending/receiving messages over the WebSocket.
+production:
+ url: redis://localhost:6379/1
+
+development:
+ url: redis://localhost:6379/2
+
+test:
+ url: redis://localhost:6379/3
diff --git a/railties/lib/rails/generators/rails/app/templates/config/routes.rb b/railties/lib/rails/generators/rails/app/templates/config/routes.rb
index 787824f888..8293c8a483 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/routes.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/routes.rb
@@ -1,3 +1,6 @@
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
+
+ # Serve websocket cable requests in-process
+ # mount ActionCable.server => '/cable'
end
diff --git a/railties/lib/rails/generators/rails/app/templates/db/seeds.rb.tt b/railties/lib/rails/generators/rails/app/templates/db/seeds.rb.tt
index 4edb1e857e..cfadd24017 100644
--- a/railties/lib/rails/generators/rails/app/templates/db/seeds.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/db/seeds.rb.tt
@@ -1,7 +1,7 @@
# This file should contain all the record creation needed to seed the database with its default values.
-# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
+# The data can then be loaded with the rails db:seed (or created alongside the db with db:setup).
#
# Examples:
#
-# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
-# Mayor.create(name: 'Emanuel', city: cities.first)
+# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
+# Character.create(name: 'Luke', movie: movies.first)
diff --git a/railties/lib/rails/generators/rails/app/templates/gitignore b/railties/lib/rails/generators/rails/app/templates/gitignore
index 1b8cf8a9fa..0e66cc4237 100644
--- a/railties/lib/rails/generators/rails/app/templates/gitignore
+++ b/railties/lib/rails/generators/rails/app/templates/gitignore
@@ -20,3 +20,6 @@
!/log/.keep
!/tmp/.keep
<% end -%>
+
+# Ignore Byebug command history file.
+.byebug_history
diff --git a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb
index eeeef430bb..7d7477de75 100644
--- a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb
+++ b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb
@@ -37,7 +37,7 @@ module Rails
end
def readme
- template "README.rdoc"
+ template "README.md"
end
def gemfile
@@ -148,9 +148,8 @@ task default: :test
end
def bin(force = false)
- return unless engine?
-
- directory "bin", force: force do |content|
+ bin_file = engine? ? 'bin/rails.tt' : 'bin/test.tt'
+ template bin_file, force: force do |content|
"#{shebang}\n" + content
end
chmod "bin", 0755, verbose: false
diff --git a/railties/lib/rails/generators/rails/plugin/templates/%name%.gemspec b/railties/lib/rails/generators/rails/plugin/templates/%name%.gemspec
index ff242adbab..d84d1aabdb 100644
--- a/railties/lib/rails/generators/rails/plugin/templates/%name%.gemspec
+++ b/railties/lib/rails/generators/rails/plugin/templates/%name%.gemspec
@@ -14,12 +14,9 @@ Gem::Specification.new do |s|
s.description = "TODO: Description of <%= camelized_modules %>."
s.license = "MIT"
- s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
-<% unless options.skip_test? -%>
- s.test_files = Dir["test/**/*"]
-<% end -%>
+ s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"]
- <%= '# ' if options.dev? || options.edge? -%>s.add_dependency "rails", "~> <%= Rails::VERSION::STRING %>"
+ <%= '# ' if options.dev? || options.edge? -%>s.add_dependency "rails", "<%= Array(rails_version_specifier).join('", "') %>"
<% unless options[:skip_active_record] -%>
s.add_development_dependency "<%= gem_for_database[0] %>"
diff --git a/railties/lib/rails/generators/rails/plugin/templates/Gemfile b/railties/lib/rails/generators/rails/plugin/templates/Gemfile
index f085a2577a..22a4548ff2 100644
--- a/railties/lib/rails/generators/rails/plugin/templates/Gemfile
+++ b/railties/lib/rails/generators/rails/plugin/templates/Gemfile
@@ -1,7 +1,7 @@
source 'https://rubygems.org'
<% if options[:skip_gemspec] -%>
-<%= '# ' if options.dev? || options.edge? -%>gem 'rails', '~> <%= Rails::VERSION::STRING %>'
+<%= '# ' if options.dev? || options.edge? -%>gem 'rails', '<%= Array(rails_version_specifier).join("', '") %>'
<% else -%>
# Declare your gem's dependencies in <%= name %>.gemspec.
# Bundler will treat runtime dependencies like base dependencies, and
diff --git a/railties/lib/rails/generators/rails/plugin/templates/README.md b/railties/lib/rails/generators/rails/plugin/templates/README.md
new file mode 100644
index 0000000000..61ad1ed36a
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin/templates/README.md
@@ -0,0 +1,3 @@
+# <%= camelized_modules %>
+
+This project rocks and uses MIT-LICENSE.
diff --git a/railties/lib/rails/generators/rails/plugin/templates/README.rdoc b/railties/lib/rails/generators/rails/plugin/templates/README.rdoc
deleted file mode 100644
index 25983ca5da..0000000000
--- a/railties/lib/rails/generators/rails/plugin/templates/README.rdoc
+++ /dev/null
@@ -1,3 +0,0 @@
-= <%= camelized_modules %>
-
-This project rocks and uses MIT-LICENSE. \ No newline at end of file
diff --git a/railties/lib/rails/generators/rails/plugin/templates/Rakefile b/railties/lib/rails/generators/rails/plugin/templates/Rakefile
index bda55bae29..f1943644e4 100644
--- a/railties/lib/rails/generators/rails/plugin/templates/Rakefile
+++ b/railties/lib/rails/generators/rails/plugin/templates/Rakefile
@@ -10,7 +10,7 @@ RDoc::Task.new(:rdoc) do |rdoc|
rdoc.rdoc_dir = 'rdoc'
rdoc.title = '<%= camelized_modules %>'
rdoc.options << '--line-numbers'
- rdoc.rdoc_files.include('README.rdoc')
+ rdoc.rdoc_files.include('README.md')
rdoc.rdoc_files.include('lib/**/*.rb')
end
diff --git a/railties/lib/rails/generators/rails/plugin/templates/app/models/application_record.rb.tt b/railties/lib/rails/generators/rails/plugin/templates/app/models/application_record.rb.tt
new file mode 100644
index 0000000000..8aa3de78f1
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin/templates/app/models/application_record.rb.tt
@@ -0,0 +1,6 @@
+<%= wrap_in_modules <<-rb.strip_heredoc
+ class ApplicationRecord < ActiveRecord::Base
+ self.abstract_class = true
+ end
+rb
+%>
diff --git a/railties/lib/rails/generators/rails/plugin/templates/bin/test.tt b/railties/lib/rails/generators/rails/plugin/templates/bin/test.tt
new file mode 100644
index 0000000000..62b94618fd
--- /dev/null
+++ b/railties/lib/rails/generators/rails/plugin/templates/bin/test.tt
@@ -0,0 +1,8 @@
+$: << File.expand_path(File.expand_path('../../test', __FILE__))
+
+require 'bundler/setup'
+require 'rails/test_unit/minitest_plugin'
+
+Rails::TestUnitReporter.executable = 'bin/test'
+
+exit Minitest.run(ARGV)
diff --git a/railties/lib/rails/generators/rails/plugin/templates/rails/routes.rb b/railties/lib/rails/generators/rails/plugin/templates/rails/routes.rb
index 673de44108..694510edc0 100644
--- a/railties/lib/rails/generators/rails/plugin/templates/rails/routes.rb
+++ b/railties/lib/rails/generators/rails/plugin/templates/rails/routes.rb
@@ -1,4 +1,3 @@
Rails.application.routes.draw do
-
mount <%= camelized_modules %>::Engine => "/<%= name %>"
end
diff --git a/railties/lib/rails/generators/rails/plugin/templates/test/test_helper.rb b/railties/lib/rails/generators/rails/plugin/templates/test/test_helper.rb
index f315144723..a0b00fc5c5 100644
--- a/railties/lib/rails/generators/rails/plugin/templates/test/test_helper.rb
+++ b/railties/lib/rails/generators/rails/plugin/templates/test/test_helper.rb
@@ -14,6 +14,10 @@ require "rails/test_help"
# to be shown.
Minitest.backtrace_filter = Minitest::BacktraceFilter.new
+<% unless engine? -%>
+Rails::TestUnitReporter.executable = 'bin/test'
+<% end -%>
+
# Load fixtures from the engine
if ActiveSupport::TestCase.respond_to?(:fixture_path=)
ActiveSupport::TestCase.fixture_path = File.expand_path("../fixtures", __FILE__)
diff --git a/railties/lib/rails/generators/rails/scaffold/templates/scaffold.css b/railties/lib/rails/generators/rails/scaffold/templates/scaffold.css
index b7818883d1..79f8b7f96f 100644
--- a/railties/lib/rails/generators/rails/scaffold/templates/scaffold.css
+++ b/railties/lib/rails/generators/rails/scaffold/templates/scaffold.css
@@ -78,3 +78,7 @@ div.actions {
font-size: 12px;
list-style: square;
}
+
+label {
+ display: block;
+}
diff --git a/railties/lib/rails/generators/rails/scaffold_controller/templates/api_controller.rb b/railties/lib/rails/generators/rails/scaffold_controller/templates/api_controller.rb
index 17a86f376b..400afec6dc 100644
--- a/railties/lib/rails/generators/rails/scaffold_controller/templates/api_controller.rb
+++ b/railties/lib/rails/generators/rails/scaffold_controller/templates/api_controller.rb
@@ -52,7 +52,7 @@ class <%= controller_class_name %>Controller < ApplicationController
# Only allow a trusted parameter "white list" through.
def <%= "#{singular_table_name}_params" %>
<%- if attributes_names.empty? -%>
- params[:<%= singular_table_name %>]
+ params.fetch(:<%= singular_table_name %>, {})
<%- else -%>
params.require(:<%= singular_table_name %>).permit(<%= attributes_names.map { |name| ":#{name}" }.join(', ') %>)
<%- end -%>
diff --git a/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb b/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb
index f73e9a96ba..42b9e34274 100644
--- a/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb
+++ b/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb
@@ -59,7 +59,7 @@ class <%= controller_class_name %>Controller < ApplicationController
# Only allow a trusted parameter "white list" through.
def <%= "#{singular_table_name}_params" %>
<%- if attributes_names.empty? -%>
- params[:<%= singular_table_name %>]
+ params.fetch(:<%= singular_table_name %>, {})
<%- else -%>
params.require(:<%= singular_table_name %>).permit(<%= attributes_names.map { |name| ":#{name}" }.join(', ') %>)
<%- end -%>
diff --git a/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb b/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb
index 5a8a3ca5e0..4f2ceb8589 100644
--- a/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb
+++ b/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb
@@ -1,11 +1,9 @@
require 'test_helper'
<% module_namespacing do -%>
-class <%= class_name %>ControllerTest < ActionController::TestCase
+class <%= class_name %>ControllerTest < ActionDispatch::IntegrationTest
<% if mountable_engine? -%>
- setup do
- @routes = Engine.routes
- end
+ include Engine.routes.url_helpers
<% end -%>
<% if actions.empty? -%>
@@ -15,7 +13,7 @@ class <%= class_name %>ControllerTest < ActionController::TestCase
<% else -%>
<% actions.each do |action| -%>
test "should get <%= action %>" do
- get :<%= action %>
+ get <%= file_name %>_<%= action %>_url
assert_response :success
end
diff --git a/railties/lib/rails/generators/test_unit/scaffold/templates/api_functional_test.rb b/railties/lib/rails/generators/test_unit/scaffold/templates/api_functional_test.rb
index f302cd6c3d..0d18478043 100644
--- a/railties/lib/rails/generators/test_unit/scaffold/templates/api_functional_test.rb
+++ b/railties/lib/rails/generators/test_unit/scaffold/templates/api_functional_test.rb
@@ -1,40 +1,41 @@
require 'test_helper'
<% module_namespacing do -%>
-class <%= controller_class_name %>ControllerTest < ActionController::TestCase
+class <%= controller_class_name %>ControllerTest < ActionDispatch::IntegrationTest
+ <%- if mountable_engine? -%>
+ include Engine.routes.url_helpers
+
+ <%- end -%>
setup do
@<%= singular_table_name %> = <%= fixture_name %>(:one)
-<% if mountable_engine? -%>
- @routes = Engine.routes
-<% end -%>
end
test "should get index" do
- get :index
+ get <%= index_helper %>_url
assert_response :success
end
test "should create <%= singular_table_name %>" do
assert_difference('<%= class_name %>.count') do
- post :create, params: { <%= "#{singular_table_name}: { #{attributes_hash} }" %> }
+ post <%= index_helper %>_url, params: { <%= "#{singular_table_name}: { #{attributes_hash} }" %> }
end
assert_response 201
end
test "should show <%= singular_table_name %>" do
- get :show, params: { id: <%= "@#{singular_table_name}" %> }
+ get <%= show_helper %>
assert_response :success
end
test "should update <%= singular_table_name %>" do
- patch :update, params: { id: <%= "@#{singular_table_name}" %>, <%= "#{singular_table_name}: { #{attributes_hash} }" %> }
+ patch <%= show_helper %>, params: { <%= "#{singular_table_name}: { #{attributes_hash} }" %> }
assert_response 200
end
test "should destroy <%= singular_table_name %>" do
assert_difference('<%= class_name %>.count', -1) do
- delete :destroy, params: { id: <%= "@#{singular_table_name}" %> }
+ delete <%= show_helper %>
end
assert_response 204
diff --git a/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb b/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb
index 50b98b2631..0e6bef12fc 100644
--- a/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb
+++ b/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb
@@ -1,50 +1,51 @@
require 'test_helper'
<% module_namespacing do -%>
-class <%= controller_class_name %>ControllerTest < ActionController::TestCase
+class <%= controller_class_name %>ControllerTest < ActionDispatch::IntegrationTest
+ <%- if mountable_engine? -%>
+ include Engine.routes.url_helpers
+
+ <%- end -%>
setup do
@<%= singular_table_name %> = <%= fixture_name %>(:one)
-<% if mountable_engine? -%>
- @routes = Engine.routes
-<% end -%>
end
test "should get index" do
- get :index
+ get <%= index_helper %>_url
assert_response :success
end
test "should get new" do
- get :new
+ get <%= new_helper %>
assert_response :success
end
test "should create <%= singular_table_name %>" do
assert_difference('<%= class_name %>.count') do
- post :create, params: { <%= "#{singular_table_name}: { #{attributes_hash} }" %> }
+ post <%= index_helper %>_url, params: { <%= "#{singular_table_name}: { #{attributes_hash} }" %> }
end
assert_redirected_to <%= singular_table_name %>_path(<%= class_name %>.last)
end
test "should show <%= singular_table_name %>" do
- get :show, params: { id: <%= "@#{singular_table_name}" %> }
+ get <%= show_helper %>
assert_response :success
end
test "should get edit" do
- get :edit, params: { id: <%= "@#{singular_table_name}" %> }
+ get <%= edit_helper %>
assert_response :success
end
test "should update <%= singular_table_name %>" do
- patch :update, params: { id: <%= "@#{singular_table_name}" %>, <%= "#{singular_table_name}: { #{attributes_hash} }" %> }
+ patch <%= show_helper %>, params: { <%= "#{singular_table_name}: { #{attributes_hash} }" %> }
assert_redirected_to <%= singular_table_name %>_path(<%= "@#{singular_table_name}" %>)
end
test "should destroy <%= singular_table_name %>" do
assert_difference('<%= class_name %>.count', -1) do
- delete :destroy, params: { id: <%= "@#{singular_table_name}" %> }
+ delete <%= show_helper %>
end
assert_redirected_to <%= index_helper %>_path
diff --git a/railties/lib/rails/tasks.rb b/railties/lib/rails/tasks.rb
index d3e33584d7..d60eaf6f4f 100644
--- a/railties/lib/rails/tasks.rb
+++ b/railties/lib/rails/tasks.rb
@@ -3,7 +3,6 @@ require 'rake'
# Load Rails Rakefile extensions
%w(
annotations
- dev
framework
initializers
log
diff --git a/railties/lib/rails/tasks/dev.rake b/railties/lib/rails/tasks/dev.rake
deleted file mode 100644
index e949172d3f..0000000000
--- a/railties/lib/rails/tasks/dev.rake
+++ /dev/null
@@ -1,15 +0,0 @@
-namespace :dev do
- task :cache do
- desc 'Toggle development mode caching on/off'
-
- if File.exist? 'tmp/caching-dev.txt'
- File.delete 'tmp/caching-dev.txt'
- puts 'Development mode is no longer being cached.'
- else
- FileUtils.touch 'tmp/caching-dev.txt'
- puts 'Development mode is now being cached.'
- end
-
- FileUtils.touch 'tmp/restart.txt'
- end
-end
diff --git a/railties/lib/rails/test_unit/minitest_plugin.rb b/railties/lib/rails/test_unit/minitest_plugin.rb
index d1ba35a5ec..d39d2f32bf 100644
--- a/railties/lib/rails/test_unit/minitest_plugin.rb
+++ b/railties/lib/rails/test_unit/minitest_plugin.rb
@@ -14,15 +14,16 @@ module Minitest
SummaryReporter.prepend AggregatedResultSuppresion
def self.plugin_rails_options(opts, options)
+ executable = ::Rails::TestUnitReporter.executable
opts.separator ""
- opts.separator "Usage: bin/rails test [options] [files or directories]"
+ opts.separator "Usage: #{executable} [options] [files or directories]"
opts.separator "You can run a single test by appending a line number to a filename:"
opts.separator ""
- opts.separator " bin/rails test test/models/user_test.rb:27"
+ opts.separator " #{executable} test/models/user_test.rb:27"
opts.separator ""
opts.separator "You can run multiple files and directories at the same time:"
opts.separator ""
- opts.separator " bin/rails test test/controllers test/integration/login_test.rb"
+ opts.separator " #{executable} test/controllers test/integration/login_test.rb"
opts.separator ""
opts.separator "By default test failures and errors are reported inline during a run."
opts.separator ""
@@ -56,7 +57,9 @@ module Minitest
# as the patterns would also contain the other Rake tasks.
def self.rake_run(patterns) # :nodoc:
@rake_patterns = patterns
- run
+ passed = run
+ exit passed unless passed
+ passed
end
def self.plugin_rails_init(options)
diff --git a/railties/lib/rails/test_unit/reporter.rb b/railties/lib/rails/test_unit/reporter.rb
index de4b002e55..00ea32d1b8 100644
--- a/railties/lib/rails/test_unit/reporter.rb
+++ b/railties/lib/rails/test_unit/reporter.rb
@@ -44,7 +44,7 @@ module Rails
end
def relative_path_for(file)
- file.sub(/^#{Rails.root}\/?/, '')
+ file.sub(/^#{app_root}\/?/, '')
end
private
@@ -66,5 +66,9 @@ module Rails
"#{self.executable} #{relative_path_for(assertion_path)}"
end
+
+ def app_root
+ @app_root ||= defined?(ENGINE_ROOT) ? ENGINE_ROOT : Rails.root
+ end
end
end
diff --git a/railties/test/application/asset_debugging_test.rb b/railties/test/application/asset_debugging_test.rb
index 8b83784ed6..0659110ac0 100644
--- a/railties/test/application/asset_debugging_test.rb
+++ b/railties/test/application/asset_debugging_test.rb
@@ -58,7 +58,7 @@ module ApplicationTests
assert_no_match(/<script src="\/assets\/xmlhr-([0-z]+)\.js"><\/script>/, last_response.body)
end
- test "assets are served with sourcemaps when compile is true and debug_assets params is true" do
+ test "assets aren't concatenated when compile is true is on and debug_assets params is true" do
add_to_env_config "production", "config.assets.compile = true"
# Load app env
@@ -67,7 +67,8 @@ module ApplicationTests
class ::PostsController < ActionController::Base ; end
get '/posts?debug_assets=true'
- assert_match(/<script src="\/assets\/application(\.debug)?-([0-z]+)\.js"><\/script>/, last_response.body)
+ assert_match(/<script src="\/assets\/application(\.self)?-([0-z]+)\.js\?body=1"><\/script>/, last_response.body)
+ assert_match(/<script src="\/assets\/xmlhr(\.self)?-([0-z]+)\.js\?body=1"><\/script>/, last_response.body)
end
end
end
diff --git a/railties/test/application/assets_test.rb b/railties/test/application/assets_test.rb
index 18882e1855..5f3b364f97 100644
--- a/railties/test/application/assets_test.rb
+++ b/railties/test/application/assets_test.rb
@@ -174,7 +174,7 @@ module ApplicationTests
precompile!
- assert_file_exists("#{app_path}/public/assets/something-*.js")
+ assert_file_exists("#{app_path}/public/assets/something/index-*.js")
end
test 'precompile use assets defined in app env config' do
@@ -410,7 +410,7 @@ module ApplicationTests
precompile!
- assert_equal "Post\n;\n", File.read(Dir["#{app_path}/public/assets/application-*.js"].first)
+ assert_match(/Post;/, File.read(Dir["#{app_path}/public/assets/application-*.js"].first))
end
test "initialization on the assets group should set assets_dir" do
@@ -458,9 +458,9 @@ module ApplicationTests
class ::PostsController < ActionController::Base; end
get '/posts', {}, {'HTTPS'=>'off'}
- assert_match('src="http://example.com/assets/application.debug.js', last_response.body)
+ assert_match('src="http://example.com/assets/application.self.js', last_response.body)
get '/posts', {}, {'HTTPS'=>'on'}
- assert_match('src="https://example.com/assets/application.debug.js', last_response.body)
+ assert_match('src="https://example.com/assets/application.self.js', last_response.body)
end
test "asset urls should be protocol-relative if no request is in scope" do
diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb
index 5f3d1879eb..50d343865c 100644
--- a/railties/test/application/configuration_test.rb
+++ b/railties/test/application/configuration_test.rb
@@ -103,7 +103,7 @@ module ApplicationTests
RUBY
app_file 'db/migrate/20140708012246_create_user.rb', <<-RUBY
- class CreateUser < ActiveRecord::Migration
+ class CreateUser < ActiveRecord::Migration::Current
def change
create_table :users
end
@@ -228,6 +228,8 @@ module ApplicationTests
end
test "the application can be eager loaded even when there are no frameworks" do
+ FileUtils.rm_rf("#{app_path}/app/models/application_record.rb")
+ FileUtils.rm_rf("#{app_path}/app/mailers/application_mailer.rb")
FileUtils.rm_rf("#{app_path}/config/environments")
add_to_config <<-RUBY
config.eager_load = true
@@ -1306,6 +1308,21 @@ module ApplicationTests
assert_equal 'custom key', Rails.application.config.my_custom_config['key']
end
+ test "config_for use the Pathname object if it is provided" do
+ app_file 'config/custom.yml', <<-RUBY
+ development:
+ key: 'custom key'
+ RUBY
+
+ add_to_config <<-RUBY
+ config.my_custom_config = config_for(Pathname.new(Rails.root.join("config/custom.yml")))
+ RUBY
+
+ app 'development'
+
+ assert_equal 'custom key', Rails.application.config.my_custom_config['key']
+ end
+
test "config_for raises an exception if the file does not exist" do
add_to_config <<-RUBY
config.my_custom_config = config_for('custom')
@@ -1393,5 +1410,45 @@ module ApplicationTests
assert_equal 'unicorn', Rails.application.config.my_custom_config['key']
end
+
+ test "api_only is false by default" do
+ app 'development'
+ refute Rails.application.config.api_only
+ end
+
+ test "api_only generator config is set when api_only is set" do
+ add_to_config <<-RUBY
+ config.api_only = true
+ RUBY
+ app 'development'
+
+ Rails.application.load_generators
+ assert Rails.configuration.api_only
+ end
+
+ test "debug_exception_response_format is :api by default if only_api is enabled" do
+ add_to_config <<-RUBY
+ config.api_only = true
+ RUBY
+ app 'development'
+
+ assert_equal :api, Rails.configuration.debug_exception_response_format
+ end
+
+ test "debug_exception_response_format can be override" do
+ add_to_config <<-RUBY
+ config.api_only = true
+ RUBY
+
+ app_file 'config/environments/development.rb', <<-RUBY
+ Rails.application.configure do
+ config.debug_exception_response_format = :default
+ end
+ RUBY
+
+ app 'development'
+
+ assert_equal :default, Rails.configuration.debug_exception_response_format
+ end
end
end
diff --git a/railties/test/application/loading_test.rb b/railties/test/application/loading_test.rb
index 1027bca2c1..2cc599ca6f 100644
--- a/railties/test/application/loading_test.rb
+++ b/railties/test/application/loading_test.rb
@@ -169,6 +169,8 @@ class LoadingTest < ActiveSupport::TestCase
config.file_watcher = Class.new do
def initialize(*); end
def updated?; false; end
+ def execute; end
+ def execute_if_updated; false; end
end
RUBY
@@ -288,7 +290,7 @@ class LoadingTest < ActiveSupport::TestCase
extend Rack::Test::Methods
app_file "db/migrate/1_create_posts.rb", <<-MIGRATION
- class CreatePosts < ActiveRecord::Migration
+ class CreatePosts < ActiveRecord::Migration::Current
def change
create_table :posts do |t|
t.string :title, default: "TITLE"
@@ -304,7 +306,7 @@ class LoadingTest < ActiveSupport::TestCase
assert_equal "TITLE", last_response.body
app_file "db/migrate/2_add_body_to_posts.rb", <<-MIGRATION
- class AddBodyToPosts < ActiveRecord::Migration
+ class AddBodyToPosts < ActiveRecord::Migration::Current
def change
add_column :posts, :body, :text, default: "BODY"
end
diff --git a/railties/test/application/middleware/static_test.rb b/railties/test/application/middleware/static_test.rb
index 5366537dc2..1246e20d94 100644
--- a/railties/test/application/middleware/static_test.rb
+++ b/railties/test/application/middleware/static_test.rb
@@ -44,7 +44,7 @@ module ApplicationTests
assert_equal 'public, max-age=60', last_response.headers["Cache-Control"]
end
- test "static_index defaults to 'index'" do
+ test "public_file_server.index_name defaults to 'index'" do
app_file "public/index.html", "/index.html"
require "#{app_path}/config/environment"
@@ -54,10 +54,10 @@ module ApplicationTests
assert_equal "/index.html\n", last_response.body
end
- test "static_index configurable" do
+ test "public_file_server.index_name configurable" do
app_file "public/other-index.html", "/other-index.html"
- add_to_config "config.static_index = 'other-index'"
-
+ add_to_config "config.public_file_server.index_name = 'other-index'"
+
require "#{app_path}/config/environment"
get '/'
diff --git a/railties/test/application/rake/dbs_test.rb b/railties/test/application/rake/dbs_test.rb
index f94d08673a..0b0fb50fe1 100644
--- a/railties/test/application/rake/dbs_test.rb
+++ b/railties/test/application/rake/dbs_test.rb
@@ -61,7 +61,7 @@ module ApplicationTests
test 'db:create failure because database exists' do
with_database_existing do
output = `bin/rake db:create 2>&1`
- assert_match /already exists/, output
+ assert_match(/already exists/, output)
assert_equal 0, $?.exitstatus
end
end
@@ -78,7 +78,7 @@ module ApplicationTests
test 'db:create failure because bad permissions' do
with_bad_permissions do
output = `bin/rake db:create 2>&1`
- assert_match /Couldn't create database/, output
+ assert_match(/Couldn't create database/, output)
assert_equal 1, $?.exitstatus
end
end
@@ -86,7 +86,7 @@ module ApplicationTests
test 'db:drop failure because database does not exist' do
Dir.chdir(app_path) do
output = `bin/rake db:drop 2>&1`
- assert_match /does not exist/, output
+ assert_match(/does not exist/, output)
assert_equal 0, $?.exitstatus
end
end
@@ -95,7 +95,7 @@ module ApplicationTests
with_database_existing do
with_bad_permissions do
output = `bin/rake db:drop 2>&1`
- assert_match /Couldn't drop/, output
+ assert_match(/Couldn't drop/, output)
assert_equal 1, $?.exitstatus
end
end
diff --git a/railties/test/application/rake/dev_test.rb b/railties/test/application/rake/dev_test.rb
deleted file mode 100644
index 28d8b22a37..0000000000
--- a/railties/test/application/rake/dev_test.rb
+++ /dev/null
@@ -1,35 +0,0 @@
-require 'isolation/abstract_unit'
-
-module ApplicationTests
- module RakeTests
- class RakeDevTest < ActiveSupport::TestCase
- include ActiveSupport::Testing::Isolation
-
- def setup
- build_app
- boot_rails
- end
-
- def teardown
- teardown_app
- end
-
- test 'dev:cache creates file and outputs message' do
- Dir.chdir(app_path) do
- output = `rake dev:cache`
- assert File.exist?('tmp/caching-dev.txt')
- assert_match(/Development mode is now being cached/, output)
- end
- end
-
- test 'dev:cache deletes file and outputs message' do
- Dir.chdir(app_path) do
- output = `rake dev:cache`
- output = `rake dev:cache`
- assert_not File.exist?('tmp/caching-dev.txt')
- assert_match(/Development mode is no longer being cached/, output)
- end
- end
- end
- end
-end
diff --git a/railties/test/application/rake/migrations_test.rb b/railties/test/application/rake/migrations_test.rb
index 6b74707959..580ed269cb 100644
--- a/railties/test/application/rake/migrations_test.rb
+++ b/railties/test/application/rake/migrations_test.rb
@@ -18,7 +18,7 @@ module ApplicationTests
`bin/rails generate model user username:string password:string`
app_file "db/migrate/01_a_migration.bukkits.rb", <<-MIGRATION
- class AMigration < ActiveRecord::Migration
+ class AMigration < ActiveRecord::Migration::Current
end
MIGRATION
@@ -158,12 +158,12 @@ module ApplicationTests
Dir.chdir(app_path) do
app_file "db/migrate/1_one_migration.rb", <<-MIGRATION
- class OneMigration < ActiveRecord::Migration
+ class OneMigration < ActiveRecord::Migration::Current
end
MIGRATION
app_file "db/migrate/02_two_migration.rb", <<-MIGRATION
- class TwoMigration < ActiveRecord::Migration
+ class TwoMigration < ActiveRecord::Migration::Current
end
MIGRATION
diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb
index 0da0928b48..c8fb9fbc67 100644
--- a/railties/test/application/rake_test.rb
+++ b/railties/test/application/rake_test.rb
@@ -98,7 +98,7 @@ module ApplicationTests
end
def test_code_statistics_sanity
- assert_match "Code LOC: 7 Test LOC: 0 Code to Test Ratio: 1:0.0",
+ assert_match "Code LOC: 14 Test LOC: 0 Code to Test Ratio: 1:0.0",
Dir.chdir(app_path){ `bin/rake stats` }
end
@@ -186,7 +186,7 @@ module ApplicationTests
def test_scaffold_tests_pass_by_default
output = Dir.chdir(app_path) do
`bin/rails generate scaffold user username:string password:string;
- bin/rake db:migrate test`
+ RAILS_ENV=test bin/rake db:migrate test`
end
assert_match(/7 runs, 12 assertions, 0 failures, 0 errors/, output)
@@ -205,7 +205,7 @@ module ApplicationTests
output = Dir.chdir(app_path) do
`bin/rails generate scaffold user username:string password:string;
- bin/rake db:migrate test`
+ RAILS_ENV=test bin/rake db:migrate test`
end
assert_match(/5 runs, 7 assertions, 0 failures, 0 errors/, output)
@@ -218,7 +218,7 @@ module ApplicationTests
output = Dir.chdir(app_path) do
`bin/rails generate scaffold LineItems product:references cart:belongs_to;
- bin/rake db:migrate test`
+ RAILS_ENV=test bin/rake db:migrate test`
end
assert_match(/7 runs, 12 assertions, 0 failures, 0 errors/, output)
diff --git a/railties/test/commands/dbconsole_test.rb b/railties/test/commands/dbconsole_test.rb
index 7950ed6aa7..a5aa6c14a2 100644
--- a/railties/test/commands/dbconsole_test.rb
+++ b/railties/test/commands/dbconsole_test.rb
@@ -113,19 +113,19 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase
end
def test_mysql
- start(adapter: 'mysql', database: 'db')
+ start(adapter: 'mysql2', database: 'db')
assert !aborted
assert_equal [%w[mysql mysql5], 'db'], dbconsole.find_cmd_and_exec_args
end
def test_mysql_full
- start(adapter: 'mysql', database: 'db', host: 'locahost', port: 1234, socket: 'socket', username: 'user', password: 'qwerty', encoding: 'UTF-8')
+ start(adapter: 'mysql2', database: 'db', host: 'locahost', port: 1234, socket: 'socket', username: 'user', password: 'qwerty', encoding: 'UTF-8')
assert !aborted
assert_equal [%w[mysql mysql5], '--host=locahost', '--port=1234', '--socket=socket', '--user=user', '--default-character-set=UTF-8', '-p', 'db'], dbconsole.find_cmd_and_exec_args
end
def test_mysql_include_password
- start({adapter: 'mysql', database: 'db', username: 'user', password: 'qwerty'}, ['-p'])
+ start({adapter: 'mysql2', database: 'db', username: 'user', password: 'qwerty'}, ['-p'])
assert !aborted
assert_equal [%w[mysql mysql5], '--user=user', '--password=qwerty', 'db'], dbconsole.find_cmd_and_exec_args
end
diff --git a/railties/test/commands/dev_cache_test.rb b/railties/test/commands/dev_cache_test.rb
new file mode 100644
index 0000000000..1b7a72e7fc
--- /dev/null
+++ b/railties/test/commands/dev_cache_test.rb
@@ -0,0 +1,32 @@
+require_relative '../isolation/abstract_unit'
+
+module CommandsTests
+ class DevCacheTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ test 'dev:cache creates file and outputs message' do
+ Dir.chdir(app_path) do
+ output = `rails dev:cache`
+ assert File.exist?('tmp/caching-dev.txt')
+ assert_match(%r{Development mode is now being cached}, output)
+ end
+ end
+
+ test 'dev:cache deletes file and outputs message' do
+ Dir.chdir(app_path) do
+ `rails dev:cache` # Create caching file.
+ output = `rails dev:cache` # Delete caching file.
+ assert_not File.exist?('tmp/caching-dev.txt')
+ assert_match(%r{Development mode is no longer being cached}, output)
+ end
+ end
+ end
+end
diff --git a/railties/test/generators/actions_test.rb b/railties/test/generators/actions_test.rb
index b4fbea4af4..2f42ce894b 100644
--- a/railties/test/generators/actions_test.rb
+++ b/railties/test/generators/actions_test.rb
@@ -261,7 +261,14 @@ class ActionsTest < Rails::Generators::TestCase
content.gsub!(/^\n/, '')
File.open(route_path, "wb") { |file| file.write(content) }
- assert_file "config/routes.rb", /\.routes\.draw do\n root 'welcome#index'\nend\n\z/
+
+ routes = <<-F
+Rails.application.routes.draw do
+ root 'welcome#index'
+end
+F
+
+ assert_file "config/routes.rb", routes
action :route, "resources :product_lines"
diff --git a/railties/test/generators/api_app_generator_test.rb b/railties/test/generators/api_app_generator_test.rb
index 998da3ef84..2c24a6e46a 100644
--- a/railties/test/generators/api_app_generator_test.rb
+++ b/railties/test/generators/api_app_generator_test.rb
@@ -37,9 +37,8 @@ class ApiAppGeneratorTest < Rails::Generators::TestCase
assert_no_match(/gem 'coffee-rails'/, content)
assert_no_match(/gem 'jquery-rails'/, content)
assert_no_match(/gem 'sass-rails'/, content)
- assert_no_match(/gem 'jbuilder'/, content)
assert_no_match(/gem 'web-console'/, content)
- assert_match(/gem 'active_model_serializers'/, content)
+ assert_match(/# gem 'jbuilder'/, content)
end
assert_file "config/application.rb" do |content|
@@ -89,6 +88,7 @@ class ApiAppGeneratorTest < Rails::Generators::TestCase
config/initializers/assets.rb
config/initializers/cookies_serializer.rb
config/initializers/session_store.rb
+ config/initializers/request_forgery_protection.rb
lib/assets
vendor/assets
test/helpers
diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb
index 446fef562b..ddbcd4c394 100644
--- a/railties/test/generators/app_generator_test.rb
+++ b/railties/test/generators/app_generator_test.rb
@@ -334,6 +334,7 @@ class AppGeneratorTest < Rails::Generators::TestCase
run_generator [destination_root, "--skip-active-record"]
assert_no_file "config/database.yml"
assert_no_file "config/initializers/active_record_belongs_to_required_by_default.rb"
+ assert_no_file "app/models/application_record.rb"
assert_file "config/application.rb", /#\s+require\s+["']active_record\/railtie["']/
assert_file "test/test_helper.rb" do |helper_content|
assert_no_match(/fixtures :all/, helper_content)
@@ -375,6 +376,11 @@ class AppGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_generator_if_skip_action_cable_is_given
+ run_generator [destination_root, "--skip-action-cable"]
+ assert_file "config/application.rb", /#\s+require\s+["']action_cable\/engine["']/
+ end
+
def test_inclusion_of_javascript_runtime
run_generator
if defined?(JRUBY_VERSION)
@@ -505,7 +511,7 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file "Gemfile" do |content|
assert_match(/gem 'web-console',\s+github: 'rails\/web-console'/, content)
- assert_no_match(/gem 'web-console', '~> 2.0'/, content)
+ assert_no_match(/gem 'web-console', '~> 3.0'/, content)
end
end
@@ -514,7 +520,7 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file "Gemfile" do |content|
assert_match(/gem 'web-console',\s+github: 'rails\/web-console'/, content)
- assert_no_match(/gem 'web-console', '~> 2.0'/, content)
+ assert_no_match(/gem 'web-console', '~> 3.0'/, content)
end
end
@@ -611,8 +617,6 @@ class AppGeneratorTest < Rails::Generators::TestCase
run_generator
folders_with_keep = %w(
app/assets/images
- app/mailers
- app/models
app/controllers/concerns
app/models/concerns
lib/tasks
diff --git a/railties/test/generators/generator_test.rb b/railties/test/generators/generator_test.rb
index 7871399dd7..8ef44a8dcb 100644
--- a/railties/test/generators/generator_test.rb
+++ b/railties/test/generators/generator_test.rb
@@ -80,6 +80,21 @@ module Rails
}
assert_equal gems.drop(2), generator.gemfile_entries
end
+
+ def test_recommended_rails_versions
+ klass = make_builder_class
+ generator = klass.start(['new', 'blah'])
+
+ specifier_for = -> v { generator.send(:rails_version_specifier, Gem::Version.new(v)) }
+
+ assert_equal '~> 4.1.13', specifier_for['4.1.13']
+ assert_equal ['>= 4.1.6.rc1', '< 4.2'], specifier_for['4.1.6.rc1']
+ assert_equal ['~> 4.1.7', '>= 4.1.7.1'], specifier_for['4.1.7.1']
+ assert_equal ['~> 4.1.7', '>= 4.1.7.1.2'], specifier_for['4.1.7.1.2']
+ assert_equal ['>= 4.1.7.1.rc2', '< 4.2'], specifier_for['4.1.7.1.rc2']
+ assert_equal ['>= 4.2.0.beta1', '< 4.3'], specifier_for['4.2.0.beta1']
+ assert_equal ['>= 5.0.0.beta1', '< 5.1'], specifier_for['5.0.0.beta1']
+ end
end
end
end
diff --git a/railties/test/generators/mailer_generator_test.rb b/railties/test/generators/mailer_generator_test.rb
index f01e8cd2d9..f8d9ccacb4 100644
--- a/railties/test/generators/mailer_generator_test.rb
+++ b/railties/test/generators/mailer_generator_test.rb
@@ -14,15 +14,6 @@ class MailerGeneratorTest < Rails::Generators::TestCase
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
-
def test_mailer_with_i18n_helper
run_generator
assert_file "app/mailers/notifier_mailer.rb" do |mailer|
@@ -87,10 +78,6 @@ class MailerGeneratorTest < Rails::Generators::TestCase
assert_match(%r(\sapp/views/notifier_mailer/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
@@ -104,17 +91,11 @@ class MailerGeneratorTest < Rails::Generators::TestCase
assert_match(%r(\sapp/views/notifier_mailer/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_mailer"
- 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
@@ -162,10 +143,6 @@ class MailerGeneratorTest < Rails::Generators::TestCase
assert_no_file "app/views/notifier/bar.text.erb"
assert_no_file "app/views/notifier/foo.html.erb"
assert_no_file "app/views/notifier/bar.html.erb"
-
- assert_file "app/mailers/application_mailer.rb"
- assert_file "app/views/layouts/mailer.text.erb"
- assert_file "app/views/layouts/mailer.html.erb"
end
def test_mailer_suffix_is_not_duplicated
diff --git a/railties/test/generators/migration_generator_test.rb b/railties/test/generators/migration_generator_test.rb
index 199743a396..80f284674d 100644
--- a/railties/test/generators/migration_generator_test.rb
+++ b/railties/test/generators/migration_generator_test.rb
@@ -7,7 +7,7 @@ class MigrationGeneratorTest < Rails::Generators::TestCase
def test_migration
migration = "change_title_body_from_posts"
run_generator [migration]
- assert_migration "db/migrate/#{migration}.rb", /class ChangeTitleBodyFromPosts < ActiveRecord::Migration/
+ assert_migration "db/migrate/#{migration}.rb", /class ChangeTitleBodyFromPosts < ActiveRecord::Migration\[[0-9.]+\]/
end
def test_migrations_generated_simultaneously
@@ -26,7 +26,7 @@ class MigrationGeneratorTest < Rails::Generators::TestCase
def test_migration_with_class_name
migration = "ChangeTitleBodyFromPosts"
run_generator [migration]
- assert_migration "db/migrate/change_title_body_from_posts.rb", /class #{migration} < ActiveRecord::Migration/
+ assert_migration "db/migrate/change_title_body_from_posts.rb", /class #{migration} < ActiveRecord::Migration\[[0-9.]+\]/
end
def test_migration_with_invalid_file_name
diff --git a/railties/test/generators/model_generator_test.rb b/railties/test/generators/model_generator_test.rb
index 64b9a480f3..fb502ec0c5 100644
--- a/railties/test/generators/model_generator_test.rb
+++ b/railties/test/generators/model_generator_test.rb
@@ -35,6 +35,17 @@ class ModelGeneratorTest < Rails::Generators::TestCase
assert_no_migration "db/migrate/create_accounts.rb"
end
+ def test_model_with_existent_application_record
+ mkdir_p "#{destination_root}/app/models"
+ touch "#{destination_root}/app/models/application_record.rb"
+
+ Dir.chdir(destination_root) do
+ run_generator ["account"]
+ end
+
+ assert_file "app/models/account.rb", /class Account < ApplicationRecord/
+ end
+
def test_plural_names_are_singularized
content = run_generator ["accounts".freeze]
assert_file "app/models/account.rb", /class Account < ActiveRecord::Base/
@@ -57,12 +68,12 @@ class ModelGeneratorTest < Rails::Generators::TestCase
def test_migration
run_generator
- assert_migration "db/migrate/create_accounts.rb", /class CreateAccounts < ActiveRecord::Migration/
+ assert_migration "db/migrate/create_accounts.rb", /class CreateAccounts < ActiveRecord::Migration\[[0-9.]+\]/
end
def test_migration_with_namespace
run_generator ["Gallery::Image"]
- assert_migration "db/migrate/create_gallery_images", /class CreateGalleryImages < ActiveRecord::Migration/
+ assert_migration "db/migrate/create_gallery_images", /class CreateGalleryImages < ActiveRecord::Migration\[[0-9.]+\]/
assert_no_migration "db/migrate/create_images"
end
@@ -70,7 +81,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase
run_generator ["Admin::Gallery::Image"]
assert_no_migration "db/migrate/create_images"
assert_no_migration "db/migrate/create_gallery_images"
- assert_migration "db/migrate/create_admin_gallery_images", /class CreateAdminGalleryImages < ActiveRecord::Migration/
+ assert_migration "db/migrate/create_admin_gallery_images", /class CreateAdminGalleryImages < ActiveRecord::Migration\[[0-9.]+\]/
assert_migration "db/migrate/create_admin_gallery_images", /create_table :admin_gallery_images/
end
@@ -80,7 +91,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase
assert_no_migration "db/migrate/create_images"
assert_no_migration "db/migrate/create_gallery_images"
assert_no_migration "db/migrate/create_admin_gallery_images"
- assert_migration "db/migrate/create_admin_gallery_image", /class CreateAdminGalleryImage < ActiveRecord::Migration/
+ assert_migration "db/migrate/create_admin_gallery_image", /class CreateAdminGalleryImage < ActiveRecord::Migration\[[0-9.]+\]/
assert_migration "db/migrate/create_admin_gallery_image", /create_table :admin_gallery_image/
ensure
ActiveRecord::Base.pluralize_table_names = true
@@ -89,7 +100,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase
def test_migration_with_namespaces_in_model_name_without_plurization
ActiveRecord::Base.pluralize_table_names = false
run_generator ["Gallery::Image"]
- assert_migration "db/migrate/create_gallery_image", /class CreateGalleryImage < ActiveRecord::Migration/
+ assert_migration "db/migrate/create_gallery_image", /class CreateGalleryImage < ActiveRecord::Migration\[[0-9.]+\]/
assert_no_migration "db/migrate/create_gallery_images"
ensure
ActiveRecord::Base.pluralize_table_names = true
@@ -98,7 +109,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase
def test_migration_without_pluralization
ActiveRecord::Base.pluralize_table_names = false
run_generator
- assert_migration "db/migrate/create_account", /class CreateAccount < ActiveRecord::Migration/
+ assert_migration "db/migrate/create_account", /class CreateAccount < ActiveRecord::Migration\[[0-9.]+\]/
assert_no_migration "db/migrate/create_accounts"
ensure
ActiveRecord::Base.pluralize_table_names = true
@@ -193,10 +204,10 @@ class ModelGeneratorTest < Rails::Generators::TestCase
def test_migration_without_timestamps
ActiveRecord::Base.timestamped_migrations = false
run_generator ["account"]
- assert_file "db/migrate/001_create_accounts.rb", /class CreateAccounts < ActiveRecord::Migration/
+ assert_file "db/migrate/001_create_accounts.rb", /class CreateAccounts < ActiveRecord::Migration\[[0-9.]+\]/
run_generator ["project"]
- assert_file "db/migrate/002_create_projects.rb", /class CreateProjects < ActiveRecord::Migration/
+ assert_file "db/migrate/002_create_projects.rb", /class CreateProjects < ActiveRecord::Migration\[[0-9.]+\]/
ensure
ActiveRecord::Base.timestamped_migrations = true
end
diff --git a/railties/test/generators/namespaced_generators_test.rb b/railties/test/generators/namespaced_generators_test.rb
index 590f06e19a..d76759a7d1 100644
--- a/railties/test/generators/namespaced_generators_test.rb
+++ b/railties/test/generators/namespaced_generators_test.rb
@@ -104,12 +104,12 @@ class NamespacedModelGeneratorTest < NamespacedGeneratorTestCase
def test_migration
run_generator
- assert_migration "db/migrate/create_test_app_accounts.rb", /create_table :test_app_accounts/, /class CreateTestAppAccounts < ActiveRecord::Migration/
+ assert_migration "db/migrate/create_test_app_accounts.rb", /create_table :test_app_accounts/, /class CreateTestAppAccounts < ActiveRecord::Migration\[[0-9.]+\]/
end
def test_migration_with_namespace
run_generator ["Gallery::Image"]
- assert_migration "db/migrate/create_test_app_gallery_images", /class CreateTestAppGalleryImages < ActiveRecord::Migration/
+ assert_migration "db/migrate/create_test_app_gallery_images", /class CreateTestAppGalleryImages < ActiveRecord::Migration\[[0-9.]+\]/
assert_no_migration "db/migrate/create_test_app_images"
end
@@ -117,7 +117,7 @@ class NamespacedModelGeneratorTest < NamespacedGeneratorTestCase
run_generator ["Admin::Gallery::Image"]
assert_no_migration "db/migrate/create_images"
assert_no_migration "db/migrate/create_gallery_images"
- assert_migration "db/migrate/create_test_app_admin_gallery_images", /class CreateTestAppAdminGalleryImages < ActiveRecord::Migration/
+ assert_migration "db/migrate/create_test_app_admin_gallery_images", /class CreateTestAppAdminGalleryImages < ActiveRecord::Migration\[[0-9.]+\]/
assert_migration "db/migrate/create_test_app_admin_gallery_images", /create_table :test_app_admin_gallery_images/
end
@@ -127,7 +127,7 @@ class NamespacedModelGeneratorTest < NamespacedGeneratorTestCase
assert_no_migration "db/migrate/create_images"
assert_no_migration "db/migrate/create_gallery_images"
assert_no_migration "db/migrate/create_test_app_admin_gallery_images"
- assert_migration "db/migrate/create_test_app_admin_gallery_image", /class CreateTestAppAdminGalleryImage < ActiveRecord::Migration/
+ assert_migration "db/migrate/create_test_app_admin_gallery_image", /class CreateTestAppAdminGalleryImage < ActiveRecord::Migration\[[0-9.]+\]/
assert_migration "db/migrate/create_test_app_admin_gallery_image", /create_table :test_app_admin_gallery_image/
ensure
ActiveRecord::Base.pluralize_table_names = true
@@ -218,7 +218,7 @@ class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase
/class ProductLinesController < ApplicationController/
assert_file "test/controllers/test_app/product_lines_controller_test.rb",
- /module TestApp\n class ProductLinesControllerTest < ActionController::TestCase/
+ /module TestApp\n class ProductLinesControllerTest < ActionDispatch::IntegrationTest/
# Views
%w(index edit new show _form).each do |view|
@@ -285,7 +285,7 @@ class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase
end
assert_file "test/controllers/test_app/admin/roles_controller_test.rb",
- /module TestApp\n class Admin::RolesControllerTest < ActionController::TestCase/
+ /module TestApp\n class Admin::RolesControllerTest < ActionDispatch::IntegrationTest/
# Views
%w(index edit new show _form).each do |view|
@@ -352,7 +352,7 @@ class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase
end
assert_file "test/controllers/test_app/admin/user/special/roles_controller_test.rb",
- /module TestApp\n class Admin::User::Special::RolesControllerTest < ActionController::TestCase/
+ /module TestApp\n class Admin::User::Special::RolesControllerTest < ActionDispatch::IntegrationTest/
# Views
%w(index edit new show _form).each do |view|
@@ -418,6 +418,6 @@ class NamespacedScaffoldGeneratorTest < NamespacedGeneratorTestCase
assert_match(%r(require_dependency "test_app/application_controller"), content)
end
assert_file "test/controllers/test_app/admin/roles_controller_test.rb",
- /module TestApp\n class Admin::RolesControllerTest < ActionController::TestCase/
+ /module TestApp\n class Admin::RolesControllerTest < ActionDispatch::IntegrationTest/
end
end
diff --git a/railties/test/generators/plugin_generator_test.rb b/railties/test/generators/plugin_generator_test.rb
index 715debf344..85a752455c 100644
--- a/railties/test/generators/plugin_generator_test.rb
+++ b/railties/test/generators/plugin_generator_test.rb
@@ -6,7 +6,7 @@ DEFAULT_PLUGIN_FILES = %w(
.gitignore
Gemfile
Rakefile
- README.rdoc
+ README.md
bukkits.gemspec
MIT-LICENSE
lib
@@ -58,15 +58,18 @@ class PluginGeneratorTest < Rails::Generators::TestCase
def test_generating_without_options
run_generator
- assert_file "README.rdoc", /Bukkits/
+ assert_file "README.md", /Bukkits/
assert_no_file "config/routes.rb"
assert_no_file "app/assets/config/bukkits_manifest.js"
assert_file "test/test_helper.rb" do |content|
assert_match(/require.+test\/dummy\/config\/environment/, content)
assert_match(/ActiveRecord::Migrator\.migrations_paths.+test\/dummy\/db\/migrate/, content)
assert_match(/Minitest\.backtrace_filter = Minitest::BacktraceFilter\.new/, content)
+ assert_match(/Rails::TestUnitReporter\.executable = 'bin\/test'/, content)
end
assert_file "test/bukkits_test.rb", /assert_kind_of Module, Bukkits/
+ assert_file 'bin/test'
+ assert_no_file 'bin/rails'
end
def test_generating_test_files_in_full_mode
@@ -223,7 +226,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase
run_generator
FileUtils.cd destination_root
quietly { system 'bundle install' }
- assert_match(/1 runs, 1 assertions, 0 failures, 0 errors/, `bundle exec rake test 2>&1`)
+ assert_match(/1 runs, 1 assertions, 0 failures, 0 errors/, `bin/test 2>&1`)
end
def test_ensure_that_tests_works_in_full_mode
@@ -315,7 +318,9 @@ class PluginGeneratorTest < Rails::Generators::TestCase
assert_match(/ActiveRecord::Migrator\.migrations_paths.+\.\.\/test\/dummy\/db\/migrate/, content)
assert_match(/ActiveRecord::Migrator\.migrations_paths.+<<.+\.\.\/db\/migrate/, content)
assert_match(/ActionDispatch::IntegrationTest\.fixture_path = ActiveSupport::TestCase\.fixture_pat/, content)
+ assert_no_match(/Rails::TestUnitReporter\.executable = 'bin\/test'/, content)
end
+ assert_no_file 'bin/test'
end
def test_create_mountable_application_with_mountable_option_and_hypenated_name
@@ -381,8 +386,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase
def test_creating_gemspec
run_generator
assert_file "bukkits.gemspec", /s.name\s+= "bukkits"/
- assert_file "bukkits.gemspec", /s.files = Dir\["\{app,config,db,lib\}\/\*\*\/\*", "MIT-LICENSE", "Rakefile", "README\.rdoc"\]/
- assert_file "bukkits.gemspec", /s.test_files = Dir\["test\/\*\*\/\*"\]/
+ assert_file "bukkits.gemspec", /s.files = Dir\["\{app,config,db,lib\}\/\*\*\/\*", "MIT-LICENSE", "Rakefile", "README\.md"\]/
assert_file "bukkits.gemspec", /s.version\s+ = Bukkits::VERSION/
end
@@ -456,9 +460,6 @@ class PluginGeneratorTest < Rails::Generators::TestCase
def test_skipping_test_files
run_generator [destination_root, "--skip-test"]
assert_no_file "test"
- assert_file "bukkits.gemspec" do |contents|
- assert_no_match(/s.test_files = Dir\["test\/\*\*\/\*"\]/, contents)
- end
assert_file '.gitignore' do |contents|
assert_no_match(/test\dummy/, contents)
end
@@ -469,7 +470,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase
assert_no_file "bukkits.gemspec"
assert_file "Gemfile" do |contents|
assert_no_match('gemspec', contents)
- assert_match(/gem 'rails', '~> #{Rails.version}'/, contents)
+ assert_match(/gem 'rails'/, contents)
assert_match_sqlite3(contents)
assert_no_match(/# gem "jquery-rails"/, contents)
end
@@ -480,7 +481,7 @@ class PluginGeneratorTest < Rails::Generators::TestCase
assert_no_file "bukkits.gemspec"
assert_file "Gemfile" do |contents|
assert_no_match('gemspec', contents)
- assert_match(/gem 'rails', '~> #{Rails.version}'/, contents)
+ assert_match(/gem 'rails'/, contents)
assert_match_sqlite3(contents)
end
end
diff --git a/railties/test/generators/plugin_test_helper.rb b/railties/test/generators/plugin_test_helper.rb
new file mode 100644
index 0000000000..96c1b1d31f
--- /dev/null
+++ b/railties/test/generators/plugin_test_helper.rb
@@ -0,0 +1,24 @@
+require 'abstract_unit'
+require 'tmpdir'
+
+module PluginTestHelper
+ def create_test_file(name, pass: true)
+ plugin_file "test/#{name}_test.rb", <<-RUBY
+ require 'test_helper'
+
+ class #{name.camelize}Test < ActiveSupport::TestCase
+ def test_truth
+ puts "#{name.camelize}Test"
+ assert #{pass}, 'wups!'
+ end
+ end
+ RUBY
+ end
+
+ def plugin_file(path, contents, mode: 'w')
+ FileUtils.mkdir_p File.dirname("#{plugin_path}/#{path}")
+ File.open("#{plugin_path}/#{path}", mode) do |f|
+ f.puts contents
+ end
+ end
+end
diff --git a/railties/test/generators/plugin_test_runner_test.rb b/railties/test/generators/plugin_test_runner_test.rb
new file mode 100644
index 0000000000..716728819e
--- /dev/null
+++ b/railties/test/generators/plugin_test_runner_test.rb
@@ -0,0 +1,104 @@
+require 'generators/plugin_test_helper'
+
+class PluginTestRunnerTest < ActiveSupport::TestCase
+ include PluginTestHelper
+
+ def setup
+ @destination_root = Dir.mktmpdir('bukkits')
+ Dir.chdir(@destination_root) { `bundle exec rails plugin new bukkits --skip-bundle` }
+ plugin_file 'test/dummy/db/schema.rb', ''
+ end
+
+ def teardown
+ FileUtils.rm_rf(@destination_root)
+ end
+
+ def test_run_single_file
+ create_test_file 'foo'
+ create_test_file 'bar'
+ assert_match "1 runs, 1 assertions, 0 failures", run_test_command("test/foo_test.rb")
+ end
+
+ def test_run_multiple_files
+ create_test_file 'foo'
+ create_test_file 'bar'
+ assert_match "2 runs, 2 assertions, 0 failures", run_test_command("test/foo_test.rb test/bar_test.rb")
+ end
+
+ def test_mix_files_and_line_filters
+ create_test_file 'account'
+ plugin_file 'test/post_test.rb', <<-RUBY
+ require 'test_helper'
+
+ class PostTest < ActiveSupport::TestCase
+ def test_post
+ puts 'PostTest'
+ assert true
+ end
+
+ def test_line_filter_does_not_run_this
+ assert true
+ end
+ end
+ RUBY
+
+ run_test_command('test/account_test.rb test/post_test.rb:4').tap do |output|
+ assert_match 'AccountTest', output
+ assert_match 'PostTest', output
+ assert_match '2 runs, 2 assertions', output
+ end
+ end
+
+ def test_multiple_line_filters
+ create_test_file 'account'
+ create_test_file 'post'
+
+ run_test_command('test/account_test.rb:4 test/post_test.rb:4').tap do |output|
+ assert_match 'AccountTest', output
+ assert_match 'PostTest', output
+ end
+ end
+
+ def test_line_filter_without_line_runs_all_tests
+ create_test_file 'account'
+
+ run_test_command('test/account_test.rb:').tap do |output|
+ assert_match 'AccountTest', output
+ end
+ end
+
+ def test_output_inline_by_default
+ create_test_file 'post', pass: false
+
+ output = run_test_command('test/post_test.rb')
+ assert_match %r{Running:\n\nPostTest\nF\n\nwups!\n\nbin/test (/private)?#{plugin_path}/test/post_test.rb:6}, output
+ end
+
+ def test_only_inline_failure_output
+ create_test_file 'post', pass: false
+
+ output = run_test_command('test/post_test.rb')
+ assert_match %r{Finished in.*\n\n1 runs, 1 assertions}, output
+ end
+
+ def test_fail_fast
+ create_test_file 'post', pass: false
+
+ assert_match(/Interrupt/,
+ capture(:stderr) { run_test_command('test/post_test.rb --fail-fast') })
+ end
+
+ def test_raise_error_when_specified_file_does_not_exist
+ error = capture(:stderr) { run_test_command('test/not_exists.rb') }
+ assert_match(%r{cannot load such file.+test/not_exists\.rb}, error)
+ end
+
+ private
+ def plugin_path
+ "#{@destination_root}/bukkits"
+ end
+
+ def run_test_command(arguments)
+ Dir.chdir(plugin_path) { `bin/test #{arguments}` }
+ end
+end
diff --git a/railties/test/generators/resource_generator_test.rb b/railties/test/generators/resource_generator_test.rb
index 581d80d60e..addaf83bc8 100644
--- a/railties/test/generators/resource_generator_test.rb
+++ b/railties/test/generators/resource_generator_test.rb
@@ -33,7 +33,7 @@ class ResourceGeneratorTest < Rails::Generators::TestCase
def test_resource_controller_with_pluralized_class_name
run_generator
assert_file "app/controllers/accounts_controller.rb", /class AccountsController < ApplicationController/
- assert_file "test/controllers/accounts_controller_test.rb", /class AccountsControllerTest < ActionController::TestCase/
+ assert_file "test/controllers/accounts_controller_test.rb", /class AccountsControllerTest < ActionDispatch::IntegrationTest/
assert_file "app/helpers/accounts_helper.rb", /module AccountsHelper/
end
diff --git a/railties/test/generators/scaffold_controller_generator_test.rb b/railties/test/generators/scaffold_controller_generator_test.rb
index 95ef853a11..c37e289f4b 100644
--- a/railties/test/generators/scaffold_controller_generator_test.rb
+++ b/railties/test/generators/scaffold_controller_generator_test.rb
@@ -56,7 +56,7 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase
assert_file "app/controllers/users_controller.rb" do |content|
assert_match(/def user_params/, content)
- assert_match(/params\[:user\]/, content)
+ assert_match(/params\.fetch\(:user, \{\}\)/, content)
end
end
@@ -104,10 +104,10 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase
run_generator ["User", "name:string", "age:integer", "organization:references{polymorphic}"]
assert_file "test/controllers/users_controller_test.rb" do |content|
- assert_match(/class UsersControllerTest < ActionController::TestCase/, content)
+ assert_match(/class UsersControllerTest < ActionDispatch::IntegrationTest/, content)
assert_match(/test "should get index"/, content)
- assert_match(/post :create, params: \{ user: \{ age: @user\.age, name: @user\.name, organization_id: @user\.organization_id, organization_type: @user\.organization_type \} \}/, content)
- assert_match(/patch :update, params: \{ id: @user, user: \{ age: @user\.age, name: @user\.name, organization_id: @user\.organization_id, organization_type: @user\.organization_type \} \}/, content)
+ assert_match(/post users_url, params: \{ user: \{ age: @user\.age, name: @user\.name, organization_id: @user\.organization_id, organization_type: @user\.organization_type \} \}/, content)
+ assert_match(/patch user_url\(@user\), params: \{ user: \{ age: @user\.age, name: @user\.name, organization_id: @user\.organization_id, organization_type: @user\.organization_type \} \}/, content)
end
end
@@ -115,10 +115,10 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase
run_generator ["User"]
assert_file "test/controllers/users_controller_test.rb" do |content|
- assert_match(/class UsersControllerTest < ActionController::TestCase/, content)
+ assert_match(/class UsersControllerTest < ActionDispatch::IntegrationTest/, content)
assert_match(/test "should get index"/, content)
- assert_match(/post :create, params: \{ user: \{ \} \}/, content)
- assert_match(/patch :update, params: \{ id: @user, user: \{ \} \}/, content)
+ assert_match(/post users_url, params: \{ user: \{ \} \}/, content)
+ assert_match(/patch user_url\(@user\), params: \{ user: \{ \} \}/, content)
end
end
@@ -236,10 +236,10 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase
run_generator ["User", "name:string", "age:integer", "organization:references{polymorphic}", "--api"]
assert_file "test/controllers/users_controller_test.rb" do |content|
- assert_match(/class UsersControllerTest < ActionController::TestCase/, content)
+ assert_match(/class UsersControllerTest < ActionDispatch::IntegrationTest/, content)
assert_match(/test "should get index"/, content)
- assert_match(/post :create, params: \{ user: \{ age: @user\.age, name: @user\.name, organization_id: @user\.organization_id, organization_type: @user\.organization_type \} \}/, content)
- assert_match(/patch :update, params: \{ id: @user, user: \{ age: @user\.age, name: @user\.name, organization_id: @user\.organization_id, organization_type: @user\.organization_type \} \}/, content)
+ assert_match(/post users_url, params: \{ user: \{ age: @user\.age, name: @user\.name, organization_id: @user\.organization_id, organization_type: @user\.organization_type \} \}/, content)
+ assert_match(/patch user_url\(@user\), params: \{ user: \{ age: @user\.age, name: @user\.name, organization_id: @user\.organization_id, organization_type: @user\.organization_type \} \}/, content)
assert_no_match(/assert_redirected_to/, content)
end
end
diff --git a/railties/test/generators/scaffold_generator_test.rb b/railties/test/generators/scaffold_generator_test.rb
index 0c3808a9a0..eb81ea3d0e 100644
--- a/railties/test/generators/scaffold_generator_test.rb
+++ b/railties/test/generators/scaffold_generator_test.rb
@@ -57,9 +57,9 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
end
assert_file "test/controllers/product_lines_controller_test.rb" do |test|
- assert_match(/class ProductLinesControllerTest < ActionController::TestCase/, test)
- assert_match(/post :create, params: \{ product_line: \{ product_id: @product_line\.product_id, title: @product_line\.title, user_id: @product_line\.user_id \} \}/, test)
- assert_match(/patch :update, params: \{ id: @product_line, product_line: \{ product_id: @product_line\.product_id, title: @product_line\.title, user_id: @product_line\.user_id \} \}/, test)
+ assert_match(/class ProductLinesControllerTest < ActionDispatch::IntegrationTest/, test)
+ assert_match(/post product_lines_url, params: \{ product_line: \{ product_id: @product_line\.product_id, title: @product_line\.title, user_id: @product_line\.user_id \} \}/, test)
+ assert_match(/patch product_line_url\(@product_line\), params: \{ product_line: \{ product_id: @product_line\.product_id, title: @product_line\.title, user_id: @product_line\.user_id \} \}/, test)
end
# Views
@@ -135,9 +135,9 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
end
assert_file "test/controllers/product_lines_controller_test.rb" do |test|
- assert_match(/class ProductLinesControllerTest < ActionController::TestCase/, test)
- assert_match(/post :create, params: \{ product_line: \{ product_id: @product_line\.product_id, title: @product_line\.title, user_id: @product_line\.user_id \} \}/, test)
- assert_match(/patch :update, params: \{ id: @product_line, product_line: \{ product_id: @product_line\.product_id, title: @product_line\.title, user_id: @product_line\.user_id \} \}/, test)
+ assert_match(/class ProductLinesControllerTest < ActionDispatch::IntegrationTest/, test)
+ assert_match(/post product_lines_url, params: \{ product_line: \{ product_id: @product_line\.product_id, title: @product_line\.title, user_id: @product_line\.user_id \} \}/, test)
+ assert_match(/patch product_line_url\(@product_line\), params: \{ product_line: \{ product_id: @product_line\.product_id, title: @product_line\.title, user_id: @product_line\.user_id \} \}/, test)
assert_no_match(/assert_redirected_to/, test)
end
@@ -161,10 +161,10 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
run_generator ["product_line"]
assert_file "test/controllers/product_lines_controller_test.rb" do |content|
- assert_match(/class ProductLinesControllerTest < ActionController::TestCase/, content)
+ assert_match(/class ProductLinesControllerTest < ActionDispatch::IntegrationTest/, content)
assert_match(/test "should get index"/, content)
- assert_match(/post :create, params: \{ product_line: \{ \} \}/, content)
- assert_match(/patch :update, params: \{ id: @product_line, product_line: \{ \} \}/, content)
+ assert_match(/post product_lines_url, params: \{ product_line: \{ \} \}/, content)
+ assert_match(/patch product_line_url\(@product_line\), params: \{ product_line: \{ \} \}/, content)
end
end
@@ -250,7 +250,7 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
end
assert_file "test/controllers/admin/roles_controller_test.rb",
- /class Admin::RolesControllerTest < ActionController::TestCase/
+ /class Admin::RolesControllerTest < ActionDispatch::IntegrationTest/
# Views
%w(index edit new show _form).each do |view|
diff --git a/railties/test/generators/shared_generator_tests.rb b/railties/test/generators/shared_generator_tests.rb
index acb78ec888..e83d54890a 100644
--- a/railties/test/generators/shared_generator_tests.rb
+++ b/railties/test/generators/shared_generator_tests.rb
@@ -144,7 +144,6 @@ module SharedGeneratorTests
def test_skip_git
run_generator [destination_root, '--skip-git', '--full']
assert_no_file('.gitignore')
- assert_file('app/mailers/.keep')
end
def test_skip_keeps
@@ -154,6 +153,6 @@ module SharedGeneratorTests
assert_no_match(/\.keep/, content)
end
- assert_no_file('app/mailers/.keep')
+ assert_no_file('app/models/concerns/.keep')
end
end
diff --git a/railties/test/generators/test_runner_in_engine_test.rb b/railties/test/generators/test_runner_in_engine_test.rb
new file mode 100644
index 0000000000..641c5d0835
--- /dev/null
+++ b/railties/test/generators/test_runner_in_engine_test.rb
@@ -0,0 +1,31 @@
+require 'generators/plugin_test_helper'
+
+class TestRunnerInEngineTest < ActiveSupport::TestCase
+ include PluginTestHelper
+
+ def setup
+ @destination_root = Dir.mktmpdir('bukkits')
+ Dir.chdir(@destination_root) { `bundle exec rails plugin new bukkits --full --skip-bundle` }
+ plugin_file 'test/dummy/db/schema.rb', ''
+ end
+
+ def teardown
+ FileUtils.rm_rf(@destination_root)
+ end
+
+ def test_rerun_snippet_is_relative_path
+ create_test_file 'post', pass: false
+
+ output = run_test_command('test/post_test.rb')
+ assert_match %r{Running:\n\nPostTest\nF\n\nwups!\n\nbin/rails test test/post_test.rb:6}, output
+ end
+
+ private
+ def plugin_path
+ "#{@destination_root}/bukkits"
+ end
+
+ def run_test_command(arguments)
+ Dir.chdir(plugin_path) { `bin/rails test #{arguments}` }
+ end
+end
diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb
index 24386de82a..4a47ab32b4 100644
--- a/railties/test/railties/engine_test.rb
+++ b/railties/test/railties/engine_test.rb
@@ -63,22 +63,22 @@ module RailtiesTest
test "copying migrations" do
@plugin.write "db/migrate/1_create_users.rb", <<-RUBY
- class CreateUsers < ActiveRecord::Migration
+ class CreateUsers < ActiveRecord::Migration::Current
end
RUBY
@plugin.write "db/migrate/2_add_last_name_to_users.rb", <<-RUBY
- class AddLastNameToUsers < ActiveRecord::Migration
+ class AddLastNameToUsers < ActiveRecord::Migration::Current
end
RUBY
@plugin.write "db/migrate/3_create_sessions.rb", <<-RUBY
- class CreateSessions < ActiveRecord::Migration
+ class CreateSessions < ActiveRecord::Migration::Current
end
RUBY
app_file "db/migrate/1_create_sessions.rb", <<-RUBY
- class CreateSessions < ActiveRecord::Migration
+ class CreateSessions < ActiveRecord::Migration::Current
def up
end
end
@@ -123,12 +123,12 @@ module RailtiesTest
end
@plugin.write "db/migrate/1_create_users.rb", <<-RUBY
- class CreateUsers < ActiveRecord::Migration
+ class CreateUsers < ActiveRecord::Migration::Current
end
RUBY
@blog.write "db/migrate/2_create_blogs.rb", <<-RUBY
- class CreateBlogs < ActiveRecord::Migration
+ class CreateBlogs < ActiveRecord::Migration::Current
end
RUBY
@@ -163,11 +163,11 @@ module RailtiesTest
end
@core.write "db/migrate/1_create_users.rb", <<-RUBY
- class CreateUsers < ActiveRecord::Migration; end
+ class CreateUsers < ActiveRecord::Migration::Current; end
RUBY
@api.write "db/migrate/2_create_keys.rb", <<-RUBY
- class CreateKeys < ActiveRecord::Migration; end
+ class CreateKeys < ActiveRecord::Migration::Current; end
RUBY
boot_rails
@@ -190,7 +190,7 @@ module RailtiesTest
RUBY
@plugin.write "db/migrate/0_add_first_name_to_users.rb", <<-RUBY
- class AddFirstNameToUsers < ActiveRecord::Migration
+ class AddFirstNameToUsers < ActiveRecord::Migration::Current
end
RUBY
diff --git a/tasks/release.rb b/tasks/release.rb
index 7c8b884d44..ea7f66a171 100644
--- a/tasks/release.rb
+++ b/tasks/release.rb
@@ -1,4 +1,4 @@
-FRAMEWORKS = %w( activesupport activemodel activerecord actionview actionpack activejob actionmailer railties )
+FRAMEWORKS = %w( activesupport activemodel activerecord actionview actionpack activejob actionmailer actioncable railties )
root = File.expand_path('../../', __FILE__)
version = File.read("#{root}/RAILS_VERSION").strip
@@ -57,8 +57,6 @@ directory "pkg"
sh "gem install #{gem}"
end
- task :prep_release => [:ensure_clean_state, :build]
-
task :push => :build do
sh "gem push #{gem}"
end
@@ -139,5 +137,7 @@ namespace :all do
sh "git push --tags"
end
+ task :prep_release => %w(ensure_clean_state build)
+
task :release => %w(ensure_clean_state build bundle commit tag push)
end
diff --git a/version.rb b/version.rb
index 7d74b1bfe5..92230a74e4 100644
--- a/version.rb
+++ b/version.rb
@@ -8,7 +8,7 @@ module Rails
MAJOR = 5
MINOR = 0
TINY = 0
- PRE = "alpha"
+ PRE = "beta1"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end