aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.travis.yml3
-rw-r--r--Gemfile18
-rw-r--r--Gemfile.lock106
-rw-r--r--README.md4
-rw-r--r--Rakefile6
-rw-r--r--actioncable/CHANGELOG.md3
-rw-r--r--actioncable/MIT-LICENSE20
-rw-r--r--actioncable/README.md463
-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.rb148
-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/lib/rails/generators/mailer/mailer_generator.rb3
-rw-r--r--actionpack/lib/action_controller/metal/strong_parameters.rb20
-rw-r--r--actionpack/test/controller/parameters/parameters_permit_test.rb28
-rw-r--r--actionview/test/template/asset_tag_helper_test.rb2
-rw-r--r--activejob/activejob.gemspec2
-rw-r--r--activerecord/CHANGELOG.md23
-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.rb3
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb43
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb3
-rw-r--r--activerecord/lib/active_record/connection_adapters/connection_specification.rb2
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql_adapter.rb481
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb3
-rw-r--r--activerecord/lib/active_record/migration/compatibility.rb36
-rw-r--r--activerecord/lib/active_record/model_schema.rb2
-rw-r--r--activerecord/lib/active_record/tasks/mysql_database_tasks.rb2
-rw-r--r--activerecord/lib/active_record/validations/uniqueness.rb1
-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/postgresql/active_schema_test.rb8
-rw-r--r--activerecord/test/cases/adapters/postgresql/geometric_test.rb8
-rw-r--r--activerecord/test/cases/adapters/postgresql/schema_test.rb2
-rw-r--r--activerecord/test/cases/associations/belongs_to_associations_test.rb2
-rw-r--r--activerecord/test/cases/attribute_methods_test.rb2
-rw-r--r--activerecord/test/cases/base_test.rb2
-rw-r--r--activerecord/test/cases/binary_test.rb4
-rw-r--r--activerecord/test/cases/calculations_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/defaults_test.rb13
-rw-r--r--activerecord/test/cases/helper.rb2
-rw-r--r--activerecord/test/cases/invalid_connection_test.rb2
-rw-r--r--activerecord/test/cases/invertible_migration_test.rb2
-rw-r--r--activerecord/test/cases/migration/change_schema_test.rb6
-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.rb2
-rw-r--r--activerecord/test/cases/migration/index_test.rb12
-rw-r--r--activerecord/test/cases/migration_test.rb2
-rw-r--r--activerecord/test/cases/primary_keys_test.rb6
-rw-r--r--activerecord/test/cases/schema_dumper_test.rb8
-rw-r--r--activerecord/test/cases/tasks/mysql_rake_test.rb24
-rw-r--r--activerecord/test/cases/test_case.rb6
-rw-r--r--activerecord/test/cases/view_test.rb4
-rw-r--r--activerecord/test/config.example.yml9
-rw-r--r--activesupport/CHANGELOG.md49
-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/per_thread_registry.rb3
-rw-r--r--activesupport/test/core_ext/module/attribute_accessor_per_thread_test.rb109
-rwxr-xr-xci/travis.rb2
-rw-r--r--guides/source/action_view_overview.md16
-rw-r--r--guides/source/active_support_core_extensions.md12
-rw-r--r--guides/source/association_basics.md234
-rw-r--r--guides/source/autoloading_and_reloading_constants.md8
-rw-r--r--guides/source/caching_with_rails.md6
-rw-r--r--guides/source/debugging_rails_applications.md2
-rw-r--r--guides/source/form_helpers.md8
-rw-r--r--guides/source/getting_started.md21
-rw-r--r--guides/source/i18n.md2
-rw-r--r--guides/source/nested_model_forms.md6
-rw-r--r--guides/source/routing.md6
-rw-r--r--guides/source/security.md2
-rw-r--r--guides/source/testing.md2
-rw-r--r--guides/source/upgrading_ruby_on_rails.md19
-rw-r--r--rails.gemspec1
-rw-r--r--railties/CHANGELOG.md4
-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/generators/app_base.rb7
-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/rails/app/app_generator.rb12
-rw-r--r--railties/lib/rails/generators/rails/app/templates/Gemfile6
-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.coffee7
-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/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/config.ru.tt (renamed from railties/lib/rails/generators/rails/app/templates/config.ru)6
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/application.rb1
-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/redis/cable.yml8
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/routes.rb3
-rw-r--r--railties/lib/rails/generators/rails/plugin/plugin_generator.rb2
-rw-r--r--railties/lib/rails/generators/rails/plugin/templates/%name%.gemspec2
-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/test_unit/scaffold/templates/functional_test.rb2
-rw-r--r--railties/test/application/assets_test.rb2
-rw-r--r--railties/test/application/configuration_test.rb16
-rw-r--r--railties/test/application/rake_test.rb2
-rw-r--r--railties/test/commands/dbconsole_test.rb6
-rw-r--r--railties/test/generators/actions_test.rb9
-rw-r--r--railties/test/generators/app_generator_test.rb7
-rw-r--r--railties/test/generators/mailer_generator_test.rb23
-rw-r--r--railties/test/generators/plugin_generator_test.rb6
-rw-r--r--railties/test/generators/shared_generator_tests.rb3
-rw-r--r--tasks/release.rb2
195 files changed, 4485 insertions, 2091 deletions
diff --git a/.travis.yml b/.travis.yml
index 2d8159cf0c..f1031a3750 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -16,8 +16,8 @@ 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"
@@ -28,7 +28,6 @@ rvm:
- ruby-head
matrix:
allow_failures:
- - env: "GEM=ar:mysql"
- rvm: ruby-head
fast_finish: true
notifications:
diff --git a/Gemfile b/Gemfile
index ff75cdd090..9ab6cddbeb 100644
--- a/Gemfile
+++ b/Gemfile
@@ -5,8 +5,7 @@ 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'
+# We need unreleased Rack 2.0.0.alpha
gem 'rack', github: 'rack/rack', branch: 'master'
# This needs to be with require false to ensure correct loading order, as has to
@@ -14,13 +13,8 @@ gem 'rack', github: 'rack/rack', branch: 'master'
gem 'mocha', '~> 0.14', require: false
gem 'rack-cache', '~> 1.2'
-gem 'jquery-rails', github: 'rails/jquery-rails', branch: 'master'
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-rails', '~> 3.0.0.beta3', github: 'rails/sprockets-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)
@@ -68,6 +62,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
@@ -85,7 +84,7 @@ group :test do
end
platforms :ruby, :mswin, :mswin64, :mingw, :x64_mingw do
- gem 'nokogiri', '>= 1.6.7'
+ gem 'nokogiri', '>= 1.6.7.1'
# Needed for compiling the ActionDispatch::Journey parser.
gem 'racc', '>=1.4.6', require: false
@@ -95,7 +94,6 @@ platforms :ruby, :mswin, :mswin64, :mingw, :x64_mingw 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 c39b8b049e..ad75b2c9c6 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -20,14 +20,6 @@ GIT
redis-namespace
GIT
- remote: git://github.com/mikel/mail.git
- revision: f0efbd4850d1bc06cdcba6178c282eeaba9c8c43
- branch: master
- specs:
- mail (2.6.3.edge)
- mime-types (>= 1.16, < 3)
-
-GIT
remote: git://github.com/rack/rack.git
revision: 96ae9b9fed8d6809383b6f48a5884437e76f8ca4
branch: master
@@ -36,49 +28,6 @@ GIT
json
GIT
- remote: git://github.com/rails/arel.git
- revision: 899e8428c50c586e6c8d4884b542ac9fdf01e95f
- branch: master
- specs:
- arel (7.0.0.alpha)
-
-GIT
- remote: git://github.com/rails/globalid.git
- revision: 4e74ec6bb60d735ef3c56080f9c9f1dee9cadaaf
- 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/sprockets-rails.git
- revision: 06d84e952490d7d391592124f6e3b79f9c596674
- 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/turbolinks.git
- revision: ad583843fdaa0c1f61462a346a495981ca314460
- branch: master
- specs:
- turbolinks (3.0.0)
- coffee-rails
-
-GIT
remote: git://github.com/sass/sass.git
revision: bce9509f396225d721501ea1070a6871b708abb1
branch: stable
@@ -88,6 +37,14 @@ GIT
PATH
remote: .
specs:
+ actioncable (5.0.0.alpha)
+ actionpack (= 5.0.0.alpha)
+ 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.alpha)
actionpack (= 5.0.0.alpha)
actionview (= 5.0.0.alpha)
@@ -109,14 +66,14 @@ PATH
rails-html-sanitizer (~> 1.0, >= 1.0.2)
activejob (5.0.0.alpha)
activesupport (= 5.0.0.alpha)
- globalid (>= 0.3.0)
+ globalid (>= 0.3.6)
activemodel (5.0.0.alpha)
activesupport (= 5.0.0.alpha)
builder (~> 3.1)
activerecord (5.0.0.alpha)
activemodel (= 5.0.0.alpha)
activesupport (= 5.0.0.alpha)
- arel (= 7.0.0.alpha)
+ arel (~> 7.0)
activesupport (5.0.0.alpha)
concurrent-ruby (~> 1.0)
i18n (~> 0.7)
@@ -125,6 +82,7 @@ PATH
minitest (~> 5.1)
tzinfo (~> 1.1)
rails (5.0.0.alpha)
+ actioncable (= 5.0.0.alpha)
actionmailer (= 5.0.0.alpha)
actionpack (= 5.0.0.alpha)
actionview (= 5.0.0.alpha)
@@ -146,6 +104,7 @@ GEM
remote: https://rubygems.org/
specs:
amq-protocol (2.0.0)
+ arel (7.0.0)
backburner (1.2.0)
beaneater (~> 1.0)
dante (> 0.1.5)
@@ -191,11 +150,21 @@ GEM
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)
@@ -208,6 +177,8 @@ GEM
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.99)
@@ -218,21 +189,20 @@ GEM
mono_logger (1.1.0)
multi_json (1.11.2)
mustache (1.0.2)
- mysql (2.9.1)
- mysql (2.9.1-x86-mingw32)
mysql2 (0.4.2)
mysql2 (0.4.2-x64-mingw32)
mysql2 (0.4.2-x86-mingw32)
- nokogiri (1.6.7)
+ nokogiri (1.6.7.1)
mini_portile2 (~> 2.0.0.rc2)
- nokogiri (1.6.7-x64-mingw32)
+ nokogiri (1.6.7.1-x64-mingw32)
mini_portile2 (~> 2.0.0.rc2)
- nokogiri (1.6.7-x86-mingw32)
+ 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.14)
rack-cache (1.5.1)
@@ -290,6 +260,10 @@ GEM
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)
@@ -301,6 +275,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)
@@ -313,6 +289,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
@@ -323,7 +302,6 @@ 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)
@@ -333,19 +311,16 @@ DEPENDENCIES
dalli (>= 2.2.1)
delayed_job
delayed_job_active_record
- globalid!
- jquery-rails!
json
kindlerb (= 0.1.1)
listen (~> 3.0.5)
- mail!
minitest (< 5.3.4)
mocha (~> 0.14)
- mysql (>= 2.9.0)
mysql2 (>= 0.4.0)
- nokogiri (>= 1.6.7)
+ nokogiri (>= 1.6.7.1)
pg (>= 0.18.0)
psych (~> 2.0)
+ puma
qu-rails!
qu-redis
que
@@ -363,11 +338,10 @@ DEPENDENCIES
sequel
sidekiq
sneakers
- sprockets-rails (~> 3.0.0.beta3)!
sqlite3 (~> 1.3.6)
stackprof
sucker_punch
- turbolinks!
+ turbolinks
tzinfo-data
uglifier (>= 1.3.0)
w3c_validators
diff --git a/README.md b/README.md
index fa566a9105..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.
diff --git a/Rakefile b/Rakefile
index 2ec39a1c85..c0b9128eff 100644
--- a/Rakefile
+++ b/Rakefile
@@ -10,8 +10,6 @@ task :build => "all:build"
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 +17,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 +26,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..df7937b27a
--- /dev/null
+++ b/actioncable/CHANGELOG.md
@@ -0,0 +1,3 @@
+* 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..13b79d15ca
--- /dev/null
+++ b/actioncable/README.md
@@ -0,0 +1,463 @@
+# 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/application_cable.coffee
+#= require cable
+
+@App = {}
+App.cable = Cable.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
+ :host: 10.10.3.153
+ :port: 6381
+ :timeout: 1
+development: &development
+ :url: redis://localhost:6379
+ :host: localhost
+ :port: 6379
+ :timeout: 1
+ :inline: true
+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 = Cable.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..ca2f987934
--- /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@heinemeierhansson.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..f3085840ca
--- /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 an 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..37950a67f2
--- /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 = "alpha"
+
+ 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..5f44bdd1c3
--- /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 an 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..6e0fbae387
--- /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..149821f1ea
--- /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..580338b44a
--- /dev/null
+++ b/actioncable/test/channel/base_test.rb
@@ -0,0 +1,148 @@
+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
+
+ 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 "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
+
+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/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/lib/action_controller/metal/strong_parameters.rb b/actionpack/lib/action_controller/metal/strong_parameters.rb
index 8bc3c271e2..957aa746c0 100644
--- a/actionpack/lib/action_controller/metal/strong_parameters.rb
+++ b/actionpack/lib/action_controller/metal/strong_parameters.rb
@@ -1,4 +1,5 @@
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'
@@ -175,7 +176,7 @@ module ActionController
# safe_params.to_h # => {"name"=>"Senjougahara Hitagi"}
def to_h
if permitted?
- @parameters.deep_dup
+ convert_parameters_to_hashes(@parameters)
else
slice(*self.class.always_permitted_parameters).permit!.to_h
end
@@ -185,7 +186,7 @@ module ActionController
# <tt>ActiveSupport::HashWithIndifferentAccess</tt> representation of this
# parameter.
def to_unsafe_h
- @parameters.deep_dup
+ convert_parameters_to_hashes(@parameters)
end
alias_method :to_unsafe_hash, :to_unsafe_h
@@ -594,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/test/controller/parameters/parameters_permit_test.rb b/actionpack/test/controller/parameters/parameters_permit_test.rb
index 87816515e7..f23aa599c1 100644
--- a/actionpack/test/controller/parameters/parameters_permit_test.rb
+++ b/actionpack/test/controller/parameters/parameters_permit_test.rb
@@ -297,4 +297,32 @@ class ParametersPermitTest < ActiveSupport::TestCase
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/actionview/test/template/asset_tag_helper_test.rb b/actionview/test/template/asset_tag_helper_test.rb
index fe40010528..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),
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/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md
index fdbb4b5b68..ecdb7e204a 100644
--- a/activerecord/CHANGELOG.md
+++ b/activerecord/CHANGELOG.md
@@ -5,18 +5,23 @@
*Grey Baker*
-* Introduce ApplicationRecord, an Active Record layer super type.
+* Ignore index name in `index_exists?` and `remove_index` when not passed a
+ name to check for.
- An `ApplicationRecord` let's engines have models, isolated from the main
- application. Plugin authors can use it to distribute extensions as modules
- to be included into `ApplicationRecord`, instead of monkey patches. It can
- also serve as a place for applications to customize the default
- `ActiveRecord::Base` model behaviour.
+ *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. Generators are smart enough to recognize that
- newly generated models have to inherit from `ApplicationRecord` only if
- it's present.
+ present by default.
*Genadi Samokovarov*
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 04ad45f5da..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]
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 b50d28862c..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)
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 25ba42e5c9..f8c9e13392 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
@@ -1101,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/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
deleted file mode 100644
index 76f1b91e6b..0000000000
--- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
+++ /dev/null
@@ -1,481 +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
- @connection_options = connection_options
- 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 new_column(field, default, sql_type_metadata = nil, null = true, default_function = nil, collation = nil) # :nodoc:
- field = set_field_encoding(field)
- super
- 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_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
index aa43854d01..a1ec570042 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
@@ -816,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/migration/compatibility.rb b/activerecord/lib/active_record/migration/compatibility.rb
index 4c8db8a2d5..831bfa2df3 100644
--- a/activerecord/lib/active_record/migration/compatibility.rb
+++ b/activerecord/lib/active_record/migration/compatibility.rb
@@ -28,6 +28,42 @@ module ActiveRecord
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
diff --git a/activerecord/lib/active_record/model_schema.rb b/activerecord/lib/active_record/model_schema.rb
index 5df67cdbe7..a6a68f3d4b 100644
--- a/activerecord/lib/active_record/model_schema.rb
+++ b/activerecord/lib/active_record/model_schema.rb
@@ -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/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/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/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 8a7a0bb25d..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 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
-
- 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).data_source_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).data_source_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(:data_source_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 390dd15b92..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
- lock_name = "test_lock_name"
-
- 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(lock_name), false,
- "expected the test advisory lock to be held but it wasn't"
-
- 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(lock_name), 'expected the test lock to be available after releasing'
- end
-
- def test_release_non_existent_advisory_lock
- 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(lock_name)
- @connection.select_value("SELECT IS_FREE_LOCK('#{lock_name}');") == '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/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/geometric_test.rb b/activerecord/test/cases/adapters/postgresql/geometric_test.rb
index 3b97cb4ad4..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
diff --git a/activerecord/test/cases/adapters/postgresql/schema_test.rb b/activerecord/test/cases/adapters/postgresql/schema_test.rb
index 3d55435b6a..542a68519c 100644
--- a/activerecord/test/cases/adapters/postgresql/schema_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/schema_test.rb
@@ -328,8 +328,6 @@ class SchemaTest < ActiveRecord::PostgreSQLTestCase
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"}
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/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 d4d08049c8..e628254b44 100644
--- a/activerecord/test/cases/base_test.rb
+++ b/activerecord/test/cases/base_test.rb
@@ -444,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
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/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/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/helper.rb b/activerecord/test/cases/helper.rb
index 07dbc8a53f..95f8706d73 100644
--- a/activerecord/test/cases/helper.rb
+++ b/activerecord/test/cases/helper.rb
@@ -51,7 +51,7 @@ def subsecond_precision_supported?
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/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 0e5df6bd5b..e030f6c588 100644
--- a/activerecord/test/cases/invertible_migration_test.rb
+++ b/activerecord/test/cases/invertible_migration_test.rb
@@ -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/migration/change_schema_test.rb b/activerecord/test/cases/migration/change_schema_test.rb
index 86e691e564..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
@@ -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 4e1fbfb690..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
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_test.rb b/activerecord/test/cases/migration_test.rb
index b6813891c6..b5b241ad1a 100644
--- a/activerecord/test/cases/migration_test.rb
+++ b/activerecord/test/cases/migration_test.rb
@@ -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
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/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb
index 9a5e4313d8..f98c9946e4 100644
--- a/activerecord/test/cases/schema_dumper_test.rb
+++ b/activerecord/test/cases/schema_dumper_test.rb
@@ -117,7 +117,7 @@ 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)
+ elsif current_adapter?(:Mysql2Adapter)
assert_match %r{c_int_without_limit.*limit: 4}, output
assert_match %r{c_int_1.*limit: 1}, 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
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/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/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/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md
index 07f7fae5d5..70d671cd2d 100644
--- a/activesupport/CHANGELOG.md
+++ b/activesupport/CHANGELOG.md
@@ -1,3 +1,52 @@
+* 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.
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..e02e965d75
--- /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.thread_variable_set("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.thread_variable_get "attr_#{name}_#{sym}"
+ end
+ EOS
+
+ unless options[:instance_reader] == false || options[:instance_accessor] == false
+ class_eval(<<-EOS, __FILE__, __LINE__ + 1)
+ def #{sym}
+ Thread.current.thread_variable_get "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.thread_variable_get("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.thread_variable_set "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.thread_variable_set "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/per_thread_registry.rb b/activesupport/lib/active_support/per_thread_registry.rb
index a909a65bb6..88e2b12cc7 100644
--- a/activesupport/lib/active_support/per_thread_registry.rb
+++ b/activesupport/lib/active_support/per_thread_registry.rb
@@ -1,6 +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/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/ci/travis.rb b/ci/travis.rb
index 658d66c6b4..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'
}
@@ -139,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/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_support_core_extensions.md b/guides/source/active_support_core_extensions.md
index 06c5476d45..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
@@ -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/association_basics.md b/guides/source/association_basics.md
index c3bac320eb..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
```
@@ -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
```
@@ -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
```
@@ -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
@@ -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
```
@@ -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
```
@@ -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
```
@@ -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
```
@@ -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"
@@ -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
```
@@ -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
```
@@ -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 a39b975c3e..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:
@@ -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/debugging_rails_applications.md b/guides/source/debugging_rails_applications.md
index 5424313b33..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
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 1416d00de5..d8b590dba1 100644
--- a/guides/source/getting_started.md
+++ b/guides/source/getting_started.md
@@ -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
```
@@ -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/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/routing.md b/guides/source/routing.md
index fc756d00b3..2b1254f7a0 100644
--- a/guides/source/routing.md
+++ b/guides/source/routing.md
@@ -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 b301736c36..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) }
diff --git a/guides/source/testing.md b/guides/source/testing.md
index 58524fd6c5..a4b62955c5 100644
--- a/guides/source/testing.md
+++ b/guides/source/testing.md
@@ -177,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
```
diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md
index 9ba5021c4a..148890bf77 100644
--- a/guides/source/upgrading_ruby_on_rails.md
+++ b/guides/source/upgrading_ruby_on_rails.md
@@ -53,6 +53,25 @@ Don't forget to review the difference, to see if there were any unexpected chang
Upgrading from Rails 4.2 to Rails 5.0
-------------------------------------
+### 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
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 b9d2db773a..bf4eae39b9 100644
--- a/railties/CHANGELOG.md
+++ b/railties/CHANGELOG.md
@@ -1,3 +1,7 @@
+* 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.
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/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb
index bc5c8052dc..9036966d42 100644
--- a/railties/lib/rails/generators/app_base.rb
+++ b/railties/lib/rails/generators/app_base.rb
@@ -51,6 +51,9 @@ module Rails
class_option :skip_spring, type: :boolean, default: false,
desc: "Don't install Spring application preloader"
+ class_option :skip_action_cable, type: :boolean, aliases: '-C', default: false,
+ desc: 'Skip Action Cable files'
+
class_option :database, type: :string, aliases: '-d', default: 'sqlite3',
desc: "Preconfigure for selected database (options: #{DATABASES.join('/')})"
@@ -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,8 +220,6 @@ module Rails
def rails_gemfile_entry
dev_edge_common = [
- GemfileEntry.github('sprockets-rails', 'rails/sprockets-rails'),
- GemfileEntry.github('arel', 'rails/arel'),
GemfileEntry.github('rack', 'rack/rack')
]
if options.dev?
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/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb
index 9997cf3b35..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
@@ -299,6 +299,14 @@ module Rails
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'
diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile
index 4384d9b6eb..da5af4eefc 100644
--- a/railties/lib/rails/generators/rails/app/templates/Gemfile
+++ b/railties/lib/rails/generators/rails/app/templates/Gemfile
@@ -12,12 +12,12 @@ 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
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..cb7653cdc5
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/cable.coffee
@@ -0,0 +1,7 @@
+#= require action_cable
+#= require_self
+#= require_tree ./channels
+
+# Turn on the cable connection (ensure it's also on in config/routes.rb):
+# @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/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/config.ru b/railties/lib/rails/generators/rails/app/templates/config.ru.tt
index bd83b25412..4dddf0c03e 100644
--- a/railties/lib/rails/generators/rails/app/templates/config.ru
+++ b/railties/lib/rails/generators/rails/app/templates/config.ru.tt
@@ -1,4 +1,10 @@
# This file is used by Rack-based servers to start the application.
require ::File.expand_path('../config/environment', __FILE__)
+
+<%- unless options[:skip_action_cable] -%>
+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..cb1018c3ba 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 -%>
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/redis/cable.yml b/railties/lib/rails/generators/rails/app/templates/config/redis/cable.yml
new file mode 100644
index 0000000000..0156763c95
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/config/redis/cable.yml
@@ -0,0 +1,8 @@
+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/plugin/plugin_generator.rb b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb
index 776019a6a0..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
diff --git a/railties/lib/rails/generators/rails/plugin/templates/%name%.gemspec b/railties/lib/rails/generators/rails/plugin/templates/%name%.gemspec
index 3f5682b0c1..f9465aa4af 100644
--- a/railties/lib/rails/generators/rails/plugin/templates/%name%.gemspec
+++ b/railties/lib/rails/generators/rails/plugin/templates/%name%.gemspec
@@ -14,7 +14,7 @@ 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"]
+ s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"]
<%= '# ' if options.dev? || options.edge? -%>s.add_dependency "rails", "~> <%= Rails::VERSION::STRING %>"
<% unless options[:skip_active_record] -%>
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/test_unit/scaffold/templates/functional_test.rb b/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb
index 1989d84c79..8af14e84dc 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
@@ -4,8 +4,8 @@ require 'test_helper'
class <%= controller_class_name %>ControllerTest < ActionDispatch::IntegrationTest
<%- if mountable_engine? -%>
include Engine.routes.url_helpers
- <% end -%>
+ <% end -%>
setup do
@<%= singular_table_name %> = <%= fixture_name %>(:one)
end
diff --git a/railties/test/application/assets_test.rb b/railties/test/application/assets_test.rb
index 7e9a9a5f3b..5f3b364f97 100644
--- a/railties/test/application/assets_test.rb
+++ b/railties/test/application/assets_test.rb
@@ -410,7 +410,7 @@ module ApplicationTests
precompile!
- assert_equal "Post;\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
diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb
index 87e28288ee..50d343865c 100644
--- a/railties/test/application/configuration_test.rb
+++ b/railties/test/application/configuration_test.rb
@@ -229,6 +229,7 @@ module ApplicationTests
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
@@ -1307,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')
diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb
index 6373c7b42b..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: 10 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
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/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/app_generator_test.rb b/railties/test/generators/app_generator_test.rb
index 3f2ac3d2b6..ddbcd4c394 100644
--- a/railties/test/generators/app_generator_test.rb
+++ b/railties/test/generators/app_generator_test.rb
@@ -376,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)
@@ -612,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/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/plugin_generator_test.rb b/railties/test/generators/plugin_generator_test.rb
index 60390cfa01..057561070f 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,7 +58,7 @@ 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|
@@ -386,7 +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.files = Dir\["\{app,config,db,lib\}\/\*\*\/\*", "MIT-LICENSE", "Rakefile", "README\.md"\]/
assert_file "bukkits.gemspec", /s.version\s+ = Bukkits::VERSION/
end
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/tasks/release.rb b/tasks/release.rb
index 7c8b884d44..d935cdc53e 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