aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.travis.yml2
-rw-r--r--Gemfile18
-rw-r--r--Gemfile.lock49
-rw-r--r--actionmailer/actionmailer.gemspec2
-rw-r--r--actionmailer/lib/action_mailer/base.rb19
-rw-r--r--actionpack/CHANGELOG.md47
-rw-r--r--actionpack/actionpack.gemspec2
-rw-r--r--actionpack/lib/abstract_controller/callbacks.rb6
-rw-r--r--actionpack/lib/action_controller.rb1
-rw-r--r--actionpack/lib/action_controller/base.rb1
-rw-r--r--actionpack/lib/action_controller/form_builder.rb48
-rw-r--r--actionpack/lib/action_controller/metal/http_authentication.rb4
-rw-r--r--actionpack/lib/action_controller/metal/implicit_render.rb7
-rw-r--r--actionpack/lib/action_controller/metal/live.rb2
-rw-r--r--actionpack/lib/action_controller/metal/mime_responds.rb13
-rw-r--r--actionpack/lib/action_controller/metal/request_forgery_protection.rb29
-rw-r--r--actionpack/lib/action_controller/metal/strong_parameters.rb4
-rw-r--r--actionpack/lib/action_controller/metal/url_for.rb6
-rw-r--r--actionpack/lib/action_dispatch/http/mime_negotiation.rb16
-rw-r--r--actionpack/lib/action_dispatch/http/request.rb2
-rw-r--r--actionpack/lib/action_dispatch/journey/formatter.rb2
-rw-r--r--actionpack/lib/action_dispatch/journey/route.rb2
-rw-r--r--actionpack/lib/action_dispatch/middleware/cookies.rb18
-rw-r--r--actionpack/lib/action_dispatch/middleware/static.rb21
-rw-r--r--actionpack/lib/action_dispatch/request/session.rb3
-rw-r--r--actionpack/lib/action_dispatch/routing/inspector.rb2
-rw-r--r--actionpack/lib/action_dispatch/routing/mapper.rb2
-rw-r--r--actionpack/lib/action_dispatch/routing/route_set.rb2
-rw-r--r--actionpack/lib/action_dispatch/testing/integration.rb1
-rw-r--r--actionpack/test/abstract_unit.rb6
-rw-r--r--actionpack/test/controller/force_ssl_test.rb2
-rw-r--r--actionpack/test/controller/form_builder_test.rb17
-rw-r--r--actionpack/test/controller/mime/respond_to_test.rb23
-rw-r--r--actionpack/test/controller/parameters/always_permitted_parameters_test.rb9
-rw-r--r--actionpack/test/controller/redirect_test.rb3
-rw-r--r--actionpack/test/controller/request_forgery_protection_test.rb17
-rw-r--r--actionpack/test/controller/routing_test.rb8
-rw-r--r--actionpack/test/dispatch/request_test.rb50
-rw-r--r--actionpack/test/dispatch/routing/inspector_test.rb16
-rw-r--r--actionpack/test/dispatch/routing_test.rb13
-rw-r--r--actionpack/test/dispatch/static_test.rb28
-rw-r--r--actionpack/test/journey/route_test.rb8
-rw-r--r--actionpack/test/journey/router_test.rb27
-rw-r--r--actionview/CHANGELOG.md18
-rw-r--r--actionview/actionview.gemspec2
-rw-r--r--actionview/lib/action_view/helpers/asset_tag_helper.rb2
-rw-r--r--actionview/lib/action_view/helpers/asset_url_helper.rb30
-rw-r--r--actionview/lib/action_view/helpers/controller_helper.rb1
-rw-r--r--actionview/lib/action_view/helpers/form_helper.rb10
-rw-r--r--actionview/lib/action_view/helpers/form_tag_helper.rb2
-rw-r--r--actionview/lib/action_view/helpers/translation_helper.rb61
-rw-r--r--actionview/lib/action_view/helpers/url_helper.rb37
-rw-r--r--actionview/lib/action_view/layouts.rb25
-rw-r--r--actionview/lib/action_view/lookup_context.rb2
-rw-r--r--actionview/lib/action_view/template/handlers/raw.rb2
-rw-r--r--actionview/lib/action_view/template/resolver.rb2
-rw-r--r--actionview/test/actionpack/controller/layout_test.rb14
-rw-r--r--actionview/test/activerecord/form_helper_activerecord_test.rb4
-rw-r--r--actionview/test/template/capture_helper_test.rb6
-rw-r--r--actionview/test/template/controller_helper_test.rb21
-rw-r--r--actionview/test/template/date_helper_test.rb10
-rw-r--r--actionview/test/template/form_helper_test.rb41
-rw-r--r--actionview/test/template/translation_helper_test.rb5
-rw-r--r--activejob/CHANGELOG.md4
-rw-r--r--activejob/activejob.gemspec2
-rw-r--r--activejob/lib/active_job/arguments.rb5
-rw-r--r--activejob/lib/active_job/queue_adapters.rb71
-rw-r--r--activejob/lib/rails/generators/job/job_generator.rb1
-rw-r--r--activejob/lib/rails/generators/job/templates/job.rb2
-rw-r--r--activejob/test/integration/queuing_test.rb4
-rw-r--r--activejob/test/support/integration/adapters/que.rb24
-rw-r--r--activejob/test/support/integration/adapters/queue_classic.rb22
-rw-r--r--activejob/test/support/integration/adapters/sidekiq.rb80
-rw-r--r--activemodel/CHANGELOG.md24
-rw-r--r--activemodel/activemodel.gemspec2
-rw-r--r--activemodel/lib/active_model/attribute_methods.rb14
-rw-r--r--activemodel/lib/active_model/dirty.rb23
-rw-r--r--activemodel/lib/active_model/errors.rb28
-rw-r--r--activemodel/lib/active_model/naming.rb1
-rw-r--r--activemodel/lib/active_model/validations.rb3
-rw-r--r--activemodel/lib/active_model/validations/callbacks.rb2
-rw-r--r--activemodel/lib/active_model/validations/length.rb38
-rw-r--r--activemodel/test/cases/dirty_test.rb13
-rw-r--r--activemodel/test/cases/errors_test.rb6
-rw-r--r--activemodel/test/cases/validations/length_validation_test.rb20
-rw-r--r--activerecord/CHANGELOG.md74
-rw-r--r--activerecord/activerecord.gemspec2
-rw-r--r--activerecord/lib/active_record.rb1
-rw-r--r--activerecord/lib/active_record/associations.rb9
-rw-r--r--activerecord/lib/active_record/associations/builder/association.rb2
-rw-r--r--activerecord/lib/active_record/associations/builder/belongs_to.rb13
-rw-r--r--activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb4
-rw-r--r--activerecord/lib/active_record/associations/collection_association.rb2
-rw-r--r--activerecord/lib/active_record/associations/has_many_through_association.rb12
-rw-r--r--activerecord/lib/active_record/base.rb10
-rw-r--r--activerecord/lib/active_record/callbacks.rb11
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb4
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/quoting.rb2
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb3
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb33
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb53
-rw-r--r--activerecord/lib/active_record/connection_adapters/column.rb1
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql_adapter.rb4
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb20
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb4
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb18
-rw-r--r--activerecord/lib/active_record/core.rb28
-rw-r--r--activerecord/lib/active_record/enum.rb2
-rw-r--r--activerecord/lib/active_record/log_subscriber.rb3
-rw-r--r--activerecord/lib/active_record/model_schema.rb4
-rw-r--r--activerecord/lib/active_record/persistence.rb27
-rw-r--r--activerecord/lib/active_record/railties/controller_runtime.rb2
-rw-r--r--activerecord/lib/active_record/railties/databases.rake2
-rw-r--r--activerecord/lib/active_record/reflection.rb4
-rw-r--r--activerecord/lib/active_record/relation/calculations.rb8
-rw-r--r--activerecord/lib/active_record/relation/finder_methods.rb12
-rw-r--r--activerecord/lib/active_record/relation/record_fetch_warning.rb5
-rw-r--r--activerecord/lib/active_record/schema_dumper.rb5
-rw-r--r--activerecord/lib/active_record/scoping/default.rb2
-rw-r--r--activerecord/lib/active_record/touch_later.rb50
-rw-r--r--activerecord/lib/active_record/transactions.rb12
-rw-r--r--activerecord/lib/active_record/type/hash_lookup_type_map.rb10
-rw-r--r--activerecord/lib/active_record/validations/presence.rb4
-rw-r--r--activerecord/lib/active_record/validations/uniqueness.rb2
-rw-r--r--activerecord/test/cases/adapters/mysql/charset_collation_test.rb54
-rw-r--r--activerecord/test/cases/adapters/mysql2/charset_collation_test.rb54
-rw-r--r--activerecord/test/cases/associations/belongs_to_associations_test.rb22
-rw-r--r--activerecord/test/cases/associations/eager_test.rb17
-rw-r--r--activerecord/test/cases/associations/has_many_associations_test.rb10
-rw-r--r--activerecord/test/cases/associations/has_many_through_associations_test.rb16
-rw-r--r--activerecord/test/cases/autosave_association_test.rb12
-rw-r--r--activerecord/test/cases/batches_test.rb5
-rw-r--r--activerecord/test/cases/connection_management_test.rb2
-rw-r--r--activerecord/test/cases/connection_pool_test.rb4
-rw-r--r--activerecord/test/cases/disconnected_test.rb4
-rw-r--r--activerecord/test/cases/fixtures_test.rb12
-rw-r--r--activerecord/test/cases/locking_test.rb10
-rw-r--r--activerecord/test/cases/migration/references_foreign_key_test.rb42
-rw-r--r--activerecord/test/cases/persistence_test.rb3
-rw-r--r--activerecord/test/cases/primary_keys_test.rb3
-rw-r--r--activerecord/test/cases/relations_test.rb8
-rw-r--r--activerecord/test/cases/schema_dumper_test.rb2
-rw-r--r--activerecord/test/cases/timestamp_test.rb11
-rw-r--r--activerecord/test/cases/touch_later_test.rb93
-rw-r--r--activerecord/test/cases/validations/uniqueness_validation_test.rb25
-rw-r--r--activerecord/test/schema/mysql2_specific_schema.rb14
-rw-r--r--activerecord/test/schema/mysql_specific_schema.rb14
-rw-r--r--activesupport/CHANGELOG.md39
-rw-r--r--activesupport/activesupport.gemspec2
-rw-r--r--activesupport/lib/active_support.rb9
-rw-r--r--activesupport/lib/active_support/array_inquirer.rb38
-rw-r--r--activesupport/lib/active_support/cache/file_store.rb1
-rw-r--r--activesupport/lib/active_support/callbacks.rb44
-rw-r--r--activesupport/lib/active_support/core_ext/array.rb1
-rw-r--r--activesupport/lib/active_support/core_ext/array/inquiry.rb17
-rw-r--r--activesupport/lib/active_support/core_ext/array/wrap.rb9
-rw-r--r--activesupport/lib/active_support/core_ext/module/aliasing.rb7
-rw-r--r--activesupport/lib/active_support/core_ext/module/concerning.rb6
-rw-r--r--activesupport/lib/active_support/core_ext/module/deprecation.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/object/with_options.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/range/each.rb38
-rw-r--r--activesupport/lib/active_support/core_ext/range/include_range.rb40
-rw-r--r--activesupport/lib/active_support/core_ext/string/filters.rb3
-rw-r--r--activesupport/lib/active_support/core_ext/time/calculations.rb6
-rw-r--r--activesupport/lib/active_support/deprecation/proxy_wrappers.rb60
-rw-r--r--activesupport/lib/active_support/inflector/methods.rb4
-rw-r--r--activesupport/lib/active_support/number_helper/number_to_currency_converter.rb2
-rw-r--r--activesupport/lib/active_support/number_helper/number_to_human_converter.rb2
-rw-r--r--activesupport/lib/active_support/number_helper/number_to_human_size_converter.rb2
-rw-r--r--activesupport/lib/active_support/number_helper/number_to_percentage_converter.rb2
-rw-r--r--activesupport/lib/active_support/rails.rb4
-rw-r--r--activesupport/lib/active_support/railtie.rb7
-rw-r--r--activesupport/lib/active_support/rescuable.rb2
-rw-r--r--activesupport/lib/active_support/subscriber.rb4
-rw-r--r--activesupport/lib/active_support/testing/isolation.rb8
-rw-r--r--activesupport/lib/active_support/time_with_zone.rb13
-rw-r--r--activesupport/lib/active_support/values/time_zone.rb72
-rw-r--r--activesupport/test/array_inquirer_test.rb36
-rw-r--r--activesupport/test/caching_test.rb6
-rw-r--r--activesupport/test/callbacks_test.rb32
-rw-r--r--activesupport/test/core_ext/time_with_zone_test.rb47
-rw-r--r--activesupport/test/dependencies_test.rb4
-rw-r--r--activesupport/test/time_zone_test.rb83
-rw-r--r--guides/CHANGELOG.md4
-rw-r--r--guides/bug_report_templates/generic_gem.rb15
-rw-r--r--guides/bug_report_templates/generic_master.rb26
-rw-r--r--guides/rails_guides/levenshtein.rb7
-rw-r--r--guides/source/4_2_release_notes.md5
-rw-r--r--guides/source/action_controller_overview.md8
-rw-r--r--guides/source/action_view_overview.md96
-rw-r--r--guides/source/active_job_basics.md9
-rw-r--r--guides/source/active_record_migrations.md2
-rw-r--r--guides/source/active_record_postgresql.md23
-rw-r--r--guides/source/active_record_querying.md8
-rw-r--r--guides/source/active_support_core_extensions.md57
-rw-r--r--guides/source/active_support_instrumentation.md2
-rw-r--r--guides/source/asset_pipeline.md37
-rw-r--r--guides/source/association_basics.md48
-rw-r--r--guides/source/autoloading_and_reloading_constants.md4
-rw-r--r--guides/source/command_line.md8
-rw-r--r--guides/source/configuring.md85
-rw-r--r--guides/source/contributing_to_ruby_on_rails.md61
-rw-r--r--guides/source/debugging_rails_applications.md11
-rw-r--r--guides/source/engines.md21
-rw-r--r--guides/source/getting_started.md8
-rw-r--r--guides/source/i18n.md6
-rw-r--r--guides/source/initialization.md6
-rw-r--r--guides/source/layouts_and_rendering.md11
-rw-r--r--guides/source/routing.md12
-rw-r--r--guides/source/security.md12
-rw-r--r--guides/source/testing.md60
-rw-r--r--guides/source/upgrading_ruby_on_rails.md21
-rw-r--r--rails.gemspec2
-rw-r--r--railties/CHANGELOG.md33
-rwxr-xr-xrailties/exe/rails (renamed from railties/bin/rails)0
-rw-r--r--railties/lib/rails/app_rails_loader.rb3
-rw-r--r--railties/lib/rails/application.rb4
-rw-r--r--railties/lib/rails/code_statistics.rb6
-rw-r--r--railties/lib/rails/commands/commands_tasks.rb11
-rw-r--r--railties/lib/rails/commands/dbconsole.rb5
-rw-r--r--railties/lib/rails/generators.rb7
-rw-r--r--railties/lib/rails/generators/app_base.rb14
-rw-r--r--railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/app/jobs/application_job.rb2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/initializers/callback_terminator.rb2
-rw-r--r--railties/lib/rails/generators/rails/controller/controller_generator.rb10
-rw-r--r--railties/lib/rails/generators/rails/plugin/plugin_generator.rb2
-rw-r--r--railties/lib/rails/generators/rails/scaffold/templates/scaffold.css27
-rw-r--r--railties/lib/rails/rack/logger.rb3
-rw-r--r--railties/lib/rails/ruby_version_check.rb6
-rw-r--r--railties/lib/rails/templates/rails/welcome/index.html.erb13
-rw-r--r--railties/railties.gemspec6
-rw-r--r--railties/test/application/asset_debugging_test.rb4
-rw-r--r--railties/test/application/assets_test.rb26
-rw-r--r--railties/test/application/rake/dbs_test.rb28
-rw-r--r--railties/test/application/rake_test.rb2
-rw-r--r--railties/test/code_statistics_test.rb20
-rw-r--r--railties/test/commands/dbconsole_test.rb6
-rw-r--r--railties/test/generators/app_generator_test.rb14
-rw-r--r--railties/test/generators/controller_generator_test.rb4
-rw-r--r--railties/test/generators/job_generator_test.rb6
-rw-r--r--railties/test/generators_test.rb6
-rw-r--r--railties/test/isolation/abstract_unit.rb2
-rw-r--r--railties/test/path_generation_test.rb6
-rw-r--r--railties/test/railties/engine_test.rb4
-rw-r--r--railties/test/railties/generators_test.rb2
246 files changed, 2727 insertions, 1031 deletions
diff --git a/.travis.yml b/.travis.yml
index 0038668ae7..6c870d8797 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -20,7 +20,7 @@ env:
- "GEM=ar:postgresql"
- "GEM=aj:integration"
rvm:
- - 2.2.1
+ - 2.2.2
- ruby-head
- rbx-2
- jruby-head
diff --git a/Gemfile b/Gemfile
index 2fdcec062c..d6b9981bc5 100644
--- a/Gemfile
+++ b/Gemfile
@@ -17,10 +17,13 @@ gem 'turbolinks'
gem 'arel', github: 'rails/arel', branch: 'master'
gem 'mail', github: 'mikel/mail'
+gem 'sprockets', '~> 3.0.0.rc.1'
+gem 'sprockets-rails', github: 'rails/sprockets-rails', branch: 'master'
+
# require: false so bcrypt is loaded only when has_secure_password is used.
# This is to avoid ActiveModel (and by extension the entire framework)
# being dependent on a binary library.
-gem 'bcrypt', '~> 3.1.7', require: false
+gem 'bcrypt', '~> 3.1.10', require: false
# This needs to be with require false to avoid
# it being automatically loaded by sprockets
@@ -28,7 +31,7 @@ gem 'uglifier', '>= 1.3.0', require: false
group :doc do
gem 'sdoc', '~> 0.4.0'
- gem 'redcarpet', '~> 3.2.2', platforms: :ruby
+ gem 'redcarpet', '~> 3.2.3', platforms: :ruby
gem 'w3c_validators'
gem 'kindlerb', '0.1.1'
end
@@ -61,18 +64,11 @@ group :test do
# FIX: Our test suite isn't ready to run in random order yet
gem 'minitest', '< 5.3.4'
- platforms :mri_19 do
- gem 'ruby-prof', '~> 0.11.2'
- end
-
- platforms :mri_21, :mri_22 do
+ platforms :mri do
gem 'stackprof'
+ gem 'byebug'
end
- # platforms :mri do
- # gem 'byebug'
- # end
-
gem 'benchmark-ips'
end
diff --git a/Gemfile.lock b/Gemfile.lock
index cd360958d3..de83b535c2 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -35,6 +35,16 @@ GIT
railties (>= 4.2.0)
thor (>= 0.14, < 2.0)
+GIT
+ remote: git://github.com/rails/sprockets-rails.git
+ revision: 85b89c44ad40af3056899808475e6e4bf65c1f5a
+ branch: master
+ specs:
+ sprockets-rails (3.0.0.beta1)
+ actionpack (>= 4.0)
+ activesupport (>= 4.0)
+ sprockets (>= 3.0.0, < 4.0)
+
PATH
remote: .
specs:
@@ -99,11 +109,15 @@ GEM
beaneater (~> 0.3.1)
dante (~> 0.1.5)
bcrypt (3.1.10)
+ bcrypt (3.1.10-x64-mingw32)
+ bcrypt (3.1.10-x86-mingw32)
beaneater (0.3.3)
benchmark-ips (2.1.1)
builder (3.2.2)
bunny (1.1.9)
amq-protocol (>= 1.9.2)
+ byebug (4.0.5)
+ columnize (= 0.9.0)
celluloid (0.16.0)
timers (~> 4.0.0)
coffee-rails (4.1.0)
@@ -113,6 +127,7 @@ GEM
coffee-script-source
execjs
coffee-script-source (1.9.0)
+ columnize (0.9.0)
connection_pool (2.1.1)
dalli (2.7.2)
dante (0.1.5)
@@ -125,8 +140,8 @@ GEM
execjs (2.3.0)
globalid (0.3.3)
activesupport (>= 4.1.0)
- hike (1.2.3)
hitimes (1.2.2)
+ hitimes (1.2.2-x86-mingw32)
i18n (0.7.0)
json (1.8.2)
kindlerb (0.1.1)
@@ -142,12 +157,16 @@ GEM
mocha (0.14.0)
metaclass (~> 0.0.1)
mono_logger (1.1.0)
- multi_json (1.10.1)
+ multi_json (1.11.0)
mustache (1.0.0)
mysql (2.9.1)
mysql2 (0.3.18)
nokogiri (1.6.6.2)
mini_portile (~> 0.6.0)
+ nokogiri (1.6.6.2-x64-mingw32)
+ mini_portile (~> 0.6.0)
+ nokogiri (1.6.6.2-x86-mingw32)
+ mini_portile (~> 0.6.0)
pg (0.18.1)
psych (2.0.13)
que (0.9.2)
@@ -163,7 +182,7 @@ GEM
rack (>= 1.0)
rails-deprecated_sanitizer (1.0.3)
activesupport (>= 4.2.0.alpha)
- rails-dom-testing (1.0.5)
+ rails-dom-testing (1.0.6)
activesupport (>= 4.2.0.beta, < 5.0)
nokogiri (~> 1.6.0)
rails-deprecated_sanitizer (>= 1.0.1)
@@ -171,7 +190,7 @@ GEM
loofah (~> 2.0)
rake (10.4.2)
rdoc (4.2.0)
- redcarpet (3.2.2)
+ redcarpet (3.2.3)
redis (3.2.1)
redis-namespace (1.5.1)
redis (~> 3.0, >= 3.0.4)
@@ -186,7 +205,6 @@ GEM
redis (~> 3.0)
resque (~> 1.25)
rufus-scheduler (~> 3.0)
- ruby-prof (0.11.3)
rufus-scheduler (3.0.9)
tzinfo
sdoc (0.4.1)
@@ -211,22 +229,15 @@ GEM
serverengine
thor
thread
- sprockets (2.12.3)
- hike (~> 1.2)
- multi_json (~> 1.0)
+ sprockets (3.0.2)
rack (~> 1.0)
- tilt (~> 1.1, != 1.3.0)
- sprockets-rails (2.2.4)
- actionpack (>= 3.0)
- activesupport (>= 3.0)
- sprockets (>= 2.8, < 4.0)
sqlite3 (1.3.10)
stackprof (0.2.7)
sucker_punch (1.3.2)
celluloid (~> 0.16.0)
thor (0.19.1)
thread (0.1.5)
- thread_safe (0.3.4)
+ thread_safe (0.3.5)
tilt (1.4.1)
timers (4.0.1)
hitimes
@@ -245,6 +256,8 @@ GEM
PLATFORMS
ruby
+ x64-mingw32
+ x86-mingw32
DEPENDENCIES
activerecord-jdbcmysql-adapter (>= 1.3.0)
@@ -252,8 +265,9 @@ DEPENDENCIES
activerecord-jdbcsqlite3-adapter (>= 1.3.0)
arel!
backburner
- bcrypt (~> 3.1.7)
+ bcrypt (~> 3.1.10)
benchmark-ips
+ byebug
coffee-rails (~> 4.1.0)
dalli (>= 2.2.1)
delayed_job
@@ -277,14 +291,15 @@ DEPENDENCIES
rack-cache (~> 1.2)
rails!
rake (>= 10.3)
- redcarpet (~> 3.2.2)
+ redcarpet (~> 3.2.3)
resque
resque-scheduler
- ruby-prof (~> 0.11.2)
sdoc (~> 0.4.0)
sequel
sidekiq
sneakers (= 0.1.1.pre)
+ sprockets (~> 3.0.0.rc.1)
+ sprockets-rails!
sqlite3 (~> 1.3.6)
stackprof
sucker_punch
diff --git a/actionmailer/actionmailer.gemspec b/actionmailer/actionmailer.gemspec
index 41913899ff..782b208ef4 100644
--- a/actionmailer/actionmailer.gemspec
+++ b/actionmailer/actionmailer.gemspec
@@ -7,7 +7,7 @@ Gem::Specification.new do |s|
s.summary = 'Email composition, delivery, and receiving framework (part of Rails).'
s.description = 'Email on Rails. Compose, deliver, receive, and test emails using the familiar controller/view pattern. First-class support for multipart email and attachments.'
- s.required_ruby_version = '>= 2.2.1'
+ s.required_ruby_version = '>= 2.2.2'
s.license = 'MIT'
diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb
index c7f09ed192..6ddc4c9596 100644
--- a/actionmailer/lib/action_mailer/base.rb
+++ b/actionmailer/lib/action_mailer/base.rb
@@ -134,25 +134,28 @@ module ActionMailer
#
# = Sending mail
#
- # Once a mailer action and template are defined, you can deliver your message or create it and save it
- # for delivery later:
+ # Once a mailer action and template are defined, you can deliver your message or defer its creation and
+ # delivery for later:
#
# NotifierMailer.welcome(User.first).deliver_now # sends the email
# mail = NotifierMailer.welcome(User.first) # => an ActionMailer::MessageDelivery object
- # mail.deliver_now # sends the email
+ # mail.deliver_now # generates and sends the email now
#
- # The <tt>ActionMailer::MessageDelivery</tt> class is a wrapper around a <tt>Mail::Message</tt> object. If
- # you want direct access to the <tt>Mail::Message</tt> object you can call the <tt>message</tt> method on
- # the <tt>ActionMailer::MessageDelivery</tt> object.
+ # The <tt>ActionMailer::MessageDelivery</tt> class is a wrapper around a delegate that will call
+ # your method to generate the mail. If you want direct access to delegator, or <tt>Mail::Message</tt>,
+ # you can call the <tt>message</tt> method on the <tt>ActionMailer::MessageDelivery</tt> object.
#
# NotifierMailer.welcome(User.first).message # => a Mail::Message object
#
- # Action Mailer is nicely integrated with Active Job so you can send emails in the background (example: outside
- # of the request-response cycle, so the user doesn't have to wait on it):
+ # Action Mailer is nicely integrated with Active Job so you can generate and send emails in the background
+ # (example: outside of the request-response cycle, so the user doesn't have to wait on it):
#
# NotifierMailer.welcome(User.first).deliver_later # enqueue the email sending to Active Job
#
+ # Note that <tt>deliver_later</tt> will execute your method from the background job.
+ #
# You never instantiate your mailer class. Rather, you just call the method you defined on the class itself.
+ # All instance method are expected to return a message object to be sent.
#
# = Multipart Emails
#
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md
index 2cbe09e3e7..e0076225ba 100644
--- a/actionpack/CHANGELOG.md
+++ b/actionpack/CHANGELOG.md
@@ -1,3 +1,40 @@
+* Fix rake routes not showing the right format when
+ nesting multiple routes.
+
+ See #18373.
+
+ *Ravil Bayramgalin*
+
+* Add ability to override default form builder for a controller.
+
+ class AdminController < ApplicationController
+ default_form_builder AdminFormBuilder
+ end
+
+ *Kevin McPhillips*
+
+* For actions with no corresponding templates, render `head :no_content`
+ instead of raising an error. This allows for slimmer API controller
+ methods that simply work, without needing further instructions.
+
+ See #19036.
+
+ *Stephen Bussey*
+
+* Provide friendlier access to request variants.
+
+ request.variant = :phone
+ request.variant.phone? # true
+ request.variant.tablet? # false
+
+ request.variant = [:phone, :tablet]
+ request.variant.phone? # true
+ request.variant.desktop? # false
+ request.variant.any?(:phone, :desktop) # true
+ request.variant.any?(:desktop, :watch) # false
+
+ *George Claghorn*
+
* Fix regression where a gzip file response would have a Content-type,
even when it was a 304 status code.
@@ -5,16 +42,16 @@
*Kohei Suzuki*
-* Fix handling of empty X_FORWARDED_HOST header in raw_host_with_port
+* Fix handling of empty `X_FORWARDED_HOST` header in `raw_host_with_port`.
- Previously, an empty X_FORWARDED_HOST header would cause
- Actiondispatch::Http:URL.raw_host_with_port to return nil, causing
- Actiondispatch::Http:URL.host to raise a NoMethodError.
+ Previously, an empty `X_FORWARDED_HOST` header would cause
+ `Actiondispatch::Http:URL.raw_host_with_port` to return `nil`, causing
+ `Actiondispatch::Http:URL.host` to raise a `NoMethodError`.
*Adam Forsyth*
* Drop request class from RouteSet constructor.
-
+
If you would like to use a custom request class, please subclass and implement
the `request_class` method.
diff --git a/actionpack/actionpack.gemspec b/actionpack/actionpack.gemspec
index b6b70a027c..1bba9df969 100644
--- a/actionpack/actionpack.gemspec
+++ b/actionpack/actionpack.gemspec
@@ -7,7 +7,7 @@ Gem::Specification.new do |s|
s.summary = 'Web-flow and rendering framework putting the VC in MVC (part of Rails).'
s.description = 'Web apps on Rails. Simple, battle-tested conventions for building and testing MVC web applications. Works with any Rack-compatible server.'
- s.required_ruby_version = '>= 2.2.1'
+ s.required_ruby_version = '>= 2.2.2'
s.license = 'MIT'
diff --git a/actionpack/lib/abstract_controller/callbacks.rb b/actionpack/lib/abstract_controller/callbacks.rb
index 59ffb0a19e..13795f0dd8 100644
--- a/actionpack/lib/abstract_controller/callbacks.rb
+++ b/actionpack/lib/abstract_controller/callbacks.rb
@@ -62,9 +62,9 @@ module AbstractController
# using #skip_action_callback
def skip_action_callback(*names)
ActiveSupport::Deprecation.warn('`skip_action_callback` is deprecated and will be removed in the next major version of Rails. Please use skip_before_action, skip_after_action or skip_around_action instead.')
- skip_before_action(*names)
- skip_after_action(*names)
- skip_around_action(*names)
+ skip_before_action(*names, raise: false)
+ skip_after_action(*names, raise: false)
+ skip_around_action(*names, raise: false)
end
def skip_filter(*names)
diff --git a/actionpack/lib/action_controller.rb b/actionpack/lib/action_controller.rb
index 7667e469d3..a1893ce920 100644
--- a/actionpack/lib/action_controller.rb
+++ b/actionpack/lib/action_controller.rb
@@ -12,6 +12,7 @@ module ActionController
autoload :Metal
autoload :Middleware
autoload :Renderer
+ autoload :FormBuilder
autoload_under "metal" do
autoload :Compatibility
diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb
index e6038396f9..bfae372f53 100644
--- a/actionpack/lib/action_controller/base.rb
+++ b/actionpack/lib/action_controller/base.rb
@@ -221,6 +221,7 @@ module ActionController
Cookies,
Flash,
+ FormBuilder,
RequestForgeryProtection,
ForceSSL,
Streaming,
diff --git a/actionpack/lib/action_controller/form_builder.rb b/actionpack/lib/action_controller/form_builder.rb
new file mode 100644
index 0000000000..f2656ca894
--- /dev/null
+++ b/actionpack/lib/action_controller/form_builder.rb
@@ -0,0 +1,48 @@
+module ActionController
+ # Override the default form builder for all views rendered by this
+ # controller and any of its descendants. Accepts a subclass of
+ # +ActionView::Helpers::FormBuilder+.
+ #
+ # For example, given a form builder:
+ #
+ # class AdminFormBuilder < ActionView::Helpers::FormBuilder
+ # def special_field(name)
+ # end
+ # end
+ #
+ # The controller specifies a form builder as its default:
+ #
+ # class AdminAreaController < ApplicationController
+ # default_form_builder AdminFormBuilder
+ # end
+ #
+ # Then in the view any form using +form_for+ will be an instance of the
+ # specified form builder:
+ #
+ # <%= form_for(@instance) do |builder| %>
+ # <%= builder.special_field(:name) %>
+ # <% end %>
+ module FormBuilder
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :_default_form_builder, instance_accessor: false
+ end
+
+ module ClassMethods
+ # Set the form builder to be used as the default for all forms
+ # in the views rendered by this controller and its subclasses.
+ #
+ # ==== Parameters
+ # * <tt>builder</tt> - Default form builder, an instance of +ActionView::Helpers::FormBuilder+
+ def default_form_builder(builder)
+ self._default_form_builder = builder
+ end
+ end
+
+ # Default form builder for the controller
+ def default_form_builder
+ self.class._default_form_builder
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/http_authentication.rb b/actionpack/lib/action_controller/metal/http_authentication.rb
index 2273406948..909ed19a49 100644
--- a/actionpack/lib/action_controller/metal/http_authentication.rb
+++ b/actionpack/lib/action_controller/metal/http_authentication.rb
@@ -118,7 +118,7 @@ module ActionController
end
def authentication_request(controller, realm)
- controller.headers["WWW-Authenticate"] = %(Basic realm="#{realm.gsub(/"/, "")}")
+ controller.headers["WWW-Authenticate"] = %(Basic realm="#{realm.tr('"'.freeze, "".freeze)}")
controller.status = 401
controller.response_body = "HTTP Basic: Access denied.\n"
end
@@ -499,7 +499,7 @@ module ActionController
#
# Returns nothing.
def authentication_request(controller, realm)
- controller.headers["WWW-Authenticate"] = %(Token realm="#{realm.gsub(/"/, "")}")
+ controller.headers["WWW-Authenticate"] = %(Token realm="#{realm.tr('"'.freeze, "".freeze)}")
controller.__send__ :render, :text => "HTTP Token: Access denied.\n", :status => :unauthorized
end
end
diff --git a/actionpack/lib/action_controller/metal/implicit_render.rb b/actionpack/lib/action_controller/metal/implicit_render.rb
index ae04b53825..1573ea7099 100644
--- a/actionpack/lib/action_controller/metal/implicit_render.rb
+++ b/actionpack/lib/action_controller/metal/implicit_render.rb
@@ -7,7 +7,12 @@ module ActionController
end
def default_render(*args)
- render(*args)
+ if template_exists?(action_name.to_s, _prefixes, variants: request.variant)
+ render(*args)
+ else
+ logger.info "No template found for #{self.class.name}\##{action_name}, rendering head :no_content" if logger
+ head :no_content
+ end
end
def method_for_action(action_name)
diff --git a/actionpack/lib/action_controller/metal/live.rb b/actionpack/lib/action_controller/metal/live.rb
index 7590fb6843..58150cd9a9 100644
--- a/actionpack/lib/action_controller/metal/live.rb
+++ b/actionpack/lib/action_controller/metal/live.rb
@@ -102,7 +102,7 @@ module ActionController
end
end
- message = json.gsub(/\n/, "\ndata: ")
+ message = json.gsub("\n".freeze, "\ndata: ".freeze)
@stream.write "data: #{message}\n\n"
end
end
diff --git a/actionpack/lib/action_controller/metal/mime_responds.rb b/actionpack/lib/action_controller/metal/mime_responds.rb
index 7dae171215..fab1be3459 100644
--- a/actionpack/lib/action_controller/metal/mime_responds.rb
+++ b/actionpack/lib/action_controller/metal/mime_responds.rb
@@ -288,16 +288,17 @@ module ActionController #:nodoc:
end
def variant
- if @variant.nil?
+ if @variant.empty?
@variants[:none] || @variants[:any]
- elsif (@variants.keys & @variant).any?
- @variant.each do |v|
- return @variants[v] if @variants.key?(v)
- end
else
- @variants[:any]
+ @variants[variant_key]
end
end
+
+ private
+ def variant_key
+ @variant.find { |variant| @variants.key?(variant) } || :any
+ end
end
end
end
diff --git a/actionpack/lib/action_controller/metal/request_forgery_protection.rb b/actionpack/lib/action_controller/metal/request_forgery_protection.rb
index 367b736035..31c8856437 100644
--- a/actionpack/lib/action_controller/metal/request_forgery_protection.rb
+++ b/actionpack/lib/action_controller/metal/request_forgery_protection.rb
@@ -13,9 +13,14 @@ module ActionController #:nodoc:
# by including a token in the rendered HTML for your application. This token is
# stored as a random string in the session, to which an attacker does not have
# access. When a request reaches your application, \Rails verifies the received
- # token with the token in the session. Only HTML and JavaScript requests are checked,
- # so this will not protect your XML API (presumably you'll have a different
- # authentication scheme there anyway).
+ # token with the token in the session. All requests are checked except GET requests
+ # as these should be idempotent. Keep in mind that all session-oriented requests
+ # should be CSRF protected, including JavaScript and HTML requests.
+ #
+ # Since HTML and JavaScript requests are typically made from the browser, we
+ # need to ensure to verify request authenticity for the web browser. We can
+ # use session-oriented authentication for these types requests, by using
+ # the `protect_form_forgery` method in our controllers.
#
# GET requests are not protected since they don't have side effects like writing
# to the database and don't leak sensitive information. JavaScript requests are
@@ -26,15 +31,21 @@ module ActionController #:nodoc:
# Ajax) requests are allowed to make GET requests for JavaScript responses.
#
# It's important to remember that XML or JSON requests are also affected and if
- # you're building an API you'll need something like:
+ # you're building an API you should change forgery protection method in
+ # <tt>ApplicationController</tt> (by default: <tt>:exception</tt>):
#
# class ApplicationController < ActionController::Base
# protect_from_forgery unless: -> { request.format.json? }
# end
#
- # CSRF protection is turned on with the <tt>protect_from_forgery</tt> method,
- # which checks the token and resets the session if it doesn't match what was expected.
- # A call to this method is generated for new \Rails applications by default.
+ # CSRF protection is turned on with the <tt>protect_from_forgery</tt> method.
+ # By default <tt>protect_from_forgery</tt> protects your session with
+ # <tt>:null_session</tt> method, which provides an empty session
+ # during request.
+ #
+ # We may want to disable CSRF protection for APIs since they are typically
+ # designed to be state-less. That is, the requestion API client will handle
+ # the session for you instead of Rails.
#
# The token parameter is named <tt>authenticity_token</tt> by default. The name and
# value of this token must be added to every layout that renders forms by including
@@ -86,10 +97,10 @@ module ActionController #:nodoc:
# Valid Options:
#
# * <tt>:only/:except</tt> - Only apply forgery protection to a subset of actions. Like <tt>only: [ :create, :create_all ]</tt>.
- # * <tt>:if/:unless</tt> - Turn off the forgery protection entirely depending on the passed proc or method reference.
+ # * <tt>:if/:unless</tt> - Turn off the forgery protection entirely depending on the passed Proc or method reference.
# * <tt>:prepend</tt> - By default, the verification of the authentication token is added to the front of the
# callback chain. If you need to make the verification depend on other callbacks, like authentication methods
- # (say cookies vs oauth), this might not work for you. Pass <tt>prepend: false</tt> to just add the
+ # (say cookies vs OAuth), this might not work for you. Pass <tt>prepend: false</tt> to just add the
# verification callback in the position of the protect_from_forgery call. This means any callbacks added
# before are run first.
# * <tt>:with</tt> - Set the method to handle unverified request.
diff --git a/actionpack/lib/action_controller/metal/strong_parameters.rb b/actionpack/lib/action_controller/metal/strong_parameters.rb
index f19c4201ba..c98e937423 100644
--- a/actionpack/lib/action_controller/metal/strong_parameters.rb
+++ b/actionpack/lib/action_controller/metal/strong_parameters.rb
@@ -117,7 +117,7 @@ module ActionController
self.always_permitted_parameters = %w( controller action )
def self.const_missing(const_name)
- super unless const_name == :NEVER_UNPERMITTED_PARAMS
+ return super unless const_name == :NEVER_UNPERMITTED_PARAMS
ActiveSupport::Deprecation.warn(<<-MSG.squish)
`ActionController::Parameters::NEVER_UNPERMITTED_PARAMS` has been deprecated.
Use `ActionController::Parameters.always_permitted_parameters` instead.
@@ -268,7 +268,7 @@ module ActionController
#
# params.permit(:name)
#
- # +:name+ passes it is a key of +params+ whose associated value is of type
+ # +:name+ passes if it is a key of +params+ whose associated value is of type
# +String+, +Symbol+, +NilClass+, +Numeric+, +TrueClass+, +FalseClass+,
# +Date+, +Time+, +DateTime+, +StringIO+, +IO+,
# +ActionDispatch::Http::UploadedFile+ or +Rack::Test::UploadedFile+.
diff --git a/actionpack/lib/action_controller/metal/url_for.rb b/actionpack/lib/action_controller/metal/url_for.rb
index fbaa90d521..5a0e5c62e4 100644
--- a/actionpack/lib/action_controller/metal/url_for.rb
+++ b/actionpack/lib/action_controller/metal/url_for.rb
@@ -5,9 +5,9 @@ module ActionController
# In addition to <tt>AbstractController::UrlFor</tt>, this module accesses the HTTP layer to define
# url options like the +host+. In order to do so, this module requires the host class
# to implement +env+ which needs to be Rack-compatible and +request+
- # which is either instance of +ActionDispatch::Request+ or an object
- # that responds to <tt>host</tt>, <tt>optional_port</tt>, <tt>protocol</tt> and
- # <tt>symbolized_path_parameter</tt> methods.
+ # which is either an instance of +ActionDispatch::Request+ or an object
+ # that responds to the +host+, +optional_port+, +protocol+ and
+ # +symbolized_path_parameter+ methods.
#
# class RootUrl
# include ActionController::UrlFor
diff --git a/actionpack/lib/action_dispatch/http/mime_negotiation.rb b/actionpack/lib/action_dispatch/http/mime_negotiation.rb
index 53a98c5d0a..ff336b7354 100644
--- a/actionpack/lib/action_dispatch/http/mime_negotiation.rb
+++ b/actionpack/lib/action_dispatch/http/mime_negotiation.rb
@@ -10,8 +10,6 @@ module ActionDispatch
self.ignore_accept_header = false
end
- attr_reader :variant
-
# The MIME type of the HTTP request, such as Mime::XML.
#
# For backward compatibility, the post \format is extracted from the
@@ -75,18 +73,22 @@ module ActionDispatch
# Sets the \variant for template.
def variant=(variant)
- if variant.is_a?(Symbol)
- @variant = [variant]
- elsif variant.nil? || variant.is_a?(Array) && variant.any? && variant.all?{ |v| v.is_a?(Symbol) }
- @variant = variant
+ variant = Array(variant)
+
+ if variant.all? { |v| v.is_a?(Symbol) }
+ @variant = ActiveSupport::ArrayInquirer.new(variant)
else
- raise ArgumentError, "request.variant must be set to a Symbol or an Array of Symbols, not a #{variant.class}. " \
+ raise ArgumentError, "request.variant must be set to a Symbol or an Array of Symbols. " \
"For security reasons, never directly set the variant to a user-provided value, " \
"like params[:variant].to_sym. Check user-provided value against a whitelist first, " \
"then set the variant: request.variant = :tablet if params[:variant] == 'tablet'"
end
end
+ def variant
+ @variant ||= ActiveSupport::ArrayInquirer.new
+ end
+
# Sets the \format by string extension, which can be used to force custom formats
# that are not controlled by the extension.
#
diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb
index 732ee67268..a1f84e5ace 100644
--- a/actionpack/lib/action_dispatch/http/request.rb
+++ b/actionpack/lib/action_dispatch/http/request.rb
@@ -340,7 +340,7 @@ module ActionDispatch
end
protected
- def parse_query(qs)
+ def parse_query(*)
Utils.deep_munge(super)
end
diff --git a/actionpack/lib/action_dispatch/journey/formatter.rb b/actionpack/lib/action_dispatch/journey/formatter.rb
index 992c1a9efe..c0566c6fc9 100644
--- a/actionpack/lib/action_dispatch/journey/formatter.rb
+++ b/actionpack/lib/action_dispatch/journey/formatter.rb
@@ -39,7 +39,7 @@ module ActionDispatch
return [route.format(parameterized_parts), params]
end
- message = "No route matches #{Hash[constraints.sort].inspect}"
+ message = "No route matches #{Hash[constraints.sort_by{|k,v| k.to_s}].inspect}"
message << " missing required keys: #{missing_keys.sort.inspect}" unless missing_keys.empty?
raise ActionController::UrlGenerationError, message
diff --git a/actionpack/lib/action_dispatch/journey/route.rb b/actionpack/lib/action_dispatch/journey/route.rb
index 4d5c18984a..4698ff8cc7 100644
--- a/actionpack/lib/action_dispatch/journey/route.rb
+++ b/actionpack/lib/action_dispatch/journey/route.rb
@@ -36,7 +36,7 @@ module ActionDispatch
def requirements # :nodoc:
# needed for rails `rake routes`
- path.requirements.merge(@defaults).delete_if { |_,v|
+ @defaults.merge(path.requirements).delete_if { |_,v|
/.+?/ == v
}
end
diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb
index b7687ca100..bb6a73afb5 100644
--- a/actionpack/lib/action_dispatch/middleware/cookies.rb
+++ b/actionpack/lib/action_dispatch/middleware/cookies.rb
@@ -181,7 +181,7 @@ module ActionDispatch
# to the Message{Encryptor,Verifier} allows us to handle the
# (de)serialization step within the cookie jar, which gives us the
# opportunity to detect and migrate legacy cookies.
- module VerifyAndUpgradeLegacySignedMessage
+ module VerifyAndUpgradeLegacySignedMessage # :nodoc:
def initialize(*args)
super
@legacy_verifier = ActiveSupport::MessageVerifier.new(@options[:secret_token], serializer: ActiveSupport::MessageEncryptor::NullSerializer)
@@ -392,7 +392,7 @@ module ActionDispatch
end
end
- class JsonSerializer
+ class JsonSerializer # :nodoc:
def self.load(value)
ActiveSupport::JSON.decode(value)
end
@@ -402,7 +402,7 @@ module ActionDispatch
end
end
- module SerializedCookieJars
+ module SerializedCookieJars # :nodoc:
MARSHAL_SIGNATURE = "\x04\x08".freeze
protected
@@ -454,12 +454,16 @@ module ActionDispatch
@verifier = ActiveSupport::MessageVerifier.new(secret, digest: digest, serializer: ActiveSupport::MessageEncryptor::NullSerializer)
end
+ # Returns the value of the cookie by +name+ if it is untampered,
+ # returns +nil+ otherwise or if no such cookie exists.
def [](name)
if signed_message = @parent_jar[name]
deserialize name, verify(signed_message)
end
end
+ # Signs and sets the cookie named +name+. The second argument may be the cookie's
+ # value or a hash of options as documented above.
def []=(name, options)
if options.is_a?(Hash)
options.symbolize_keys!
@@ -482,8 +486,8 @@ module ActionDispatch
# UpgradeLegacySignedCookieJar is used instead of SignedCookieJar if
# secrets.secret_token and secrets.secret_key_base are both set. It reads
- # legacy cookies signed with the old dummy key generator and re-saves
- # them using the new key generator to provide a smooth upgrade path.
+ # legacy cookies signed with the old dummy key generator and signs and
+ # re-saves them using the new key generator to provide a smooth upgrade path.
class UpgradeLegacySignedCookieJar < SignedCookieJar #:nodoc:
include VerifyAndUpgradeLegacySignedMessage
@@ -511,12 +515,16 @@ module ActionDispatch
@encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret, digest: digest, serializer: ActiveSupport::MessageEncryptor::NullSerializer)
end
+ # Returns the value of the cookie by +name+ if it is untampered,
+ # returns +nil+ otherwise or if no such cookie exists.
def [](name)
if encrypted_message = @parent_jar[name]
deserialize name, decrypt_and_verify(encrypted_message)
end
end
+ # Encrypts and sets the cookie named +name+. The second argument may be the cookie's
+ # value or a hash of options as documented above.
def []=(name, options)
if options.is_a?(Hash)
options.symbolize_keys!
diff --git a/actionpack/lib/action_dispatch/middleware/static.rb b/actionpack/lib/action_dispatch/middleware/static.rb
index fdd1bc4e69..c47e5d5245 100644
--- a/actionpack/lib/action_dispatch/middleware/static.rb
+++ b/actionpack/lib/action_dispatch/middleware/static.rb
@@ -3,15 +3,15 @@ require 'active_support/core_ext/uri'
module ActionDispatch
# This middleware returns a file's contents from disk in the body response.
- # When initialized it can accept an optional 'Cache-Control' header which
+ # When initialized, it can accept an optional 'Cache-Control' header, which
# will be set when a response containing a file's contents is delivered.
#
# This middleware will render the file specified in `env["PATH_INFO"]`
- # where the base path is in the +root+ directory. For example if the +root+
- # is set to `public/` then a request with `env["PATH_INFO"]` of
- # `assets/application.js` will return a response with contents of a file
+ # where the base path is in the +root+ directory. For example, if the +root+
+ # is set to `public/`, then a request with `env["PATH_INFO"]` of
+ # `assets/application.js` will return a response with the contents of a file
# located at `public/assets/application.js` if the file exists. If the file
- # does not exist a 404 "File not Found" response will be returned.
+ # does not exist, a 404 "File not Found" response will be returned.
class FileHandler
def initialize(root, cache_control)
@root = root.chomp('/')
@@ -20,6 +20,13 @@ module ActionDispatch
@file_server = ::Rack::File.new(@root, headers)
end
+
+ # Takes a path to a file. If the file is found, has valid encoding, and has
+ # correct read permissions, the return value is a URI-escaped string
+ # representing the filename. Otherwise, false is returned.
+ #
+ # Used by the `Static` class to check the existence of a valid file
+ # in the server's `public/` directory. (See Static#call)
def match?(path)
path = URI.parser.unescape(path)
return false unless path.valid_encoding?
@@ -28,7 +35,7 @@ module ActionDispatch
paths = [path, "#{path}#{ext}", "#{path}/index#{ext}"]
if match = paths.detect { |p|
- path = File.join(@root, p)
+ path = File.join(@root, p.force_encoding('UTF-8'))
begin
File.file?(path) && File.readable?(path)
rescue SystemCallError
@@ -88,7 +95,7 @@ module ActionDispatch
end
# This middleware will attempt to return the contents of a file's body from
- # disk in the response. If a file is not found on disk, the request will be
+ # disk in the response. If a file is not found on disk, the request will be
# delegated to the application stack. This middleware is commonly initialized
# to serve assets from a server's `public/` directory.
#
diff --git a/actionpack/lib/action_dispatch/request/session.rb b/actionpack/lib/action_dispatch/request/session.rb
index 973627f106..9a1a05e971 100644
--- a/actionpack/lib/action_dispatch/request/session.rb
+++ b/actionpack/lib/action_dispatch/request/session.rb
@@ -9,7 +9,8 @@ module ActionDispatch
# Singleton object used to determine if an optional param wasn't specified
Unspecified = Object.new
-
+
+ # Creates a session hash, merging the properties of the previous session if any
def self.create(store, env, default_options)
session_was = find env
session = Request::Session.new(store, env)
diff --git a/actionpack/lib/action_dispatch/routing/inspector.rb b/actionpack/lib/action_dispatch/routing/inspector.rb
index c513737fc2..48c10a7d4c 100644
--- a/actionpack/lib/action_dispatch/routing/inspector.rb
+++ b/actionpack/lib/action_dispatch/routing/inspector.rb
@@ -45,7 +45,7 @@ module ActionDispatch
end
def internal?
- controller.to_s =~ %r{\Arails/(info|mailers|welcome)} || path =~ %r{\A#{Rails.application.config.assets.prefix}\z}
+ controller.to_s =~ %r{\Arails/(info|mailers|welcome)}
end
def engine?
diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb
index 34b5b48f3a..49009a45cc 100644
--- a/actionpack/lib/action_dispatch/routing/mapper.rb
+++ b/actionpack/lib/action_dispatch/routing/mapper.rb
@@ -1678,7 +1678,7 @@ module ActionDispatch
end
def shallow_nesting_depth #:nodoc:
- @nesting.select(&:shallow?).size
+ @nesting.count(&:shallow?)
end
def param_constraint? #:nodoc:
diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb
index 0f3734dd74..d0d8ded515 100644
--- a/actionpack/lib/action_dispatch/routing/route_set.rb
+++ b/actionpack/lib/action_dispatch/routing/route_set.rb
@@ -226,7 +226,7 @@ module ActionDispatch
params = parameterize_args(args) { |missing_key|
missing_keys << missing_key
}
- constraints = Hash[@route.requirements.merge(params).sort]
+ constraints = Hash[@route.requirements.merge(params).sort_by{|k,v| k.to_s}]
message = "No route matches #{constraints.inspect}"
message << " missing required keys: #{missing_keys.sort.inspect}"
diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb
index 9390e2937a..3800c61dab 100644
--- a/actionpack/lib/action_dispatch/testing/integration.rb
+++ b/actionpack/lib/action_dispatch/testing/integration.rb
@@ -2,6 +2,7 @@ require 'stringio'
require 'uri'
require 'active_support/core_ext/kernel/singleton_class'
require 'active_support/core_ext/object/try'
+require 'active_support/core_ext/string/strip'
require 'rack/test'
require 'minitest'
diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb
index 62ff1be5c9..c1be2c9afe 100644
--- a/actionpack/test/abstract_unit.rb
+++ b/actionpack/test/abstract_unit.rb
@@ -14,7 +14,11 @@ silence_warnings do
end
require 'drb'
-require 'drb/unix'
+begin
+ require 'drb/unix'
+rescue LoadError
+ puts "'drb/unix' is not available"
+end
require 'tempfile'
PROCESS_COUNT = (ENV['N'] || 4).to_i
diff --git a/actionpack/test/controller/force_ssl_test.rb b/actionpack/test/controller/force_ssl_test.rb
index 04222745d9..5639abdc56 100644
--- a/actionpack/test/controller/force_ssl_test.rb
+++ b/actionpack/test/controller/force_ssl_test.rb
@@ -315,7 +315,7 @@ class RedirectToSSLTest < ActionController::TestCase
assert_equal "https://secure.cheeseburger.host/redirect_to_ssl/cheeseburger", redirect_to_url
end
- def test_banana_does_not_redirect_if_already_https
+ def test_cheeseburgers_does_not_redirect_if_already_https
request.env['HTTPS'] = 'on'
get :cheeseburger
assert_response 200
diff --git a/actionpack/test/controller/form_builder_test.rb b/actionpack/test/controller/form_builder_test.rb
new file mode 100644
index 0000000000..99eeaf9ab6
--- /dev/null
+++ b/actionpack/test/controller/form_builder_test.rb
@@ -0,0 +1,17 @@
+require 'abstract_unit'
+
+class FormBuilderController < ActionController::Base
+ class SpecializedFormBuilder < ActionView::Helpers::FormBuilder ; end
+
+ default_form_builder SpecializedFormBuilder
+end
+
+class ControllerFormBuilderTest < ActiveSupport::TestCase
+ setup do
+ @controller = FormBuilderController.new
+ end
+
+ def test_default_form_builder_assigned
+ assert_equal FormBuilderController::SpecializedFormBuilder, @controller.default_form_builder
+ end
+end
diff --git a/actionpack/test/controller/mime/respond_to_test.rb b/actionpack/test/controller/mime/respond_to_test.rb
index 1f5f66dc80..7aef8a50ce 100644
--- a/actionpack/test/controller/mime/respond_to_test.rb
+++ b/actionpack/test/controller/mime/respond_to_test.rb
@@ -1,4 +1,5 @@
require 'abstract_unit'
+require "active_support/log_subscriber/test_helper"
class RespondToController < ActionController::Base
layout :set_layout
@@ -608,19 +609,29 @@ class RespondToControllerTest < ActionController::TestCase
end
def test_invalid_variant
+ logger = ActiveSupport::LogSubscriber::TestHelper::MockLogger.new
+ old_logger, ActionController::Base.logger = ActionController::Base.logger, logger
+
@request.variant = :invalid
- assert_raises(ActionView::MissingTemplate) do
- get :variant_with_implicit_rendering
- end
+ get :variant_with_implicit_rendering
+ assert_response :no_content
+ assert_equal 1, logger.logged(:info).select{ |s| s =~ /No template found/ }.size, "Implicit head :no_content not logged"
+ ensure
+ ActionController::Base.logger = old_logger
end
def test_variant_not_set_regular_template_missing
- assert_raises(ActionView::MissingTemplate) do
- get :variant_with_implicit_rendering
- end
+ get :variant_with_implicit_rendering
+ assert_response :no_content
end
def test_variant_with_implicit_rendering
+ @request.variant = :implicit
+ get :variant_with_implicit_rendering
+ assert_response :no_content
+ end
+
+ def test_variant_with_implicit_template_rendering
@request.variant = :mobile
get :variant_with_implicit_rendering
assert_equal "text/html", @response.content_type
diff --git a/actionpack/test/controller/parameters/always_permitted_parameters_test.rb b/actionpack/test/controller/parameters/always_permitted_parameters_test.rb
index 059f310d49..59be08db54 100644
--- a/actionpack/test/controller/parameters/always_permitted_parameters_test.rb
+++ b/actionpack/test/controller/parameters/always_permitted_parameters_test.rb
@@ -1,5 +1,6 @@
require 'abstract_unit'
require 'action_controller/metal/strong_parameters'
+require 'minitest/mock'
class AlwaysPermittedParametersTest < ActiveSupport::TestCase
def setup
@@ -14,7 +15,13 @@ class AlwaysPermittedParametersTest < ActiveSupport::TestCase
test "shows deprecations warning on NEVER_UNPERMITTED_PARAMS" do
assert_deprecated do
- ActionController::Parameters::NEVER_UNPERMITTED_PARAMS
+ ActionController::Parameters::NEVER_UNPERMITTED_PARAMS
+ end
+ end
+
+ test "returns super on missing constant other than NEVER_UNPERMITTED_PARAMS" do
+ ActionController::Parameters.superclass.stub :const_missing, "super" do
+ assert_equal "super", ActionController::Parameters::NON_EXISTING_CONSTANT
end
end
diff --git a/actionpack/test/controller/redirect_test.rb b/actionpack/test/controller/redirect_test.rb
index efd790de63..ef30f1ea0f 100644
--- a/actionpack/test/controller/redirect_test.rb
+++ b/actionpack/test/controller/redirect_test.rb
@@ -1,8 +1,5 @@
require 'abstract_unit'
-class WorkshopsController < ActionController::Base
-end
-
class RedirectController < ActionController::Base
# empty method not used anywhere to ensure methods like
# `status` and `location` aren't called on `redirect_to` calls
diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb
index 8887f291cf..f8cf79a257 100644
--- a/actionpack/test/controller/request_forgery_protection_test.rb
+++ b/actionpack/test/controller/request_forgery_protection_test.rb
@@ -12,14 +12,6 @@ module RequestForgeryProtectionActions
render :inline => "<%= button_to('New', '/') %>"
end
- def external_form
- render :inline => "<%= form_tag('http://farfar.away/form', :authenticity_token => 'external_token') {} %>"
- end
-
- def external_form_without_protection
- render :inline => "<%= form_tag('http://farfar.away/form', :authenticity_token => false) {} %>"
- end
-
def unsafe
render :text => 'pwn'
end
@@ -28,14 +20,6 @@ module RequestForgeryProtectionActions
render :inline => "<%= csrf_meta_tags %>"
end
- def external_form_for
- render :inline => "<%= form_for(:some_resource, :authenticity_token => 'external_token') {} %>"
- end
-
- def form_for_without_protection
- render :inline => "<%= form_for(:some_resource, :authenticity_token => false ) {} %>"
- end
-
def form_for_remote
render :inline => "<%= form_for(:some_resource, :remote => true ) {} %>"
end
@@ -70,7 +54,6 @@ module RequestForgeryProtectionActions
negotiate_same_origin
end
- def rescue_action(e) raise e end
end
# sample controllers
diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb
index 2d08987ca6..9bbfb74e72 100644
--- a/actionpack/test/controller/routing_test.rb
+++ b/actionpack/test/controller/routing_test.rb
@@ -8,8 +8,6 @@ class MilestonesController < ActionController::Base
alias_method :show, :index
end
-ROUTING = ActionDispatch::Routing
-
# See RFC 3986, section 3.3 for allowed path characters.
class UriReservedCharactersRoutingTest < ActiveSupport::TestCase
include RoutingTestHelpers
@@ -871,7 +869,7 @@ class RouteSetTest < ActiveSupport::TestCase
def default_route_set
@default_route_set ||= begin
- set = ROUTING::RouteSet.new
+ set = ActionDispatch::Routing::RouteSet.new
set.draw do
get '/:controller(/:action(/:id))'
end
@@ -1748,13 +1746,13 @@ class RouteSetTest < ActiveSupport::TestCase
include ActionDispatch::RoutingVerbs
- class TestSet < ROUTING::RouteSet
+ class TestSet < ActionDispatch::Routing::RouteSet
def initialize(block)
@block = block
super()
end
- class Dispatcher < ROUTING::RouteSet::Dispatcher
+ class Dispatcher < ActionDispatch::Routing::RouteSet::Dispatcher
def initialize(defaults, set, block)
super(defaults)
@block = block
diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb
index 61cc4dcd7e..f208cfda89 100644
--- a/actionpack/test/dispatch/request_test.rb
+++ b/actionpack/test/dispatch/request_test.rb
@@ -1128,35 +1128,47 @@ class RequestEtag < BaseRequestTest
end
class RequestVariant < BaseRequestTest
- test "setting variant" do
- request = stub_request
+ def setup
+ super
+ @request = stub_request
+ end
- request.variant = :mobile
- assert_equal [:mobile], request.variant
+ test 'setting variant to a symbol' do
+ @request.variant = :phone
- request.variant = [:phone, :tablet]
- assert_equal [:phone, :tablet], request.variant
+ assert @request.variant.phone?
+ assert_not @request.variant.tablet?
+ assert @request.variant.any?(:phone, :tablet)
+ assert_not @request.variant.any?(:tablet, :desktop)
+ end
- assert_raise ArgumentError do
- request.variant = [:phone, "tablet"]
- end
+ test 'setting variant to an array of symbols' do
+ @request.variant = [:phone, :tablet]
- assert_raise ArgumentError do
- request.variant = "yolo"
- end
+ assert @request.variant.phone?
+ assert @request.variant.tablet?
+ assert_not @request.variant.desktop?
+ assert @request.variant.any?(:tablet, :desktop)
+ assert_not @request.variant.any?(:desktop, :watch)
end
- test "reset variant" do
- request = stub_request
+ test 'clearing variant' do
+ @request.variant = nil
- request.variant = nil
- assert_equal nil, request.variant
+ assert @request.variant.empty?
+ assert_not @request.variant.phone?
+ assert_not @request.variant.any?(:phone, :tablet)
end
- test "setting variant with non symbol value" do
- request = stub_request
+ test 'setting variant to a non-symbol value' do
+ assert_raise ArgumentError do
+ @request.variant = 'phone'
+ end
+ end
+
+ test 'setting variant to an array containing a non-symbol value' do
assert_raise ArgumentError do
- request.variant = "mobile"
+ @request.variant = [:phone, 'tablet']
end
end
end
diff --git a/actionpack/test/dispatch/routing/inspector_test.rb b/actionpack/test/dispatch/routing/inspector_test.rb
index 3df022c64b..4047214843 100644
--- a/actionpack/test/dispatch/routing/inspector_test.rb
+++ b/actionpack/test/dispatch/routing/inspector_test.rb
@@ -313,6 +313,22 @@ module ActionDispatch
assert_equal ["Prefix Verb URI Pattern Controller#Action",
" GET /:controller(/:action) (?-mix:api\\/[^\\/]+)#:action"], output
end
+
+ def test_inspect_routes_shows_resources_route_when_assets_disabled
+ @set = ActionDispatch::Routing::RouteSet.new
+ app = ActiveSupport::OrderedOptions.new
+
+ Rails.stubs(:application).returns(app)
+
+ output = draw do
+ get '/cart', to: 'cart#show'
+ end
+
+ assert_equal [
+ "Prefix Verb URI Pattern Controller#Action",
+ " cart GET /cart(.:format) cart#show"
+ ], output
+ end
end
end
end
diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb
index 55fc160ac8..62c99a2edc 100644
--- a/actionpack/test/dispatch/routing_test.rb
+++ b/actionpack/test/dispatch/routing_test.rb
@@ -4476,6 +4476,19 @@ class TestUrlGenerationErrors < ActionDispatch::IntegrationTest
error = assert_raises(ActionController::UrlGenerationError, message){ product_path(id: nil) }
assert_equal message, error.message
end
+
+ test "url helpers raise message with mixed parameters when generation fails " do
+ url, missing = { action: 'show', controller: 'products', id: nil, "id"=>"url-tested"}, [:id]
+ message = "No route matches #{url.inspect} missing required keys: #{missing.inspect}"
+
+ # Optimized url helper
+ error = assert_raises(ActionController::UrlGenerationError){ product_path(nil, 'id'=>'url-tested') }
+ assert_equal message, error.message
+
+ # Non-optimized url helper
+ error = assert_raises(ActionController::UrlGenerationError, message){ product_path(id: nil, 'id'=>'url-tested') }
+ assert_equal message, error.message
+ end
end
class TestDefaultUrlOptions < ActionDispatch::IntegrationTest
diff --git a/actionpack/test/dispatch/static_test.rb b/actionpack/test/dispatch/static_test.rb
index 288a2084f6..93e5c85a97 100644
--- a/actionpack/test/dispatch/static_test.rb
+++ b/actionpack/test/dispatch/static_test.rb
@@ -2,6 +2,20 @@ require 'abstract_unit'
require 'zlib'
module StaticTests
+ def setup
+ silence_warnings do
+ @default_internal_encoding = Encoding.default_internal
+ @default_external_encoding = Encoding.default_external
+ end
+ end
+
+ def teardown
+ silence_warnings do
+ Encoding.default_internal = @default_internal_encoding
+ Encoding.default_external = @default_external_encoding
+ end
+ end
+
def test_serves_dynamic_content
assert_equal "Hello, World!", get("/nofile").body
end
@@ -10,6 +24,18 @@ module StaticTests
assert_equal "Hello, World!", get("/doorkeeper%E3E4").body
end
+ def test_handles_urls_with_ascii_8bit
+ assert_equal "Hello, World!", get("/doorkeeper%E3E4".force_encoding('ASCII-8BIT')).body
+ end
+
+ def test_handles_urls_with_ascii_8bit_on_win_31j
+ silence_warnings do
+ Encoding.default_internal = "Windows-31J"
+ Encoding.default_external = "Windows-31J"
+ end
+ assert_equal "Hello, World!", get("/doorkeeper%E3E4".force_encoding('ASCII-8BIT')).body
+ end
+
def test_sets_cache_control
response = get("/index.html")
assert_html "/index.html", response
@@ -208,6 +234,7 @@ class StaticTest < ActiveSupport::TestCase
}
def setup
+ super
@root = "#{FIXTURE_LOAD_PATH}/public"
@app = ActionDispatch::Static.new(DummyApp, @root, "public, max-age=60")
end
@@ -237,6 +264,7 @@ end
class StaticEncodingTest < StaticTest
def setup
+ super
@root = "#{FIXTURE_LOAD_PATH}/公共"
@app = ActionDispatch::Static.new(DummyApp, @root, "public, max-age=60")
end
diff --git a/actionpack/test/journey/route_test.rb b/actionpack/test/journey/route_test.rb
index 21d867aca0..9616f036b3 100644
--- a/actionpack/test/journey/route_test.rb
+++ b/actionpack/test/journey/route_test.rb
@@ -25,6 +25,14 @@ module ActionDispatch
end
end
+ def test_path_requirements_override_defaults
+ strexp = Router::Strexp.build(':name', { name: /love/ }, ['/'])
+ path = Path::Pattern.new strexp
+ defaults = { name: 'tender' }
+ route = Route.new('name', nil, path, nil, defaults)
+ assert_equal /love/, route.requirements[:name]
+ end
+
def test_ip_address
path = Path::Pattern.from_string '/messages/:id(.:format)'
route = Route.new("name", nil, path, {:ip => '192.168.1.1'},
diff --git a/actionpack/test/journey/router_test.rb b/actionpack/test/journey/router_test.rb
index 19c61b5914..a134e343cc 100644
--- a/actionpack/test/journey/router_test.rb
+++ b/actionpack/test/journey/router_test.rb
@@ -401,6 +401,33 @@ module ActionDispatch
assert_equal({:id => 1, :relative_url_root => nil}, params)
end
+ def test_generate_missing_keys_no_matches_different_format_keys
+ path = Path::Pattern.from_string '/:controller/:action/:name'
+ @router.routes.add_route @app, path, {}, {}, {}
+ primarty_parameters = {
+ :id => 1,
+ :controller => "tasks",
+ :action => "show",
+ :relative_url_root => nil
+ }
+ redirection_parameters = {
+ 'action'=>'show',
+ }
+ missing_key = 'name'
+ missing_parameters ={
+ missing_key => "task_1"
+ }
+ request_parameters = primarty_parameters.merge(redirection_parameters).merge(missing_parameters)
+
+ message = "No route matches #{Hash[request_parameters.sort_by{|k,v|k.to_s}].inspect} missing required keys: #{[missing_key.to_sym].inspect}"
+
+ error = assert_raises(ActionController::UrlGenerationError) do
+ @formatter.generate(
+ nil, request_parameters, request_parameters)
+ end
+ assert_equal message, error.message
+ end
+
def test_generate_uses_recall_if_needed
path = Path::Pattern.from_string '/:controller(/:action(/:id))'
@router.routes.add_route @app, path, {}, {}, {}
diff --git a/actionview/CHANGELOG.md b/actionview/CHANGELOG.md
index 74a677968f..78ce230b3a 100644
--- a/actionview/CHANGELOG.md
+++ b/actionview/CHANGELOG.md
@@ -1,6 +1,20 @@
+* Load the `default_form_builder` from the controller on initialization, which overrides
+ the global config if it is present.
+
+ *Kevin McPhillips*
+
+* Accept lambda as `child_index` option in `fields_for` method.
+
+ *Karol Galanciak*
+
+* `translate` allows `default: [[]]` again for a default value of `[]`.
+
+ Fixes #19640.
+
+ *Adam Prescott*
+
* `translate` should accept nils as members of the `:default`
- parameter without raising a translation missing error. Fixes a
- regression introduced 362557e.
+ parameter without raising a translation missing error.
Fixes #19419
diff --git a/actionview/actionview.gemspec b/actionview/actionview.gemspec
index d8ea9d562c..612e94021d 100644
--- a/actionview/actionview.gemspec
+++ b/actionview/actionview.gemspec
@@ -7,7 +7,7 @@ Gem::Specification.new do |s|
s.summary = 'Rendering framework putting the V in MVC (part of Rails).'
s.description = 'Simple, battle-tested conventions and helpers for building web pages.'
- s.required_ruby_version = '>= 2.2.1'
+ s.required_ruby_version = '>= 2.2.2'
s.license = 'MIT'
diff --git a/actionview/lib/action_view/helpers/asset_tag_helper.rb b/actionview/lib/action_view/helpers/asset_tag_helper.rb
index 5c28043f8a..60fc9ee1a2 100644
--- a/actionview/lib/action_view/helpers/asset_tag_helper.rb
+++ b/actionview/lib/action_view/helpers/asset_tag_helper.rb
@@ -127,7 +127,7 @@ module ActionView
# auto_discovery_link_tag(:rss, {controller: "news", action: "feed"})
# # => <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/news/feed" />
# auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {title: "Example RSS"})
- # # => <link rel="alternate" type="application/rss+xml" title="Example RSS" href="http://www.example.com/feed" />
+ # # => <link rel="alternate" type="application/rss+xml" title="Example RSS" href="http://www.example.com/feed.rss" />
def auto_discovery_link_tag(type = :rss, url_options = {}, tag_options = {})
if !(type == :rss || type == :atom) && tag_options[:type].blank?
raise ArgumentError.new("You should pass :type tag_option key explicitly, because you have passed #{type} type other than :rss or :atom.")
diff --git a/actionview/lib/action_view/helpers/asset_url_helper.rb b/actionview/lib/action_view/helpers/asset_url_helper.rb
index 29733442c1..ef4a6c98c0 100644
--- a/actionview/lib/action_view/helpers/asset_url_helper.rb
+++ b/actionview/lib/action_view/helpers/asset_url_helper.rb
@@ -248,6 +248,11 @@ module ActionView
# Computes the full URL to a JavaScript asset in the public javascripts directory.
# This will use +javascript_path+ internally, so most of their behaviors will be the same.
+ # Since +javascript_url+ is based on +asset_url+ method you can set :host options. If :host
+ # options is set, it overwrites global +config.action_controller.asset_host+ setting.
+ #
+ # javascript_url "js/xmlhr.js", host: "http://stage.example.com" # => http://stage.example.com/assets/dir/xmlhr.js
+ #
def javascript_url(source, options = {})
url_to_asset(source, {type: :javascript}.merge!(options))
end
@@ -270,6 +275,11 @@ module ActionView
# Computes the full URL to a stylesheet asset in the public stylesheets directory.
# This will use +stylesheet_path+ internally, so most of their behaviors will be the same.
+ # Since +stylesheet_url+ is based on +asset_url+ method you can set :host options. If :host
+ # options is set, it overwrites global +config.action_controller.asset_host+ setting.
+ #
+ # stylesheet_url "css/style.css", host: "http://stage.example.com" # => http://stage.example.com/css/style.css
+ #
def stylesheet_url(source, options = {})
url_to_asset(source, {type: :stylesheet}.merge!(options))
end
@@ -295,6 +305,11 @@ module ActionView
# Computes the full URL to an image asset.
# This will use +image_path+ internally, so most of their behaviors will be the same.
+ # Since +image_url+ is based on +asset_url+ method you can set :host options. If :host
+ # options is set, it overwrites global +config.action_controller.asset_host+ setting.
+ #
+ # image_url "edit.png", host: "http://stage.example.com" # => http://stage.example.com/edit.png
+ #
def image_url(source, options = {})
url_to_asset(source, {type: :image}.merge!(options))
end
@@ -316,6 +331,11 @@ module ActionView
# Computes the full URL to a video asset in the public videos directory.
# This will use +video_path+ internally, so most of their behaviors will be the same.
+ # Since +video_url+ is based on +asset_url+ method you can set :host options. If :host
+ # options is set, it overwrites global +config.action_controller.asset_host+ setting.
+ #
+ # video_url "hd.avi", host: "http://stage.example.com" # => http://stage.example.com/hd.avi
+ #
def video_url(source, options = {})
url_to_asset(source, {type: :video}.merge!(options))
end
@@ -337,6 +357,11 @@ module ActionView
# Computes the full URL to an audio asset in the public audios directory.
# This will use +audio_path+ internally, so most of their behaviors will be the same.
+ # Since +audio_url+ is based on +asset_url+ method you can set :host options. If :host
+ # options is set, it overwrites global +config.action_controller.asset_host+ setting.
+ #
+ # audio_url "horse.wav", host: "http://stage.example.com" # => http://stage.example.com/horse.wav
+ #
def audio_url(source, options = {})
url_to_asset(source, {type: :audio}.merge!(options))
end
@@ -357,6 +382,11 @@ module ActionView
# Computes the full URL to a font asset.
# This will use +font_path+ internally, so most of their behaviors will be the same.
+ # Since +font_url+ is based on +asset_url+ method you can set :host options. If :host
+ # options is set, it overwrites global +config.action_controller.asset_host+ setting.
+ #
+ # font_url "font.ttf", host: "http://stage.example.com" # => http://stage.example.com/font.ttf
+ #
def font_url(source, options = {})
url_to_asset(source, {type: :font}.merge!(options))
end
diff --git a/actionview/lib/action_view/helpers/controller_helper.rb b/actionview/lib/action_view/helpers/controller_helper.rb
index 74ef25f7c1..3569fba8c6 100644
--- a/actionview/lib/action_view/helpers/controller_helper.rb
+++ b/actionview/lib/action_view/helpers/controller_helper.rb
@@ -14,6 +14,7 @@ module ActionView
if @_controller = controller
@_request = controller.request if controller.respond_to?(:request)
@_config = controller.config.inheritable_copy if controller.respond_to?(:config)
+ @_default_form_builder = controller.default_form_builder if controller.respond_to?(:default_form_builder)
end
end
diff --git a/actionview/lib/action_view/helpers/form_helper.rb b/actionview/lib/action_view/helpers/form_helper.rb
index 891cc53765..7fdeca5ea8 100644
--- a/actionview/lib/action_view/helpers/form_helper.rb
+++ b/actionview/lib/action_view/helpers/form_helper.rb
@@ -114,6 +114,8 @@ module ActionView
include ModelNaming
include RecordIdentifier
+ attr_internal :default_form_builder
+
# Creates a form that allows the user to create or update the attributes
# of a specific model object.
#
@@ -1233,7 +1235,7 @@ module ActionView
end
def default_form_builder_class
- builder = ActionView::Base.default_form_builder
+ builder = default_form_builder || ActionView::Base.default_form_builder
builder.respond_to?(:constantize) ? builder.constantize : builder
end
end
@@ -1928,7 +1930,11 @@ module ActionView
explicit_child_index = options[:child_index]
output = ActiveSupport::SafeBuffer.new
association.each do |child|
- options[:child_index] = nested_child_index(name) unless explicit_child_index
+ if explicit_child_index
+ options[:child_index] = explicit_child_index.call if explicit_child_index.respond_to?(:call)
+ else
+ options[:child_index] = nested_child_index(name)
+ end
output << fields_for_nested_model("#{name}[#{options[:child_index]}]", child, options, block)
end
output
diff --git a/actionview/lib/action_view/helpers/form_tag_helper.rb b/actionview/lib/action_view/helpers/form_tag_helper.rb
index 65a0548ffb..1f76f40138 100644
--- a/actionview/lib/action_view/helpers/form_tag_helper.rb
+++ b/actionview/lib/action_view/helpers/form_tag_helper.rb
@@ -80,7 +80,7 @@ module ActionView
# associated records. <tt>option_tags</tt> is a string containing the option tags for the select box.
#
# ==== Options
- # * <tt>:multiple</tt> - If set to true the selection will allow multiple choices.
+ # * <tt>:multiple</tt> - If set to true, the selection will allow multiple choices.
# * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
# * <tt>:include_blank</tt> - If set to true, an empty option will be created. If set to a string, the string will be used as the option's content and the value will be empty.
# * <tt>:prompt</tt> - Create a prompt option with blank value and the text asking user to select something.
diff --git a/actionview/lib/action_view/helpers/translation_helper.rb b/actionview/lib/action_view/helpers/translation_helper.rb
index 29a0860c00..089627a221 100644
--- a/actionview/lib/action_view/helpers/translation_helper.rb
+++ b/actionview/lib/action_view/helpers/translation_helper.rb
@@ -7,41 +7,54 @@ module ActionView
module Helpers
module TranslationHelper
include TagHelper
- # Delegates to <tt>I18n#translate</tt> but also performs three additional functions.
+ # Delegates to <tt>I18n#translate</tt> but also performs three additional
+ # functions.
#
- # First, it will ensure that any thrown +MissingTranslation+ messages will be turned
- # into inline spans that:
+ # First, it will ensure that any thrown +MissingTranslation+ messages will
+ # be rendered as inline spans that:
#
- # * have a "translation-missing" class set,
- # * contain the missing key as a title attribute and
- # * a titleized version of the last key segment as a text.
+ # * Have a <tt>translation-missing</tt> class applied
+ # * Contain the missing key as the value of the +title+ attribute
+ # * Have a titleized version of the last key segment as text
#
- # E.g. the value returned for a missing translation key :"blog.post.title" will be
- # <span class="translation_missing" title="translation missing: en.blog.post.title">Title</span>.
- # This way your views will display rather reasonable strings but it will still
- # be easy to spot missing translations.
+ # For example, the value returned for the missing translation key
+ # <tt>"blog.post.title"</tt> will be:
#
- # Second, it'll scope the key by the current partial if the key starts
- # with a period. So if you call <tt>translate(".foo")</tt> from the
- # <tt>people/index.html.erb</tt> template, you'll actually be calling
- # <tt>I18n.translate("people.index.foo")</tt>. This makes it less repetitive
- # to translate many keys within the same partials and gives you a simple framework
- # for scoping them consistently. If you don't prepend the key with a period,
- # nothing is converted.
+ # <span
+ # class="translation_missing"
+ # title="translation missing: en.blog.post.title">Title</span>
#
- # Third, it'll mark the translation as safe HTML if the key has the suffix
- # "_html" or the last element of the key is the word "html". For example,
- # calling translate("footer_html") or translate("footer.html") will return
- # a safe HTML string that won't be escaped by other HTML helper methods. This
- # naming convention helps to identify translations that include HTML tags so that
- # you know what kind of output to expect when you call translate in a template.
+ # This allows for views to display rather reasonable strings while still
+ # giving developers a way to find missing translations.
+ #
+ # If you would prefer missing translations to raise an error, you can
+ # opt out of span-wrapping behavior globally by setting
+ # <tt>ActionView::Base.raise_on_missing_translations = true</tt> or
+ # individually by passing <tt>raise: true</tt> as an option to
+ # <tt>translate</tt>.
+ #
+ # Second, if the key starts with a period <tt>translate</tt> will scope
+ # the key by the current partial. Calling <tt>translate(".foo")</tt> from
+ # the <tt>people/index.html.erb</tt> template is equivalent to calling
+ # <tt>translate("people.index.foo")</tt>. This makes it less
+ # repetitive to translate many keys within the same partial and provides
+ # a convention to scope keys consistently.
+ #
+ # Third, the translation will be marked as <tt>html_safe</tt> if the key
+ # has the suffix "_html" or the last element of the key is "html". Calling
+ # <tt>translate("footer_html")</tt> or <tt>translate("footer.html")</tt>
+ # will return an HTML safe string that won't be escaped by other HTML
+ # helper methods. This naming convention helps to identify translations
+ # that include HTML tags so that you know what kind of output to expect
+ # when you call translate in a template and translators know which keys
+ # they can provide HTML values for.
def translate(key, options = {})
options = options.dup
has_default = options.has_key?(:default)
remaining_defaults = Array(options.delete(:default)).compact
if has_default && !remaining_defaults.first.kind_of?(Symbol)
- options[:default] = remaining_defaults.shift
+ options[:default] = remaining_defaults
end
# If the user has explicitly decided to NOT raise errors, pass that option to I18n.
diff --git a/actionview/lib/action_view/helpers/url_helper.rb b/actionview/lib/action_view/helpers/url_helper.rb
index 89b96ac42c..afb1265ad9 100644
--- a/actionview/lib/action_view/helpers/url_helper.rb
+++ b/actionview/lib/action_view/helpers/url_helper.rb
@@ -172,6 +172,11 @@ module ActionView
#
# link_to "Visit Other Site", "http://www.rubyonrails.org/", data: { confirm: "Are you sure?" }
# # => <a href="http://www.rubyonrails.org/" data-confirm="Are you sure?">Visit Other Site</a>
+ #
+ # Also you can set any link attributes such as <tt>target</tt>, <tt>rel</tt>, <tt>type</tt>:
+ #
+ # link_to "External link", "http://www.rubyonrails.org/", target: "_blank", rel: "nofollow"
+ # # => <a href="http://www.rubyonrails.org/" target="_blank" rel="nofollow">External link</a>
def link_to(name = nil, options = nil, html_options = nil, &block)
html_options, options, name = options, name, block if block_given?
options ||= {}
@@ -471,57 +476,45 @@ module ActionView
# True if the current request URI was generated by the given +options+.
#
# ==== Examples
- # Let's say we're in the <tt>http://www.example.com/shop/checkout?order=desc</tt> action.
+ # Let's say we're in the <tt>http://www.example.com/shop/checkout?order=desc&page=1</tt> action.
#
# current_page?(action: 'process')
# # => false
#
- # current_page?(controller: 'shop', action: 'checkout')
- # # => true
- #
- # current_page?(controller: 'shop', action: 'checkout', order: 'asc')
- # # => false
- #
# current_page?(action: 'checkout')
# # => true
#
# current_page?(controller: 'library', action: 'checkout')
# # => false
#
- # current_page?('http://www.example.com/shop/checkout')
- # # => true
- #
- # current_page?('/shop/checkout')
+ # current_page?(controller: 'shop', action: 'checkout')
# # => true
#
- # Let's say we're in the <tt>http://www.example.com/shop/checkout?order=desc&page=1</tt> action.
- #
- # current_page?(action: 'process')
+ # current_page?(controller: 'shop', action: 'checkout', order: 'asc')
# # => false
#
- # current_page?(controller: 'shop', action: 'checkout')
- # # => true
- #
# current_page?(controller: 'shop', action: 'checkout', order: 'desc', page: '1')
# # => true
#
# current_page?(controller: 'shop', action: 'checkout', order: 'desc', page: '2')
# # => false
#
- # current_page?(controller: 'shop', action: 'checkout', order: 'desc')
- # # => false
+ # current_page?('http://www.example.com/shop/checkout')
+ # # => true
#
- # current_page?(action: 'checkout')
+ # current_page?('/shop/checkout')
# # => true
#
- # current_page?(controller: 'library', action: 'checkout')
- # # => false
+ # current_page?('http://www.example.com/shop/checkout?order=desc&page=1')
+ # # => true
#
# Let's say we're in the <tt>http://www.example.com/products</tt> action with method POST in case of invalid product.
#
# current_page?(controller: 'product', action: 'index')
# # => false
#
+ # We can also pass in the symbol arguments instead of strings.
+ #
def current_page?(options)
unless request
raise "You cannot use helpers that need to determine the current " \
diff --git a/actionview/lib/action_view/layouts.rb b/actionview/lib/action_view/layouts.rb
index 9d636c8c9e..1fc609f2cd 100644
--- a/actionview/lib/action_view/layouts.rb
+++ b/actionview/lib/action_view/layouts.rb
@@ -315,16 +315,25 @@ module ActionView
name_clause
end
- self.class_eval <<-RUBY, __FILE__, __LINE__ + 1
- def _layout
- if _conditional_layout?
+ if self._layout_conditions.empty?
+ self.class_eval <<-RUBY, __FILE__, __LINE__ + 1
+ def _layout
#{layout_definition}
- else
- #{name_clause}
end
- end
- private :_layout
- RUBY
+ private :_layout
+ RUBY
+ else
+ self.class_eval <<-RUBY, __FILE__, __LINE__ + 1
+ def _layout
+ if _conditional_layout?
+ #{layout_definition}
+ else
+ #{name_clause}
+ end
+ end
+ private :_layout
+ RUBY
+ end
end
private
diff --git a/actionview/lib/action_view/lookup_context.rb b/actionview/lib/action_view/lookup_context.rb
index 36855ec3d0..4452dcfed5 100644
--- a/actionview/lib/action_view/lookup_context.rb
+++ b/actionview/lib/action_view/lookup_context.rb
@@ -126,7 +126,7 @@ module ActionView
@view_paths.find_all(*args_for_lookup(name, prefixes, partial, keys, options))
end
- def exists?(name, prefixes = [], partial = false, keys = [], options = {})
+ def exists?(name, prefixes = [], partial = false, keys = [], **options)
@view_paths.exists?(*args_for_lookup(name, prefixes, partial, keys, options))
end
alias :template_exists? :exists?
diff --git a/actionview/lib/action_view/template/handlers/raw.rb b/actionview/lib/action_view/template/handlers/raw.rb
index 397c86014a..b08fb0870f 100644
--- a/actionview/lib/action_view/template/handlers/raw.rb
+++ b/actionview/lib/action_view/template/handlers/raw.rb
@@ -2,7 +2,7 @@ module ActionView
module Template::Handlers
class Raw
def call(template)
- escaped = template.source.gsub(/:/, '\:')
+ escaped = template.source.gsub(':'.freeze, '\:'.freeze)
'%q:' + escaped + ':;'
end
diff --git a/actionview/lib/action_view/template/resolver.rb b/actionview/lib/action_view/template/resolver.rb
index bc0db330ea..955118a554 100644
--- a/actionview/lib/action_view/template/resolver.rb
+++ b/actionview/lib/action_view/template/resolver.rb
@@ -270,7 +270,7 @@ module ActionView
#
# ActionController::Base.view_paths = FileSystemResolver.new(
# Rails.root.join("app/views"),
- # ":prefix{/:locale}/:action{.:formats,}{+:variants,}{.:handlers,}"
+ # ":prefix/:action{.:locale,}{.:formats,}{+:variants,}{.:handlers,}",
# )
#
# ==== Pattern format and variables
diff --git a/actionview/test/actionpack/controller/layout_test.rb b/actionview/test/actionpack/controller/layout_test.rb
index 7b8a83e2fe..64ab125637 100644
--- a/actionview/test/actionpack/controller/layout_test.rb
+++ b/actionview/test/actionpack/controller/layout_test.rb
@@ -122,6 +122,14 @@ class PrependsViewPathController < LayoutTest
end
end
+class ParentController < LayoutTest
+ layout 'item'
+end
+
+class ChildController < ParentController
+ layout 'layout_test', only: :hello
+end
+
class OnlyLayoutController < LayoutTest
layout 'item', :only => "hello"
end
@@ -225,6 +233,12 @@ class LayoutSetInResponseTest < ActionController::TestCase
get :hello
assert_equal "layout_test.erb hello.erb", @response.body.strip
end
+
+ def test_respect_to_parent_layout
+ @controller = ChildController.new
+ get :goodbye
+ assert_template :layout => "layouts/item"
+ end
end
class SetsNonExistentLayoutFile < LayoutTest
diff --git a/actionview/test/activerecord/form_helper_activerecord_test.rb b/actionview/test/activerecord/form_helper_activerecord_test.rb
index 0a62f49f35..2769b97445 100644
--- a/actionview/test/activerecord/form_helper_activerecord_test.rb
+++ b/actionview/test/activerecord/form_helper_activerecord_test.rb
@@ -35,10 +35,6 @@ class FormHelperActiveRecordTest < ActionView::TestCase
end
end
- def _routes
- Routes
- end
-
include Routes.url_helpers
def test_nested_fields_for_with_child_index_option_override_on_a_nested_attributes_collection_association
diff --git a/actionview/test/template/capture_helper_test.rb b/actionview/test/template/capture_helper_test.rb
index f213da5934..1e099d482c 100644
--- a/actionview/test/template/capture_helper_test.rb
+++ b/actionview/test/template/capture_helper_test.rb
@@ -210,10 +210,4 @@ class CaptureHelperTest < ActionView::TestCase
def alt_encoding(output_buffer)
output_buffer.encoding == Encoding::US_ASCII ? Encoding::UTF_8 : Encoding::US_ASCII
end
-
- def view_with_controller
- TestController.new.view_context.tap do |view|
- view.output_buffer = ActionView::OutputBuffer.new
- end
- end
end
diff --git a/actionview/test/template/controller_helper_test.rb b/actionview/test/template/controller_helper_test.rb
new file mode 100644
index 0000000000..b5e94ea4f1
--- /dev/null
+++ b/actionview/test/template/controller_helper_test.rb
@@ -0,0 +1,21 @@
+require 'abstract_unit'
+
+class ControllerHelperTest < ActionView::TestCase
+ tests ActionView::Helpers::ControllerHelper
+
+ class SpecializedFormBuilder < ActionView::Helpers::FormBuilder ; end
+
+ def test_assign_controller_sets_default_form_builder
+ @controller = OpenStruct.new(default_form_builder: SpecializedFormBuilder)
+ assign_controller(@controller)
+
+ assert_equal SpecializedFormBuilder, self.default_form_builder
+ end
+
+ def test_assign_controller_skips_default_form_builder
+ @controller = OpenStruct.new
+ assign_controller(@controller)
+
+ assert_nil self.default_form_builder
+ end
+end
diff --git a/actionview/test/template/date_helper_test.rb b/actionview/test/template/date_helper_test.rb
index bfb073680e..9212420ec9 100644
--- a/actionview/test/template/date_helper_test.rb
+++ b/actionview/test/template/date_helper_test.rb
@@ -130,7 +130,7 @@ class DateHelperTest < ActionView::TestCase
def test_distance_in_words_with_mathn_required
# test we avoid Integer#/ (redefined by mathn)
- require 'mathn'
+ silence_warnings { require "mathn" }
from = Time.utc(2004, 6, 6, 21, 45, 0)
assert_distance_of_time_in_words(from)
end
@@ -3217,12 +3217,4 @@ class DateHelperTest < ActionView::TestCase
expected = '<time datetime="2013-02-20T00:00:00+00:00">20 Feb 00:00</time>'
assert_equal expected, time_tag(time, :format => :short)
end
-
- protected
- def with_env_tz(new_tz = 'US/Eastern')
- old_tz, ENV['TZ'] = ENV['TZ'], new_tz
- yield
- ensure
- old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
- end
end
diff --git a/actionview/test/template/form_helper_test.rb b/actionview/test/template/form_helper_test.rb
index 4e336bea63..b8cb5bd746 100644
--- a/actionview/test/template/form_helper_test.rb
+++ b/actionview/test/template/form_helper_test.rb
@@ -2878,6 +2878,23 @@ class FormHelperTest < ActionView::TestCase
assert_dom_equal expected, output_buffer
end
+ def test_nested_fields_for_with_child_index_as_lambda_option_override_on_a_nested_attributes_collection_association
+ @post.comments = []
+
+ form_for(@post) do |f|
+ concat f.fields_for(:comments, Comment.new(321), child_index: -> { 'abc' } ) { |cf|
+ concat cf.text_field(:name)
+ }
+ end
+
+ expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', method: 'patch') do
+ '<input id="post_comments_attributes_abc_name" name="post[comments_attributes][abc][name]" type="text" value="comment #321" />' +
+ '<input id="post_comments_attributes_abc_id" name="post[comments_attributes][abc][id]" type="hidden" value="321" />'
+ end
+
+ assert_dom_equal expected, output_buffer
+ end
+
class FakeAssociationProxy
def to_ary
[1, 2, 3]
@@ -3252,6 +3269,30 @@ class FormHelperTest < ActionView::TestCase
ActionView::Base.default_form_builder = old_default_form_builder
end
+ def test_form_builder_override
+ self.default_form_builder = LabelledFormBuilder
+
+ output_buffer = fields_for(:post, @post) do |f|
+ concat f.text_field(:title)
+ end
+
+ expected = "<label for='title'>Title:</label> <input name='post[title]' type='text' id='post_title' value='Hello World' /><br/>"
+
+ assert_dom_equal expected, output_buffer
+ end
+
+ def test_lazy_loading_form_builder_override
+ self.default_form_builder = "FormHelperTest::LabelledFormBuilder"
+
+ output_buffer = fields_for(:post, @post) do |f|
+ concat f.text_field(:title)
+ end
+
+ expected = "<label for='title'>Title:</label> <input name='post[title]' type='text' id='post_title' value='Hello World' /><br/>"
+
+ assert_dom_equal expected, output_buffer
+ end
+
def test_fields_for_with_labelled_builder
output_buffer = fields_for(:post, @post, builder: LabelledFormBuilder) do |f|
concat f.text_field(:title)
diff --git a/actionview/test/template/translation_helper_test.rb b/actionview/test/template/translation_helper_test.rb
index c4daaae221..df096b3c3a 100644
--- a/actionview/test/template/translation_helper_test.rb
+++ b/actionview/test/template/translation_helper_test.rb
@@ -195,6 +195,11 @@ class TranslationHelperTest < ActiveSupport::TestCase
assert_equal 'A Generic String', translation
end
+ def test_translate_with_array_of_array_default
+ translation = translate(:'translations.missing', default: [[]])
+ assert_equal [], translation
+ end
+
def test_translate_does_not_change_options
options = {}
translate(:'translations.missing', options)
diff --git a/activejob/CHANGELOG.md b/activejob/CHANGELOG.md
index d4e19274fa..85a437a1dd 100644
--- a/activejob/CHANGELOG.md
+++ b/activejob/CHANGELOG.md
@@ -1,3 +1,7 @@
+* A generated job now inherents from `app/jobs/application_job.rb` by default.
+
+ *Jeroen van Baarsen*
+
* Add an `:only` option to `perform_enqueued_jobs` to filter jobs based on
type.
diff --git a/activejob/activejob.gemspec b/activejob/activejob.gemspec
index ef8db3bcd3..24e38e495f 100644
--- a/activejob/activejob.gemspec
+++ b/activejob/activejob.gemspec
@@ -7,7 +7,7 @@ Gem::Specification.new do |s|
s.summary = 'Job framework with pluggable queues.'
s.description = 'Declare job classes that can be run by a variety of queueing backends.'
- s.required_ruby_version = '>= 2.2.1'
+ s.required_ruby_version = '>= 2.2.2'
s.license = 'MIT'
diff --git a/activejob/lib/active_job/arguments.rb b/activejob/lib/active_job/arguments.rb
index 622c37098e..f9392cf278 100644
--- a/activejob/lib/active_job/arguments.rb
+++ b/activejob/lib/active_job/arguments.rb
@@ -24,6 +24,7 @@ module ActiveJob
module Arguments
extend self
+ # :nodoc:
TYPE_WHITELIST = [ NilClass, Fixnum, Float, String, TrueClass, FalseClass, Bignum ]
# Serializes a set of arguments. Whitelisted types are returned
@@ -43,8 +44,11 @@ module ActiveJob
end
private
+ # :nodoc:
GLOBALID_KEY = '_aj_globalid'.freeze
+ # :nodoc:
SYMBOL_KEYS_KEY = '_aj_symbol_keys'.freeze
+ # :nodoc:
WITH_INDIFFERENT_ACCESS_KEY = '_aj_hash_with_indifferent_access'.freeze
private_constant :GLOBALID_KEY, :SYMBOL_KEYS_KEY, :WITH_INDIFFERENT_ACCESS_KEY
@@ -113,6 +117,7 @@ module ActiveJob
result
end
+ # :nodoc:
RESERVED_KEYS = [
GLOBALID_KEY, GLOBALID_KEY.to_sym,
SYMBOL_KEYS_KEY, SYMBOL_KEYS_KEY.to_sym,
diff --git a/activejob/lib/active_job/queue_adapters.rb b/activejob/lib/active_job/queue_adapters.rb
index b3d91dc562..bd69e525bb 100644
--- a/activejob/lib/active_job/queue_adapters.rb
+++ b/activejob/lib/active_job/queue_adapters.rb
@@ -27,13 +27,76 @@ module ActiveJob
# | Sneakers | Yes | Yes | No | Queue | Queue | No |
# | Sucker Punch | Yes | Yes | No | No | No | No |
# | Active Job Inline | No | Yes | N/A | N/A | N/A | N/A |
- # | Active Job | Yes | Yes | Yes | No | No | No |
+ #
+ # ==== Async
+ #
+ # Yes: The Queue Adapter runs the jobs in a separate or forked process.
+ #
+ # No: The job is run in the same process.
+ #
+ # ==== Queues
+ #
+ # Yes: Jobs may set which queue they are run in with queue_as or by using the set
+ # method.
+ #
+ # ==== Delayed
+ #
+ # Yes: The adapter will run the job in the future through perform_later.
+ #
+ # (Gem): An additional gem is required to use perform_later with this adapter.
+ #
+ # No: The adapter will run jobs at the next opportunity and cannot use perform_later.
+ #
+ # N/A: The adapter does not support queueing.
#
# NOTE:
- # queue_classic does not support Job scheduling. However you can implement this
- # yourself or you can use the queue_classic-later gem. See the documentation for
- # ActiveJob::QueueAdapters::QueueClassicAdapter.
+ # queue_classic does not support job scheduling.
+ # However, you can use the queue_classic-later gem.
+ # See the documentation for ActiveJob::QueueAdapters::QueueClassicAdapter.
+ #
+ # ==== Priorities
+ #
+ # The order in which jobs are processed can be configured differently depending
+ # on the adapter.
+ #
+ # Job: Any class inheriting from the adapter may set the priority on the job
+ # object relative to other jobs.
+ #
+ # Queue: The adapter can set the priority for job queues, when setting a queue
+ # with Active Job this will be respected.
+ #
+ # Yes: Allows the priority to be set on the job object, at the queue level or
+ # as default configuration option.
+ #
+ # No: Does not allow the priority of jobs to be configured.
+ #
+ # N/A: The adapter does not support queueing, and therefore sorting them.
+ #
+ # ==== Timeout
+ #
+ # When a job will stop after the allotted time.
+ #
+ # Job: The timeout can be set for each instance of the job class.
+ #
+ # Queue: The timeout is set for all jobs on the queue.
+ #
+ # Global: The adapter is configured that all jobs have a maximum run time.
+ #
+ # N/A: This adapter does not run in a separate process, and therefore timeout
+ # is unsupported.
+ #
+ # ==== Retries
+ #
+ # Job: The number of retries can be set per instance of the job class.
+ #
+ # Yes: The Number of retries can be configured globally, for each instance or
+ # on the queue. This adapter may also present failed instances of the job class
+ # that can be restarted.
+ #
+ # Global: The adapter has a global number of retries.
#
+ # N/A: The adapter does not run in a separate process, and therefore doesn't
+ # support retries.
module QueueAdapters
extend ActiveSupport::Autoload
diff --git a/activejob/lib/rails/generators/job/job_generator.rb b/activejob/lib/rails/generators/job/job_generator.rb
index 979ffcb748..86e4c5266c 100644
--- a/activejob/lib/rails/generators/job/job_generator.rb
+++ b/activejob/lib/rails/generators/job/job_generator.rb
@@ -18,7 +18,6 @@ module Rails
def create_job_file
template 'job.rb', File.join('app/jobs', class_path, "#{file_name}_job.rb")
end
-
end
end
end
diff --git a/activejob/lib/rails/generators/job/templates/job.rb b/activejob/lib/rails/generators/job/templates/job.rb
index 462c71d917..4ad2914a45 100644
--- a/activejob/lib/rails/generators/job/templates/job.rb
+++ b/activejob/lib/rails/generators/job/templates/job.rb
@@ -1,5 +1,5 @@
<% module_namespacing do -%>
-class <%= class_name %>Job < ActiveJob::Base
+class <%= class_name %>Job < ApplicationJob
queue_as :<%= options[:queue] %>
def perform(*args)
diff --git a/activejob/test/integration/queuing_test.rb b/activejob/test/integration/queuing_test.rb
index af19a92118..09f5c329cc 100644
--- a/activejob/test/integration/queuing_test.rb
+++ b/activejob/test/integration/queuing_test.rb
@@ -26,8 +26,6 @@ class QueuingTest < ActiveSupport::TestCase
test 'should supply a wrapped class name to Sidekiq' do
skip unless adapter_is?(:sidekiq)
- require 'sidekiq/testing'
-
Sidekiq::Testing.fake! do
::HelloJob.perform_later
hash = ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper.jobs.first
@@ -48,7 +46,7 @@ class QueuingTest < ActiveSupport::TestCase
test 'should run job enqueued in the future at the specified time' do
begin
- TestJob.set(wait: 3.seconds).perform_later @id
+ TestJob.set(wait: 5.seconds).perform_later @id
wait_for_jobs_to_finish_for(2.seconds)
assert_not job_executed
wait_for_jobs_to_finish_for(10.seconds)
diff --git a/activejob/test/support/integration/adapters/que.rb b/activejob/test/support/integration/adapters/que.rb
index ba7657a42a..ff5235bdc8 100644
--- a/activejob/test/support/integration/adapters/que.rb
+++ b/activejob/test/support/integration/adapters/que.rb
@@ -2,6 +2,15 @@ module QueJobsManager
def setup
require 'sequel'
ActiveJob::Base.queue_adapter = :que
+ Que.mode = :off
+ Que.worker_count = 1
+ end
+
+ def clear_jobs
+ Que.clear!
+ end
+
+ def start_workers
que_url = ENV['QUE_DATABASE_URL'] || 'postgres:///active_jobs_que_int_test'
uri = URI.parse(que_url)
user = uri.user||ENV['USER']
@@ -11,24 +20,17 @@ module QueJobsManager
%x{#{"PGPASSWORD=\"#{pass}\"" if pass} psql -c 'create database "#{db}"' -U #{user} -t template1}
Que.connection = Sequel.connect(que_url)
Que.migrate!
- Que.mode = :off
- Que.worker_count = 1
- rescue Sequel::DatabaseConnectionError
- puts "Cannot run integration tests for que. To be able to run integration tests for que you need to install and start postgresql.\n"
- exit
- end
-
- def clear_jobs
- Que.clear!
- end
- def start_workers
@thread = Thread.new do
loop do
Que::Job.work("integration_tests")
sleep 0.5
end
end
+
+ rescue Sequel::DatabaseConnectionError
+ puts "Cannot run integration tests for que. To be able to run integration tests for que you need to install and start postgresql.\n"
+ exit
end
def stop_workers
diff --git a/activejob/test/support/integration/adapters/queue_classic.rb b/activejob/test/support/integration/adapters/queue_classic.rb
index f522b2711f..29c04bf625 100644
--- a/activejob/test/support/integration/adapters/queue_classic.rb
+++ b/activejob/test/support/integration/adapters/queue_classic.rb
@@ -3,17 +3,7 @@ module QueueClassicJobsManager
ENV['QC_DATABASE_URL'] ||= 'postgres:///active_jobs_qc_int_test'
ENV['QC_RAILS_DATABASE'] = 'false'
ENV['QC_LISTEN_TIME'] = "0.5"
- uri = URI.parse(ENV['QC_DATABASE_URL'])
- user = uri.user||ENV['USER']
- pass = uri.password
- db = uri.path[1..-1]
- %x{#{"PGPASSWORD=\"#{pass}\"" if pass} psql -c 'drop database if exists "#{db}"' -U #{user} -t template1}
- %x{#{"PGPASSWORD=\"#{pass}\"" if pass} psql -c 'create database "#{db}"' -U #{user} -t template1}
ActiveJob::Base.queue_adapter = :queue_classic
- QC::Setup.create
- rescue PG::ConnectionBad
- puts "Cannot run integration tests for queue_classic. To be able to run integration tests for queue_classic you need to install and start postgresql.\n"
- exit
end
def clear_jobs
@@ -21,12 +11,24 @@ module QueueClassicJobsManager
end
def start_workers
+ uri = URI.parse(ENV['QC_DATABASE_URL'])
+ user = uri.user||ENV['USER']
+ pass = uri.password
+ db = uri.path[1..-1]
+ %x{#{"PGPASSWORD=\"#{pass}\"" if pass} psql -c 'drop database if exists "#{db}"' -U #{user} -t template1}
+ %x{#{"PGPASSWORD=\"#{pass}\"" if pass} psql -c 'create database "#{db}"' -U #{user} -t template1}
+ QC::Setup.create
+
QC.default_conn_adapter.disconnect
QC.default_conn_adapter = nil
@pid = fork do
worker = QC::Worker.new(q_name: 'integration_tests')
worker.start
end
+
+ rescue PG::ConnectionBad
+ puts "Cannot run integration tests for queue_classic. To be able to run integration tests for queue_classic you need to install and start postgresql.\n"
+ exit
end
def stop_workers
diff --git a/activejob/test/support/integration/adapters/sidekiq.rb b/activejob/test/support/integration/adapters/sidekiq.rb
index 6ff18fb56a..4988cdb33f 100644
--- a/activejob/test/support/integration/adapters/sidekiq.rb
+++ b/activejob/test/support/integration/adapters/sidekiq.rb
@@ -1,6 +1,8 @@
-require 'sidekiq/cli'
require 'sidekiq/api'
+require 'sidekiq/testing'
+Sidekiq::Testing.disable!
+
module SidekiqJobsManager
def setup
@@ -17,33 +19,71 @@ module SidekiqJobsManager
end
def start_workers
- fork do
- sidekiq = Sidekiq::CLI.instance
+ continue_read, continue_write = IO.pipe
+ death_read, death_write = IO.pipe
+
+ @pid = fork do
+ continue_read.close
+ death_write.close
+
+ # Celluloid & Sidekiq are not warning-clean :(
+ $VERBOSE = false
+
+ $stdin.reopen('/dev/null')
+ $stdout.sync = true
+ $stderr.sync = true
+
logfile = Rails.root.join("log/sidekiq.log").to_s
- pidfile = Rails.root.join("tmp/sidekiq.pid").to_s
- sidekiq.parse([ "--require", Rails.root.to_s,
- "--queue", "integration_tests",
- "--logfile", logfile,
- "--pidfile", pidfile,
- "--environment", "test",
- "--concurrency", "1",
- "--timeout", "1",
- "--daemon",
- ])
+ Sidekiq::Logging.initialize_logger(logfile)
+
+ self_read, self_write = IO.pipe
+ trap "TERM" do
+ self_write.puts("TERM")
+ end
+
+ Thread.new do
+ begin
+ death_read.read
+ rescue Exception
+ end
+ self_write.puts("TERM")
+ end
+
require 'celluloid'
- require 'sidekiq/scheduled'
+ Celluloid.logger = nil
+ require 'sidekiq/launcher'
+ sidekiq = Sidekiq::Launcher.new({queues: ["integration_tests"],
+ environment: "test",
+ concurrency: 1,
+ timeout: 1,
+ })
Sidekiq.poll_interval = 0.5
Sidekiq::Scheduled.const_set :INITIAL_WAIT, 1
- sidekiq.run
+ begin
+ sidekiq.run
+ continue_write.puts "started"
+ while readable_io = IO.select([self_read])
+ signal = readable_io.first[0].gets.strip
+ raise Interrupt if signal == "TERM"
+ end
+ rescue Interrupt
+ end
+
+ sidekiq.stop
+ exit!
end
- sleep 1
+ continue_write.close
+ death_read.close
+ @worker_lifeline = death_write
+
+ raise "Failed to start worker" unless continue_read.gets == "started\n"
end
def stop_workers
- pidfile = Rails.root.join("tmp/sidekiq.pid").to_s
- Process.kill 'TERM', File.open(pidfile).read.to_i
- FileUtils.rm_f pidfile
- rescue
+ if @pid
+ Process.kill 'TERM', @pid
+ Process.wait @pid
+ end
end
def can_run?
diff --git a/activemodel/CHANGELOG.md b/activemodel/CHANGELOG.md
index 80b42859e2..4961d69d2a 100644
--- a/activemodel/CHANGELOG.md
+++ b/activemodel/CHANGELOG.md
@@ -1,3 +1,17 @@
+* Add `ActiveModel::Dirty#[attr_name]_previously_changed?` and
+ `ActiveModel::Dirty#[attr_name]_previous_change` to improve access
+ to recorded changes after the model has been saved.
+
+ It makes the dirty-attributes query methods consistent before and after
+ saving.
+
+ *Fernando Tapia Rico*
+
+* Deprecate the `:tokenizer` option for `validates_length_of`, in favor of
+ plain Ruby.
+
+ *Sean Griffin*
+
* Deprecate `ActiveModel::Errors#add_on_empty` and `ActiveModel::Errors#add_on_blank`
with no replacement.
@@ -8,7 +22,7 @@
*Wojciech Wnętrzak*
-* Allow symbol as values for `tokenize` of `LengthValidator`
+* Allow symbol as values for `tokenize` of `LengthValidator`.
*Kensuke Naito*
@@ -35,11 +49,11 @@
cat = Cat.new
cat.assign_attributes(name: "Gorby", status: "yawning")
- cat.name # => 'Gorby'
- cat.status => 'yawning'
+ cat.name # => 'Gorby'
+ cat.status # => 'yawning'
cat.assign_attributes(status: "sleeping")
- cat.name # => 'Gorby'
- cat.status => 'sleeping'
+ cat.name # => 'Gorby'
+ cat.status # => 'sleeping'
*Bogdan Gusiev*
diff --git a/activemodel/activemodel.gemspec b/activemodel/activemodel.gemspec
index 1a16f2a1ed..8d00b3aa27 100644
--- a/activemodel/activemodel.gemspec
+++ b/activemodel/activemodel.gemspec
@@ -7,7 +7,7 @@ Gem::Specification.new do |s|
s.summary = 'A toolkit for building modeling frameworks (part of Rails).'
s.description = 'A toolkit for building modeling frameworks like Active Record. Rich support for attributes, callbacks, validations, serialization, internationalization, and testing.'
- s.required_ruby_version = '>= 2.2.1'
+ s.required_ruby_version = '>= 2.2.2'
s.license = 'MIT'
diff --git a/activemodel/lib/active_model/attribute_methods.rb b/activemodel/lib/active_model/attribute_methods.rb
index 96be551264..ff7280f9e5 100644
--- a/activemodel/lib/active_model/attribute_methods.rb
+++ b/activemodel/lib/active_model/attribute_methods.rb
@@ -23,7 +23,7 @@ module ActiveModel
# The requirements to implement <tt>ActiveModel::AttributeMethods</tt> are to:
#
# * <tt>include ActiveModel::AttributeMethods</tt> in your class.
- # * Call each of its method you want to add, such as +attribute_method_suffix+
+ # * Call each of its methods you want to add, such as +attribute_method_suffix+
# or +attribute_method_prefix+.
# * Call +define_attribute_methods+ after the other methods are called.
# * Define the various generic +_attribute+ methods that you have declared.
@@ -227,7 +227,7 @@ module ActiveModel
# Declares the attributes that should be prefixed and suffixed by
# ActiveModel::AttributeMethods.
#
- # To use, pass attribute names (as strings or symbols), be sure to declare
+ # To use, pass attribute names (as strings or symbols). Be sure to declare
# +define_attribute_methods+ after you define any prefix, suffix or affix
# methods, or they will not hook in.
#
@@ -239,7 +239,7 @@ module ActiveModel
#
# # Call to define_attribute_methods must appear after the
# # attribute_method_prefix, attribute_method_suffix or
- # # attribute_method_affix declares.
+ # # attribute_method_affix declarations.
# define_attribute_methods :name, :age, :address
#
# private
@@ -255,7 +255,7 @@ module ActiveModel
# Declares an attribute that should be prefixed and suffixed by
# ActiveModel::AttributeMethods.
#
- # To use, pass an attribute name (as string or symbol), be sure to declare
+ # To use, pass an attribute name (as string or symbol). Be sure to declare
# +define_attribute_method+ after you define any prefix, suffix or affix
# method, or they will not hook in.
#
@@ -267,7 +267,7 @@ module ActiveModel
#
# # Call to define_attribute_method must appear after the
# # attribute_method_prefix, attribute_method_suffix or
- # # attribute_method_affix declares.
+ # # attribute_method_affix declarations.
# define_attribute_method :name
#
# private
@@ -363,7 +363,7 @@ module ActiveModel
end
# Define a method `name` in `mod` that dispatches to `send`
- # using the given `extra` args. This fallbacks `define_method`
+ # using the given `extra` args. This falls back on `define_method`
# and `send` if the given names cannot be compiled.
def define_proxy_call(include_private, mod, name, send, *extra) #:nodoc:
defn = if name =~ NAME_COMPILABLE_REGEXP
@@ -419,7 +419,7 @@ module ActiveModel
# returned by <tt>attributes</tt>, as though they were first-class
# methods. So a +Person+ class with a +name+ attribute can for example use
# <tt>Person#name</tt> and <tt>Person#name=</tt> and never directly use
- # the attributes hash -- except for multiple assigns with
+ # the attributes hash -- except for multiple assignments with
# <tt>ActiveRecord::Base#attributes=</tt>.
#
# It's also possible to instantiate related objects, so a <tt>Client</tt>
diff --git a/activemodel/lib/active_model/dirty.rb b/activemodel/lib/active_model/dirty.rb
index c03e5fac79..c0fc507286 100644
--- a/activemodel/lib/active_model/dirty.rb
+++ b/activemodel/lib/active_model/dirty.rb
@@ -76,9 +76,11 @@ module ActiveModel
#
# Reset the changes:
#
- # person.previous_changes # => {"name" => ["Uncle Bob", "Bill"]}
+ # person.previous_changes # => {"name" => ["Uncle Bob", "Bill"]}
+ # person.name_previously_changed? # => true
+ # person.name_previous_change # => ["Uncle Bob", "Bill"]
# person.reload!
- # person.previous_changes # => {}
+ # person.previous_changes # => {}
#
# Rollback the changes:
#
@@ -115,6 +117,7 @@ module ActiveModel
included do
attribute_method_suffix '_changed?', '_change', '_will_change!', '_was'
+ attribute_method_suffix '_previously_changed?', '_previous_change'
attribute_method_affix prefix: 'restore_', suffix: '!'
end
@@ -179,6 +182,11 @@ module ActiveModel
attribute_changed?(attr) ? changed_attributes[attr] : __send__(attr)
end
+ # Handles <tt>*_previously_changed?</tt> for +method_missing+.
+ def attribute_previously_changed?(attr, options = {}) #:nodoc:
+ previous_changes_include?(attr)
+ end
+
# Restore all previous data of the provided attributes.
def restore_attributes(attributes = changed)
attributes.each { |attr| restore_attribute! attr }
@@ -192,6 +200,12 @@ module ActiveModel
end
alias attribute_changed_by_setter? changes_include?
+ # Returns +true+ if attr_name were changed before the model was saved,
+ # +false+ otherwise.
+ def previous_changes_include?(attr_name)
+ @previously_changed.include?(attr_name)
+ end
+
# Removes current changes and makes them accessible through +previous_changes+.
def changes_applied # :doc:
@previously_changed = changes
@@ -209,6 +223,11 @@ module ActiveModel
[changed_attributes[attr], __send__(attr)] if attribute_changed?(attr)
end
+ # Handles <tt>*_previous_change</tt> for +method_missing+.
+ def attribute_previous_change(attr)
+ @previously_changed[attr] if attribute_previously_changed?(attr)
+ end
+
# Handles <tt>*_will_change!</tt> for +method_missing+.
def attribute_will_change!(attr)
return if attribute_changed?(attr)
diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb
index e35ed03e74..f843b279ce 100644
--- a/activemodel/lib/active_model/errors.rb
+++ b/activemodel/lib/active_model/errors.rb
@@ -102,9 +102,7 @@ module ActiveModel
def include?(attribute)
messages[attribute].present?
end
- # aliases include?
alias :has_key? :include?
- # aliases include?
alias :key? :include?
# Get messages for +key+.
@@ -199,6 +197,7 @@ module ActiveModel
def size
values.flatten.size
end
+ alias :count :size
# Returns all message values.
#
@@ -216,35 +215,15 @@ module ActiveModel
messages.keys
end
- # Returns an array of error messages, with the attribute name included.
- #
- # person.errors.add(:name, :blank, message: "can't be blank")
- # person.errors.add(:name, :not_specified, message: "must be specified")
- # person.errors.to_a # => ["name can't be blank", "name must be specified"]
- def to_a
- full_messages
- end
-
- # Returns the number of error messages.
- #
- # person.errors.add(:name, :blank, message: "can't be blank")
- # person.errors.count # => 1
- # person.errors.add(:name, :not_specified, message: "must be specified")
- # person.errors.count # => 2
- def count
- to_a.size
- end
-
# Returns +true+ if no errors are found, +false+ otherwise.
# If the error message is a string it can be empty.
#
# person.errors.full_messages # => ["name cannot be nil"]
# person.errors.empty? # => false
def empty?
- all? { |k, v| v && v.empty? && !v.is_a?(String) }
+ size.zero?
end
- # aliases empty?
- alias_method :blank?, :empty?
+ alias :blank? :empty?
# Returns an xml formatted representation of the Errors hash.
#
@@ -407,6 +386,7 @@ module ActiveModel
def full_messages
map { |attribute, message| full_message(attribute, message) }
end
+ alias :to_a :full_messages
# Returns all the full error messages for a given attribute in an array.
#
diff --git a/activemodel/lib/active_model/naming.rb b/activemodel/lib/active_model/naming.rb
index 22010b517c..1f1749af4e 100644
--- a/activemodel/lib/active_model/naming.rb
+++ b/activemodel/lib/active_model/naming.rb
@@ -1,6 +1,7 @@
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/module/introspection'
require 'active_support/core_ext/module/remove_method'
+require 'active_support/core_ext/module/delegation'
module ActiveModel
class Name
diff --git a/activemodel/lib/active_model/validations.rb b/activemodel/lib/active_model/validations.rb
index 176d4c0607..c1019169e1 100644
--- a/activemodel/lib/active_model/validations.rb
+++ b/activemodel/lib/active_model/validations.rb
@@ -87,6 +87,7 @@ module ActiveModel
validates_with BlockValidator, _merge_attributes(attr_names), &block
end
+ # :nodoc:
VALID_OPTIONS_FOR_VALIDATE = [:on, :if, :unless, :prepend].freeze
# Adds a validation method or block to the class. This is useful when
@@ -401,7 +402,7 @@ module ActiveModel
protected
def run_validations! #:nodoc:
- _run_validate_callbacks
+ run_callbacks :validate
errors.empty?
end
diff --git a/activemodel/lib/active_model/validations/callbacks.rb b/activemodel/lib/active_model/validations/callbacks.rb
index 4b58ef66e3..b4301c23e4 100644
--- a/activemodel/lib/active_model/validations/callbacks.rb
+++ b/activemodel/lib/active_model/validations/callbacks.rb
@@ -109,7 +109,7 @@ module ActiveModel
# Overwrite run validations to include callbacks.
def run_validations! #:nodoc:
- _run_validation_callbacks { super }
+ run_callbacks(:validation) { super }
end
end
end
diff --git a/activemodel/lib/active_model/validations/length.rb b/activemodel/lib/active_model/validations/length.rb
index 23201b264a..c22a58f9e1 100644
--- a/activemodel/lib/active_model/validations/length.rb
+++ b/activemodel/lib/active_model/validations/length.rb
@@ -1,3 +1,5 @@
+require "active_support/core_ext/string/strip"
+
module ActiveModel
# == Active \Model Length Validator
@@ -18,6 +20,27 @@ module ActiveModel
options[:minimum] = 1
end
+ if options[:tokenizer]
+ ActiveSupport::Deprecation.warn(<<-EOS.strip_heredoc)
+ The `:tokenizer` option is deprecated, and will be removed in Rails 5.1.
+ You can achieve the same functionality by defining an instance method
+ with the value that you want to validate the length of. For example,
+
+ validates_length_of :essay, minimum: 100,
+ tokenizer: ->(str) { str.scan(/\w+/) }
+
+ should be written as
+
+ validates_length_of :words_in_essay, minimum: 100
+
+ private
+
+ def words_in_essay
+ essay.scan(/\w+/)
+ end
+ EOS
+ end
+
super
end
@@ -88,8 +111,13 @@ module ActiveModel
# validates_length_of :user_name, within: 6..20, too_long: 'pick a shorter name', too_short: 'pick a longer name'
# validates_length_of :zip_code, minimum: 5, too_short: 'please enter at least 5 characters'
# validates_length_of :smurf_leader, is: 4, message: "papa is spelled with 4 characters... don't play me."
- # validates_length_of :essay, minimum: 100, too_short: 'Your essay must be at least 100 words.',
- # tokenizer: ->(str) { str.scan(/\w+/) }
+ # validates_length_of :words_in_essay, minimum: 100, too_short: 'Your essay must be at least 100 words.'
+ #
+ # private
+ #
+ # def words_in_essay
+ # essay.scan(/\w+/)
+ # end
# end
#
# Configuration options:
@@ -112,12 +140,6 @@ module ActiveModel
# * <tt>:message</tt> - The error message to use for a <tt>:minimum</tt>,
# <tt>:maximum</tt>, or <tt>:is</tt> violation. An alias of the appropriate
# <tt>too_long</tt>/<tt>too_short</tt>/<tt>wrong_length</tt> message.
- # * <tt>:tokenizer</tt> - A method (as a symbol), proc or string to
- # specify how to split up the attribute string. (e.g.
- # <tt>tokenizer: :word_tokenizer</tt> to call the +word_tokenizer+ method
- # or <tt>tokenizer: ->(str) { str.scan(/\w+/) }</tt> to count words as in
- # above example). Defaults to <tt>->(value) { value.split(//) }</tt> which
- # counts individual characters.
#
# There is also a list of default options supported by every validator:
# +:if+, +:unless+, +:on+ and +:strict+.
diff --git a/activemodel/test/cases/dirty_test.rb b/activemodel/test/cases/dirty_test.rb
index 66ed8a350a..d17a12ad12 100644
--- a/activemodel/test/cases/dirty_test.rb
+++ b/activemodel/test/cases/dirty_test.rb
@@ -137,6 +137,19 @@ class DirtyTest < ActiveModel::TestCase
assert_equal [nil, "Jericho Cane"], @model.previous_changes['name']
end
+ test "setting new attributes should not affect previous changes" do
+ @model.name = "Jericho Cane"
+ @model.save
+ @model.name = "DudeFella ManGuy"
+ assert_equal [nil, "Jericho Cane"], @model.name_previous_change
+ end
+
+ test "saving should preserve model's previous changed status" do
+ @model.name = "Jericho Cane"
+ @model.save
+ assert @model.name_previously_changed?
+ end
+
test "previous value is preserved when changed after save" do
assert_equal({}, @model.changed_attributes)
@model.name = "Paul"
diff --git a/activemodel/test/cases/errors_test.rb b/activemodel/test/cases/errors_test.rb
index ddd003d53f..f781a0017f 100644
--- a/activemodel/test/cases/errors_test.rb
+++ b/activemodel/test/cases/errors_test.rb
@@ -212,6 +212,12 @@ class ErrorsTest < ActiveModel::TestCase
assert_equal 1, person.errors.size
end
+ test "count calculates the number of error messages" do
+ person = Person.new
+ person.errors.add(:name, "cannot be blank")
+ assert_equal 1, person.errors.count
+ end
+
test "to_a returns the list of errors with complete messages containing the attribute names" do
person = Person.new
person.errors.add(:name, "cannot be blank")
diff --git a/activemodel/test/cases/validations/length_validation_test.rb b/activemodel/test/cases/validations/length_validation_test.rb
index 209903898e..ee901b75fb 100644
--- a/activemodel/test/cases/validations/length_validation_test.rb
+++ b/activemodel/test/cases/validations/length_validation_test.rb
@@ -319,8 +319,14 @@ class LengthValidationTest < ActiveModel::TestCase
end
def test_validates_length_of_with_block
- Topic.validates_length_of :content, minimum: 5, too_short: "Your essay must be at least %{count} words.",
- tokenizer: lambda {|str| str.scan(/\w+/) }
+ assert_deprecated do
+ Topic.validates_length_of(
+ :content,
+ minimum: 5,
+ too_short: "Your essay must be at least %{count} words.",
+ tokenizer: lambda {|str| str.scan(/\w+/) },
+ )
+ end
t = Topic.new(content: "this content should be long enough")
assert t.valid?
@@ -332,8 +338,14 @@ class LengthValidationTest < ActiveModel::TestCase
def test_validates_length_of_with_symbol
- Topic.validates_length_of :content, minimum: 5, too_short: "Your essay must be at least %{count} words.",
- tokenizer: :my_word_tokenizer
+ assert_deprecated do
+ Topic.validates_length_of(
+ :content,
+ minimum: 5,
+ too_short: "Your essay must be at least %{count} words.",
+ tokenizer: :my_word_tokenizer,
+ )
+ end
t = Topic.new(content: "this content should be long enough")
assert t.valid?
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md
index be3a461eda..b6a943eca7 100644
--- a/activerecord/CHANGELOG.md
+++ b/activerecord/CHANGELOG.md
@@ -1,11 +1,79 @@
-* Add `config.active_record.warn_on_records_fetched_greater_than` option
+* Make `unscope` aware of "less than" and "greater than" conditions.
+
+ *TAKAHASHI Kazuaki*
+
+* `find_by` and `find_by!` raise `ArgumentError` when called without
+ arguments.
+
+ *Kohei Suzuki*
+
+* Revert behavior of `db:schema:load` back to loading the full
+ environment. This ensures that initializers are run.
+
+ Fixes #19545.
+
+ *Yves Senn*
+
+* Fix missing index when using `timestamps` with the `index` option.
+
+ The `index` option used with `timestamps` should be passed to both
+ `column` definitions for `created_at` and `updated_at` rather than just
+ the first.
+
+ *Paul Mucur*
+
+* Rename `:class` to `:anonymous_class` in association options.
+
+ Fixes #19659.
+
+ *Andrew White*
+
+* Autosave existing records on a has many through association when the parent
+ is new.
+
+ Fixes #19782.
+
+ *Sean Griffin*
+
+* Fixed a bug where uniqueness validations would error on out of range values,
+ even if an validation should have prevented it from hitting the database.
+
+ *Andrey Voronkov*
+
+* MySQL: `:charset` and `:collation` support for string and text columns.
+
+ Example:
+
+ create_table :foos do |t|
+ t.string :string_utf8_bin, charset: 'utf8', collation: 'utf8_bin'
+ t.text :text_ascii, charset: 'ascii'
+ end
+
+ *Ryuta Kamizono*
+
+* Foreign key related methods in the migration DSL respect
+ `ActiveRecord::Base.pluralize_table_names = false`.
+
+ Fixes #19643.
+
+ *Mehmet Emin İNAÇ*
+
+* Reduce memory usage from loading types on PostgreSQL.
+
+ Fixes #19578.
+
+ *Sean Griffin*
+
+* Add `config.active_record.warn_on_records_fetched_greater_than` option.
When set to an integer, a warning will be logged whenever a result set
- larger than the specified size is returned by a query. Fixes #16463
+ larger than the specified size is returned by a query.
+
+ Fixes #16463.
*Jason Nochlin*
-* Ignore psqlrc when loading database structure.
+* Ignore `.psqlrc` when loading database structure.
*Jason Weathered*
diff --git a/activerecord/activerecord.gemspec b/activerecord/activerecord.gemspec
index c88b9e8718..bd95b57303 100644
--- a/activerecord/activerecord.gemspec
+++ b/activerecord/activerecord.gemspec
@@ -7,7 +7,7 @@ Gem::Specification.new do |s|
s.summary = 'Object-relational mapper framework (part of Rails).'
s.description = 'Databases on Rails. Build a persistent domain model by mapping database tables to Ruby classes. Strong conventions for associations, validations, aggregations, migrations, and testing come baked-in.'
- s.required_ruby_version = '>= 2.2.1'
+ s.required_ruby_version = '>= 2.2.2'
s.license = 'MIT'
diff --git a/activerecord/lib/active_record.rb b/activerecord/lib/active_record.rb
index 58a4694880..1844b29ccb 100644
--- a/activerecord/lib/active_record.rb
+++ b/activerecord/lib/active_record.rb
@@ -49,6 +49,7 @@ module ActiveRecord
autoload :ModelSchema
autoload :NestedAttributes
autoload :NoTouching
+ autoload :TouchLater
autoload :Persistence
autoload :QueryCache
autoload :Querying
diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb
index 5e3e5f709b..c5c2178ee2 100644
--- a/activerecord/lib/active_record/associations.rb
+++ b/activerecord/lib/active_record/associations.rb
@@ -1565,10 +1565,7 @@ module ActiveRecord
#
# class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration
# def change
- # create_table :developers_projects, id: false do |t|
- # t.integer :developer_id
- # t.integer :project_id
- # end
+ # create_join_table :developers, :projects
# end
# end
#
@@ -1718,10 +1715,8 @@ module ActiveRecord
join_model = builder.through_model
- # FIXME: we should move this to the internal constants. Also people
- # should never directly access this constant so I'm not happy about
- # setting it.
const_set join_model.name, join_model
+ private_constant join_model.name
middle_reflection = builder.middle_reflection join_model
diff --git a/activerecord/lib/active_record/associations/builder/association.rb b/activerecord/lib/active_record/associations/builder/association.rb
index 88406740d8..ba1b1814d1 100644
--- a/activerecord/lib/active_record/associations/builder/association.rb
+++ b/activerecord/lib/active_record/associations/builder/association.rb
@@ -16,7 +16,7 @@ module ActiveRecord::Associations::Builder
end
self.extensions = []
- VALID_OPTIONS = [:class_name, :class, :foreign_key, :validate] # :nodoc:
+ VALID_OPTIONS = [:class_name, :anonymous_class, :foreign_key, :validate] # :nodoc:
def self.build(model, name, scope, options, &block)
if model.dangerous_attribute_method?(name)
diff --git a/activerecord/lib/active_record/associations/builder/belongs_to.rb b/activerecord/lib/active_record/associations/builder/belongs_to.rb
index ec135d49b7..97eb007f62 100644
--- a/activerecord/lib/active_record/associations/builder/belongs_to.rb
+++ b/activerecord/lib/active_record/associations/builder/belongs_to.rb
@@ -60,7 +60,7 @@ module ActiveRecord::Associations::Builder
klass.attr_readonly cache_column if klass && klass.respond_to?(:attr_readonly)
end
- def self.touch_record(o, foreign_key, name, touch) # :nodoc:
+ def self.touch_record(o, foreign_key, name, touch, touch_method) # :nodoc:
old_foreign_id = o.changed_attributes[foreign_key]
if old_foreign_id
@@ -75,9 +75,9 @@ module ActiveRecord::Associations::Builder
if old_record
if touch != true
- old_record.touch touch
+ old_record.send(touch_method, touch)
else
- old_record.touch
+ old_record.send(touch_method)
end
end
end
@@ -85,9 +85,9 @@ module ActiveRecord::Associations::Builder
record = o.send name
if record && record.persisted?
if touch != true
- record.touch touch
+ record.send(touch_method, touch)
else
- record.touch
+ record.send(touch_method)
end
end
end
@@ -98,7 +98,8 @@ module ActiveRecord::Associations::Builder
touch = reflection.options[:touch]
callback = lambda { |record|
- BelongsTo.touch_record(record, foreign_key, n, touch)
+ touch_method = touching_delayed_records? ? :touch : :touch_later
+ BelongsTo.touch_record(record, foreign_key, n, touch, touch_method)
}
model.after_save callback, if: :changed?
diff --git a/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb b/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb
index 93dc4ae118..ffd9c9d6fc 100644
--- a/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb
+++ b/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb
@@ -78,14 +78,14 @@ module ActiveRecord::Associations::Builder
join_model.table_name_resolver = habtm
join_model.class_resolver = lhs_model
- join_model.add_left_association :left_side, class: lhs_model
+ join_model.add_left_association :left_side, anonymous_class: lhs_model
join_model.add_right_association association_name, belongs_to_options(options)
join_model
end
def middle_reflection(join_model)
middle_name = [lhs_model.name.downcase.pluralize,
- association_name].join('_').gsub(/::/, '_').to_sym
+ association_name].join('_'.freeze).gsub('::'.freeze, '_'.freeze).to_sym
middle_options = middle_options join_model
HasMany.create_reflection(lhs_model,
diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb
index 88531205a1..6caadb4ce8 100644
--- a/activerecord/lib/active_record/associations/collection_association.rb
+++ b/activerecord/lib/active_record/associations/collection_association.rb
@@ -370,6 +370,8 @@ module ActiveRecord
replace_common_records_in_memory(other_array, original_target)
if other_array != original_target
transaction { replace_records(other_array, original_target) }
+ else
+ other_array
end
end
end
diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb
index 4897ec44e9..cd79266952 100644
--- a/activerecord/lib/active_record/associations/has_many_through_association.rb
+++ b/activerecord/lib/active_record/associations/has_many_through_association.rb
@@ -38,12 +38,10 @@ module ActiveRecord
def insert_record(record, validate = true, raise = false)
ensure_not_nested
- if record.new_record?
- if raise
- record.save!(:validate => validate)
- else
- return unless record.save(:validate => validate)
- end
+ if raise
+ record.save!(:validate => validate)
+ else
+ return unless record.save(:validate => validate)
end
save_through_record(record)
@@ -135,7 +133,7 @@ module ActiveRecord
if scope.klass.primary_key
count = scope.destroy_all.length
else
- scope.each(&:_run_destroy_callbacks)
+ scope.each { |record| record.run_callbacks :destroy }
arel = scope.arel
diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb
index 93550a69f1..9c5b7d937d 100644
--- a/activerecord/lib/active_record/base.rb
+++ b/activerecord/lib/active_record/base.rb
@@ -120,23 +120,22 @@ module ActiveRecord #:nodoc:
# All column values are automatically available through basic accessors on the Active Record
# object, but sometimes you want to specialize this behavior. This can be done by overwriting
# the default accessors (using the same name as the attribute) and calling
- # <tt>read_attribute(attr_name)</tt> and <tt>write_attribute(attr_name, value)</tt> to actually
- # change things.
+ # +super+ to actually change things.
#
# class Song < ActiveRecord::Base
# # Uses an integer of seconds to hold the length of the song
#
# def length=(minutes)
- # write_attribute(:length, minutes.to_i * 60)
+ # super(minutes.to_i * 60)
# end
#
# def length
- # read_attribute(:length) / 60
+ # super / 60
# end
# end
#
# You can alternatively use <tt>self[:attribute]=(value)</tt> and <tt>self[:attribute]</tt>
- # instead of <tt>write_attribute(:attribute, value)</tt> and <tt>read_attribute(:attribute)</tt>.
+ # or <tt>write_attribute(:attribute, value)</tt> and <tt>read_attribute(:attribute)</tt>.
#
# == Attribute query methods
#
@@ -309,6 +308,7 @@ module ActiveRecord #:nodoc:
include Aggregations
include Transactions
include NoTouching
+ include TouchLater
include Reflection
include Serialization
include Store
diff --git a/activerecord/lib/active_record/callbacks.rb b/activerecord/lib/active_record/callbacks.rb
index f44e5af5de..2fcba8e309 100644
--- a/activerecord/lib/active_record/callbacks.rb
+++ b/activerecord/lib/active_record/callbacks.rb
@@ -289,25 +289,24 @@ module ActiveRecord
end
def destroy #:nodoc:
- _run_destroy_callbacks { super }
+ run_callbacks(:destroy) { super }
end
def touch(*) #:nodoc:
- _run_touch_callbacks { super }
+ run_callbacks(:touch) { super }
end
private
-
def create_or_update(*) #:nodoc:
- _run_save_callbacks { super }
+ run_callbacks(:save) { super }
end
def _create_record #:nodoc:
- _run_create_callbacks { super }
+ run_callbacks(:create) { super }
end
def _update_record(*) #:nodoc:
- _run_update_callbacks { super }
+ run_callbacks(:update) { super }
end
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
index d99dc9a5db..8c50f3d1a3 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
@@ -358,7 +358,7 @@ module ActiveRecord
synchronize do
owner = conn.owner
- conn._run_checkin_callbacks do
+ conn.run_callbacks :checkin do
conn.expire
end
@@ -449,7 +449,7 @@ module ActiveRecord
end
def checkout_and_verify(c)
- c._run_checkout_callbacks do
+ c.run_callbacks :checkout do
c.verify!
end
c
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
index d2840b9498..91c7298983 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
@@ -77,7 +77,7 @@ module ActiveRecord
# Quotes a string, escaping any ' (single quote) and \ (backslash)
# characters.
def quote_string(s)
- s.gsub(/\\/, '\&\&').gsub(/'/, "''") # ' (for ruby-mode)
+ s.gsub('\\'.freeze, '\&\&'.freeze).gsub("'".freeze, "''".freeze) # ' (for ruby-mode)
end
# Quotes the column name. Defaults to no quoting.
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
index a768ee2d70..4761024ad0 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
@@ -138,7 +138,7 @@ module ActiveRecord
end
def foreign_table_name
- name.to_s.pluralize
+ Base.pluralize_table_names ? name.to_s.pluralize : name
end
end
@@ -359,6 +359,7 @@ module ActiveRecord
def column(name, type, options = {})
name = name.to_s
type = type.to_sym
+ options = options.dup
if @columns_hash[name] && @columns_hash[name].primary_key?
raise ArgumentError, "you can't redefine the primary key column '#{name}'. To define a custom primary key, pass { id: false } to create_table."
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 72e019066e..879a47f021 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
@@ -120,6 +120,8 @@ module ActiveRecord
# [<tt>:id</tt>]
# Whether to automatically add a primary key column. Defaults to true.
# Join tables for +has_and_belongs_to_many+ should set it to false.
+ #
+ # A Symbol can be used to specify the type of the generated primary key column.
# [<tt>:primary_key</tt>]
# The name of the primary key, if one is to be added automatically.
# Defaults to +id+. If <tt>:id</tt> is false this option is ignored.
@@ -163,6 +165,19 @@ module ActiveRecord
# name varchar(80)
# )
#
+ # ====== Change the primary key column type
+ #
+ # create_table(:tags, id: :string) do |t|
+ # t.column :label, :string
+ # end
+ #
+ # generates:
+ #
+ # CREATE TABLE tags (
+ # id varchar PRIMARY KEY,
+ # label varchar
+ # )
+ #
# ====== Do not add a primary key column
#
# create_table(:categories_suppliers, id: false) do |t|
@@ -377,6 +392,9 @@ module ActiveRecord
# [<tt>:force</tt>]
# Set to +:cascade+ to drop dependent objects as well.
# Defaults to false.
+ # [<tt>:if_exists</tt>]
+ # Set to +true+ to only drop the table if it exists.
+ # Defaults to false.
#
# Although this command ignores most +options+ and the block if one is given,
# it can be helpful to provide these in a migration's +change+ method so it can be reverted.
@@ -387,6 +405,10 @@ module ActiveRecord
# Adds a new column to the named table.
# See TableDefinition#column for details of the options you can use.
+ #
+ # Note: Not all options will be available, generally this command should
+ # ignore most of them. In favor of doing a low-level call to simply
+ # create a column.
def add_column(table_name, column_name, type, options = {})
at = create_alter_table table_name
at.add_column(column_name, type, options)
@@ -530,6 +552,8 @@ module ActiveRecord
#
# CREATE UNIQUE INDEX index_accounts_on_branch_id_and_party_id ON accounts(branch_id, party_id) WHERE active
#
+ # Note: Partial indexes are only supported for PostgreSQL and SQLite 3.8.0+.
+ #
# ====== Creating an index with a specific method
#
# add_index(:developers, :name, using: 'btree')
@@ -667,7 +691,10 @@ module ActiveRecord
# remove_reference(:products, :user, index: true, foreign_key: true)
#
def remove_reference(table_name, ref_name, options = {})
- remove_foreign_key table_name, ref_name.to_s.pluralize if options[:foreign_key]
+ if options[:foreign_key]
+ reference_name = Base.pluralize_table_names ? ref_name.to_s.pluralize : ref_name
+ remove_foreign_key(table_name, reference_name)
+ end
remove_column(table_name, "#{ref_name}_id")
remove_column(table_name, "#{ref_name}_type") if options[:polymorphic]
@@ -684,8 +711,8 @@ module ActiveRecord
# +to_table+ contains the referenced primary key.
#
# The foreign key will be named after the following pattern: <tt>fk_rails_<identifier></tt>.
- # +identifier+ is a 10 character long random string. A custom name can be specified with
- # the <tt>:name</tt> option.
+ # +identifier+ is a 10 character long string which is deterministically generated from the
+ # +from_table+ and +column+. A custom name can be specified with the <tt>:name</tt> option.
#
# ====== Creating a simple foreign key
#
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 b7c7ff1187..76aee452ca 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
@@ -13,6 +13,10 @@ module ActiveRecord
end
end
+ class ColumnDefinition < ActiveRecord::ConnectionAdapters::ColumnDefinition
+ attr_accessor :charset, :collation
+ end
+
class TableDefinition < ActiveRecord::ConnectionAdapters::TableDefinition
include ColumnMethods
@@ -23,8 +27,16 @@ module ActiveRecord
column.type = :integer
column.auto_increment = true
end
+ column.charset = options[:charset]
+ column.collation = options[:collation]
column
end
+
+ private
+
+ def create_column_definition(name, type)
+ ColumnDefinition.new(name, type)
+ end
end
class Table < ActiveRecord::ConnectionAdapters::Table
@@ -60,6 +72,23 @@ module ActiveRecord
add_column_position!(change_column_sql, column_options(o.column))
end
+ def column_options(o)
+ column_options = super
+ column_options[:charset] = o.charset
+ column_options[:collation] = o.collation
+ column_options
+ end
+
+ def add_column_options!(sql, options)
+ if options[:charset]
+ sql << " CHARACTER SET #{options[:charset]}"
+ end
+ if options[:collation]
+ sql << " COLLATE #{options[:collation]}"
+ end
+ super
+ end
+
def add_column_position!(sql, options)
if options[:first]
sql << " FIRST"
@@ -99,9 +128,18 @@ module ActiveRecord
spec = super
spec.delete(:precision) if /time/ === column.sql_type && column.precision == 0
spec.delete(:limit) if :boolean === column.type
+ if column.collation && table_name = column.instance_variable_get(:@table_name)
+ @collation_cache ||= {}
+ @collation_cache[table_name] ||= select_one("SHOW TABLE STATUS LIKE '#{table_name}'")["Collation"]
+ spec[:collation] = column.collation.inspect if column.collation != @collation_cache[table_name]
+ end
spec
end
+ def migration_keys
+ super + [:collation]
+ end
+
class Column < ConnectionAdapters::Column # :nodoc:
delegate :strict, :collation, :extra, to: :sql_type_metadata, allow_nil: true
@@ -562,6 +600,21 @@ module ActiveRecord
rename_table_indexes(table_name, new_name)
end
+ # Drops a table from the database.
+ #
+ # [<tt>:force</tt>]
+ # Set to +:cascade+ to drop dependent objects as well.
+ # Defaults to false.
+ # [<tt>:if_exists</tt>]
+ # Set to +true+ to only drop the table if it exists.
+ # Defaults to false.
+ # [<tt>:temporary</tt>]
+ # Set to +true+ to drop temporary table.
+ # Defaults to false.
+ #
+ # Although this command ignores most +options+ and the block if one is given,
+ # it can be helpful to provide these in a migration's +change+ method so it can be reverted.
+ # In that case, +options+ and the block will be used by create_table.
def drop_table(table_name, options = {})
execute "DROP#{' TEMPORARY' if options[:temporary]} TABLE#{' IF EXISTS' if options[:if_exists]} #{quote_table_name(table_name)}#{' CASCADE' if options[:force] == :cascade}"
end
diff --git a/activerecord/lib/active_record/connection_adapters/column.rb b/activerecord/lib/active_record/connection_adapters/column.rb
index a67127bd71..f4dda5154e 100644
--- a/activerecord/lib/active_record/connection_adapters/column.rb
+++ b/activerecord/lib/active_record/connection_adapters/column.rb
@@ -28,6 +28,7 @@ module ActiveRecord
@null = null
@default = default
@default_function = default_function
+ @table_name = nil
end
def has_default?
diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
index 45b935f1d6..18febf66b4 100644
--- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
@@ -5,8 +5,10 @@ require 'active_support/core_ext/hash/keys'
gem 'mysql', '~> 2.9'
require 'mysql'
-class 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
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb
index 9d421d6975..191c828e60 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb
@@ -15,10 +15,10 @@ module ActiveRecord
def run(records)
nodes = records.reject { |row| @store.key? row['oid'].to_i }
mapped, nodes = nodes.partition { |row| @store.key? row['typname'] }
- ranges, nodes = nodes.partition { |row| row['typtype'] == 'r' }
- enums, nodes = nodes.partition { |row| row['typtype'] == 'e' }
- domains, nodes = nodes.partition { |row| row['typtype'] == 'd' }
- arrays, nodes = nodes.partition { |row| row['typinput'] == 'array_in' }
+ ranges, nodes = nodes.partition { |row| row['typtype'] == 'r'.freeze }
+ enums, nodes = nodes.partition { |row| row['typtype'] == 'e'.freeze }
+ domains, nodes = nodes.partition { |row| row['typtype'] == 'd'.freeze }
+ arrays, nodes = nodes.partition { |row| row['typinput'] == 'array_in'.freeze }
composites, nodes = nodes.partition { |row| row['typelem'].to_i != 0 }
mapped.each { |row| register_mapped_type(row) }
@@ -29,6 +29,18 @@ module ActiveRecord
composites.each { |row| register_composite_type(row) }
end
+ def query_conditions_for_initial_load(type_map)
+ known_type_names = type_map.keys.map { |n| "'#{n}'" }
+ known_type_types = %w('r' 'e' 'd')
+ <<-SQL % [known_type_names.join(", "), known_type_types.join(", ")]
+ WHERE
+ t.typname IN (%s)
+ OR t.typtype IN (%s)
+ OR t.typinput::varchar = 'array_in'
+ OR t.typelem != 0
+ SQL
+ end
+
private
def register_mapped_type(row)
alias_type row['oid'], row['typname']
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
index cb0b9cdbe9..168180cfd3 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
@@ -87,7 +87,7 @@ module ActiveRecord
SQL
end
- def drop_table(table_name, options = {})
+ def drop_table(table_name, options = {}) # :nodoc:
execute "DROP TABLE#{' IF EXISTS' if options[:if_exists]} #{quote_table_name(table_name)}#{' CASCADE' if options[:force] == :cascade}"
end
@@ -422,7 +422,7 @@ module ActiveRecord
end
# Changes the default value of a table column.
- def change_column_default(table_name, column_name, default)
+ def change_column_default(table_name, column_name, default) # :nodoc:
clear_cache!
column = column_for(table_name, column_name)
return unless column
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
index e616cee5eb..332ac9d88c 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
@@ -568,9 +568,9 @@ module ActiveRecord
case default
# Quoted types
when /\A[\(B]?'(.*)'::/m
- $1.gsub(/''/, "'")
+ $1.gsub("''".freeze, "'".freeze)
# Boolean types
- when 'true', 'false'
+ when 'true'.freeze, 'false'.freeze
default
# Numeric types
when /\A\(?(-?\d+(\.\d*)?)\)?(::bigint)?\z/
@@ -594,6 +594,8 @@ module ActiveRecord
end
def load_additional_types(type_map, oids = nil) # :nodoc:
+ initializer = OID::TypeMapInitializer.new(type_map)
+
if supports_ranges?
query = <<-SQL
SELECT t.oid, t.typname, t.typelem, t.typdelim, t.typinput, r.rngsubtype, t.typtype, t.typbasetype
@@ -609,11 +611,13 @@ module ActiveRecord
if oids
query += "WHERE t.oid::integer IN (%s)" % oids.join(", ")
+ else
+ query += initializer.query_conditions_for_initial_load(type_map)
end
- initializer = OID::TypeMapInitializer.new(type_map)
- records = execute(query, 'SCHEMA')
- initializer.run(records)
+ execute_and_clear(query, 'SCHEMA', []) do |records|
+ initializer.run(records)
+ end
end
FEATURE_NOT_SUPPORTED = "0A000" #:nodoc:
@@ -823,9 +827,11 @@ module ActiveRecord
'float8' => PG::TextDecoder::Float,
'bool' => PG::TextDecoder::Boolean,
}
- query = <<-SQL
+ known_coder_types = coders_by_name.keys.map { |n| quote(n) }
+ query = <<-SQL % known_coder_types.join(", ")
SELECT t.oid, t.typname
FROM pg_type as t
+ WHERE t.typname IN (%s)
SQL
coders = execute_and_clear(query, "SCHEMA", []) do |result|
result
diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb
index a17eb226f4..1ad910c4bc 100644
--- a/activerecord/lib/active_record/core.rb
+++ b/activerecord/lib/active_record/core.rb
@@ -96,10 +96,10 @@ module ActiveRecord
##
# :singleton-method:
- # Specify a threshold for the size of query result sets. If the
- # number of records in the set exceeds threshold, a warning is
- # logged. This should be used to identify queries which pull
- # thousands of records, which may cause memory bloat.
+ # Specify a threshold for the size of query result sets. If the number of
+ # records in the set exceeds the threshold, a warning is logged. This can
+ # be used to identify queries which load thousands of records and
+ # potentially cause memory bloat.
mattr_accessor :warn_on_records_fetched_greater_than, instance_writer: false
self.warn_on_records_fetched_greater_than = nil
@@ -302,18 +302,22 @@ module ActiveRecord
assign_attributes(attributes) if attributes
yield self if block_given?
- _run_initialize_callbacks
+ run_callbacks :initialize
end
- # Initialize an empty model object from +coder+. +coder+ must contain
- # the attributes necessary for initializing an empty model object. For
- # example:
+ # Initialize an empty model object from +coder+. +coder+ should be
+ # the result of previously encoding an Active Record model, using
+ # `encode_with`
#
# class Post < ActiveRecord::Base
# end
#
+ # old_post = Post.new(title: "hello world")
+ # coder = {}
+ # old_post.encode_with(coder)
+ #
# post = Post.allocate
- # post.init_with('attributes' => { 'title' => 'hello world' })
+ # post.init_with(coder)
# post.title # => 'hello world'
def init_with(coder)
coder = LegacyYamlAdapter.convert(self.class, coder)
@@ -325,8 +329,8 @@ module ActiveRecord
self.class.define_attribute_methods
- _run_find_callbacks
- _run_initialize_callbacks
+ run_callbacks :find
+ run_callbacks :initialize
self
end
@@ -362,7 +366,7 @@ module ActiveRecord
@attributes = @attributes.dup
@attributes.reset(self.class.primary_key)
- _run_initialize_callbacks
+ run_callbacks(:initialize)
@new_record = true
@destroyed = false
diff --git a/activerecord/lib/active_record/enum.rb b/activerecord/lib/active_record/enum.rb
index ea88983917..2b99899e42 100644
--- a/activerecord/lib/active_record/enum.rb
+++ b/activerecord/lib/active_record/enum.rb
@@ -32,7 +32,7 @@ module ActiveRecord
# Conversation.active
# Conversation.archived
#
- # Of course, you can also query them directly if the scopes doesn't fit your
+ # Of course, you can also query them directly if the scopes don't fit your
# needs:
#
# Conversation.where(status: [:active, :archived])
diff --git a/activerecord/lib/active_record/log_subscriber.rb b/activerecord/lib/active_record/log_subscriber.rb
index 6b26d7be78..af816a278e 100644
--- a/activerecord/lib/active_record/log_subscriber.rb
+++ b/activerecord/lib/active_record/log_subscriber.rb
@@ -31,9 +31,10 @@ module ActiveRecord
end
def sql(event)
- self.class.runtime += event.duration
return unless logger.debug?
+ self.class.runtime += event.duration
+
payload = event.payload
return if IGNORE_PAYLOAD_NAMES.include?(payload[:name])
diff --git a/activerecord/lib/active_record/model_schema.rb b/activerecord/lib/active_record/model_schema.rb
index 75adcccce6..3674f672cb 100644
--- a/activerecord/lib/active_record/model_schema.rb
+++ b/activerecord/lib/active_record/model_schema.rb
@@ -328,12 +328,8 @@ module ActiveRecord
@default_attributes = nil
@inheritance_column = nil unless defined?(@explicit_inheritance_column) && @explicit_inheritance_column
@attributes_builder = nil
- @column_names = nil
- @attribute_types = nil
@columns = nil
@columns_hash = nil
- @content_columns = nil
- @default_attributes = nil
@attribute_names = nil
end
diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb
index a6176dffdb..da8f4d027a 100644
--- a/activerecord/lib/active_record/persistence.rb
+++ b/activerecord/lib/active_record/persistence.rb
@@ -205,7 +205,9 @@ module ActiveRecord
# instance using the companies/company partial instead of clients/client.
#
# Note: The new instance will share a link to the same attributes as the original class.
- # So any change to the attributes in either instance will affect the other.
+ # Therefore the sti column value will still be the same.
+ # Any change to the attributes on either instance will affect both instances.
+ # If you want to change the sti column as well, use +becomes!+ instead.
def becomes(klass)
became = klass.new
became.instance_variable_set("@attributes", @attributes)
@@ -428,7 +430,7 @@ module ActiveRecord
self
end
- # Saves the record with the updated_at/on attributes set to the current time
+ # Saves the record with the updated_at/on attributes set to the current time
# or the time specified.
# Please note that no validation is performed and only the +after_touch+,
# +after_commit+ and +after_rollback+ callbacks are executed.
@@ -462,9 +464,10 @@ module ActiveRecord
# ball = Ball.new
# ball.touch(:updated_at) # => raises ActiveRecordError
#
- def touch(*names, time: current_time_from_proper_timezone)
+ def touch(*names, time: nil)
raise ActiveRecordError, "cannot touch on a new record object" unless persisted?
+ time ||= current_time_from_proper_timezone
attributes = timestamp_attributes_for_update_in_model
attributes.concat(names)
@@ -476,11 +479,23 @@ module ActiveRecord
changes[column] = write_attribute(column, time)
end
- changes[self.class.locking_column] = increment_lock if locking_enabled?
-
clear_attribute_changes(changes.keys)
primary_key = self.class.primary_key
- self.class.unscoped.where(primary_key => self[primary_key]).update_all(changes) == 1
+ scope = self.class.unscoped.where(primary_key => _read_attribute(primary_key))
+
+ if locking_enabled?
+ locking_column = self.class.locking_column
+ scope = scope.where(locking_column => _read_attribute(locking_column))
+ changes[locking_column] = increment_lock
+ end
+
+ result = scope.update_all(changes) == 1
+
+ if !result && locking_enabled?
+ raise ActiveRecord::StaleObjectError.new(self, "touch")
+ end
+
+ result
else
true
end
diff --git a/activerecord/lib/active_record/railties/controller_runtime.rb b/activerecord/lib/active_record/railties/controller_runtime.rb
index af4840476c..8727e46cb3 100644
--- a/activerecord/lib/active_record/railties/controller_runtime.rb
+++ b/activerecord/lib/active_record/railties/controller_runtime.rb
@@ -19,7 +19,7 @@ module ActiveRecord
end
def cleanup_view_runtime
- if ActiveRecord::Base.connected?
+ if logger.info? && ActiveRecord::Base.connected?
db_rt_before_render = ActiveRecord::LogSubscriber.reset_runtime
self.db_runtime = (db_runtime || 0) + db_rt_before_render
runtime = super
diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake
index 2591e7492d..d168786e71 100644
--- a/activerecord/lib/active_record/railties/databases.rake
+++ b/activerecord/lib/active_record/railties/databases.rake
@@ -240,7 +240,7 @@ db_namespace = namespace :db do
end
desc 'Load a schema.rb file into the database'
- task :load => [:load_config] do
+ task :load => [:environment, :load_config] do
ActiveRecord::Tasks::DatabaseTasks.load_schema_current(:ruby, ENV['SCHEMA'])
end
diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb
index 4265afc0a5..1b0ae2c942 100644
--- a/activerecord/lib/active_record/reflection.rb
+++ b/activerecord/lib/active_record/reflection.rb
@@ -196,7 +196,7 @@ module ActiveRecord
@scope = scope
@options = options
@active_record = active_record
- @klass = options[:class]
+ @klass = options[:anonymous_class]
@plural_name = active_record.pluralize_table_names ?
name.to_s.pluralize : name.to_s
end
@@ -635,7 +635,7 @@ module ActiveRecord
def initialize(delegate_reflection)
@delegate_reflection = delegate_reflection
- @klass = delegate_reflection.options[:class]
+ @klass = delegate_reflection.options[:anonymous_class]
@source_reflection_name = delegate_reflection.options[:source]
end
diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb
index 8f16de3519..402b317d9c 100644
--- a/activerecord/lib/active_record/relation/calculations.rb
+++ b/activerecord/lib/active_record/relation/calculations.rb
@@ -130,9 +130,9 @@ module ActiveRecord
# the plucked column names, if they can be deduced. Plucking an SQL fragment
# returns String values by default.
#
- # Person.pluck(:id)
- # # SELECT people.id FROM people
- # # => [1, 2, 3]
+ # Person.pluck(:name)
+ # # SELECT people.name FROM people
+ # # => ['David', 'Jeremy', 'Jose']
#
# Person.pluck(:id, :name)
# # SELECT people.id, people.name FROM people
@@ -150,6 +150,8 @@ module ActiveRecord
# # SELECT DATEDIFF(updated_at, created_at) FROM people
# # => ['0', '27761', '173']
#
+ # See also +ids+.
+ #
def pluck(*column_names)
column_names.map! do |column_name|
if column_name.is_a?(Symbol) && attribute_alias?(column_name)
diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb
index 3f747a20b3..576a32bf75 100644
--- a/activerecord/lib/active_record/relation/finder_methods.rb
+++ b/activerecord/lib/active_record/relation/finder_methods.rb
@@ -5,7 +5,7 @@ module ActiveRecord
ONE_AS_ONE = '1 AS one'
# Find by id - This can either be a specific id (1), a list of ids (1, 5, 6), or an array of ids ([5, 6, 10]).
- # If no record can be found for all of the listed ids, then RecordNotFound will be raised. If the primary key
+ # If one or more records can not be found for the requested ids, then RecordNotFound will be raised. If the primary key
# is an integer, find by id coerces its arguments using +to_i+.
#
# Person.find(1) # returns the object for ID = 1
@@ -16,8 +16,6 @@ module ActiveRecord
# Person.find([1]) # returns an array for the object with ID = 1
# Person.where("administrator = 1").order("created_on DESC").find(1)
#
- # <tt>ActiveRecord::RecordNotFound</tt> will be raised if one or more ids are not found.
- #
# NOTE: The returned records may not be in the same order as the ids you
# provide since database rows are unordered. You'd need to provide an explicit <tt>order</tt>
# option if you want the results are sorted.
@@ -79,16 +77,16 @@ module ActiveRecord
#
# Post.find_by name: 'Spartacus', rating: 4
# Post.find_by "published_at < ?", 2.weeks.ago
- def find_by(*args)
- where(*args).take
+ def find_by(arg, *args)
+ where(arg, *args).take
rescue RangeError
nil
end
# Like <tt>find_by</tt>, except that if no record is found, raises
# an <tt>ActiveRecord::RecordNotFound</tt> error.
- def find_by!(*args)
- where(*args).take!
+ def find_by!(arg, *args)
+ where(arg, *args).take!
rescue RangeError
raise RecordNotFound, "Couldn't find #{@klass.name} with an out of range value"
end
diff --git a/activerecord/lib/active_record/relation/record_fetch_warning.rb b/activerecord/lib/active_record/relation/record_fetch_warning.rb
index 0d31f73ddd..14e1bf89fa 100644
--- a/activerecord/lib/active_record/relation/record_fetch_warning.rb
+++ b/activerecord/lib/active_record/relation/record_fetch_warning.rb
@@ -5,9 +5,8 @@ module ActiveRecord
# `config.active_record.warn_on_records_fetched_greater_than` is
# set to an integer, if the number of records a query returns is
# greater than the value of `warn_on_records_fetched_greater_than`,
- # a warning is logged. This allows for the dection of queries that
- # return a large number of records, which could cause memory
- # bloat.
+ # a warning is logged. This allows for the detection of queries that
+ # return a large number of records, which could cause memory bloat.
#
# In most cases, fetching large number of records can be performed
# efficiently using the ActiveRecord::Batches methods.
diff --git a/activerecord/lib/active_record/schema_dumper.rb b/activerecord/lib/active_record/schema_dumper.rb
index da95920571..eaeaf0321b 100644
--- a/activerecord/lib/active_record/schema_dumper.rb
+++ b/activerecord/lib/active_record/schema_dumper.rb
@@ -105,7 +105,10 @@ HEADER
end
def table(table, stream)
- columns = @connection.columns(table)
+ columns = @connection.columns(table).map do |column|
+ column.instance_variable_set(:@table_name, table)
+ column
+ end
begin
tbl = StringIO.new
diff --git a/activerecord/lib/active_record/scoping/default.rb b/activerecord/lib/active_record/scoping/default.rb
index 5ec2c88b47..3590b8846e 100644
--- a/activerecord/lib/active_record/scoping/default.rb
+++ b/activerecord/lib/active_record/scoping/default.rb
@@ -35,7 +35,7 @@ module ActiveRecord
# Are there attributes associated with this scope?
def scope_attributes? # :nodoc:
- super || default_scopes.any?
+ super || default_scopes.any? || respond_to?(:default_scope)
end
def before_remove_const #:nodoc:
diff --git a/activerecord/lib/active_record/touch_later.rb b/activerecord/lib/active_record/touch_later.rb
new file mode 100644
index 0000000000..4352a0ffea
--- /dev/null
+++ b/activerecord/lib/active_record/touch_later.rb
@@ -0,0 +1,50 @@
+module ActiveRecord
+ # = Active Record Touch Later
+ module TouchLater
+ extend ActiveSupport::Concern
+
+ included do
+ before_commit_without_transaction_enrollment :touch_deferred_attributes
+ end
+
+ def touch_later(*names) # :nodoc:
+ raise ActiveRecordError, "cannot touch on a new record object" unless persisted?
+
+ @_defer_touch_attrs ||= timestamp_attributes_for_update_in_model
+ @_defer_touch_attrs |= names
+ @_touch_time = current_time_from_proper_timezone
+
+ surreptitiously_touch @_defer_touch_attrs
+ self.class.connection.add_transaction_record self
+ end
+
+ def touch(*names, time: nil) # :nodoc:
+ if has_defer_touch_attrs?
+ names |= @_defer_touch_attrs
+ end
+ super(*names, time: time)
+ end
+
+ private
+ def surreptitiously_touch(attrs)
+ attrs.each { |attr| write_attribute attr, @_touch_time }
+ clear_attribute_changes attrs
+ end
+
+ def touch_deferred_attributes
+ if has_defer_touch_attrs? && persisted?
+ @_touching_delayed_records = true
+ touch(*@_defer_touch_attrs, time: @_touch_time)
+ @_touching_delayed_records, @_defer_touch_attrs, @_touch_time = nil, nil, nil
+ end
+ end
+
+ def has_defer_touch_attrs?
+ defined?(@_defer_touch_attrs) && @_defer_touch_attrs.present?
+ end
+
+ def touching_delayed_records?
+ defined?(@_touching_delayed_records) && @_touching_delayed_records
+ end
+ end
+end
diff --git a/activerecord/lib/active_record/transactions.rb b/activerecord/lib/active_record/transactions.rb
index 2293d1b258..311dacb449 100644
--- a/activerecord/lib/active_record/transactions.rb
+++ b/activerecord/lib/active_record/transactions.rb
@@ -319,8 +319,8 @@ module ActiveRecord
end
def before_committed! # :nodoc:
- _run_before_commit_without_transaction_enrollment_callbacks
- _run_before_commit_callbacks
+ run_callbacks :before_commit_without_transaction_enrollment
+ run_callbacks :before_commit
end
# Call the +after_commit+ callbacks.
@@ -329,8 +329,8 @@ module ActiveRecord
# but call it after the commit of a destroyed object.
def committed!(should_run_callbacks: true) #:nodoc:
if should_run_callbacks && destroyed? || persisted?
- _run_commit_without_transaction_enrollment_callbacks
- _run_commit_callbacks
+ run_callbacks :commit_without_transaction_enrollment
+ run_callbacks :commit
end
ensure
force_clear_transaction_record_state
@@ -340,8 +340,8 @@ module ActiveRecord
# state should be rolled back to the beginning or just to the last savepoint.
def rolledback!(force_restore_state: false, should_run_callbacks: true) #:nodoc:
if should_run_callbacks
- _run_rollback_without_transaction_enrollment_callbacks
- _run_rollback_callbacks
+ run_callbacks :rollback
+ run_callbacks :rollback_without_transaction_enrollment
end
ensure
restore_transaction_record_state(force_restore_state)
diff --git a/activerecord/lib/active_record/type/hash_lookup_type_map.rb b/activerecord/lib/active_record/type/hash_lookup_type_map.rb
index 82d9327fc0..3b01e3f8ca 100644
--- a/activerecord/lib/active_record/type/hash_lookup_type_map.rb
+++ b/activerecord/lib/active_record/type/hash_lookup_type_map.rb
@@ -1,12 +1,18 @@
module ActiveRecord
module Type
class HashLookupTypeMap < TypeMap # :nodoc:
- delegate :key?, to: :@mapping
-
def alias_type(type, alias_type)
register_type(type) { |_, *args| lookup(alias_type, *args) }
end
+ def key?(key)
+ @mapping.key?(key)
+ end
+
+ def keys
+ @mapping.keys
+ end
+
private
def perform_fetch(type, *args, &block)
diff --git a/activerecord/lib/active_record/validations/presence.rb b/activerecord/lib/active_record/validations/presence.rb
index 75d5bd5a35..a9b791397b 100644
--- a/activerecord/lib/active_record/validations/presence.rb
+++ b/activerecord/lib/active_record/validations/presence.rb
@@ -43,6 +43,10 @@ module ActiveRecord
# deletes the associated object, thus putting the parent object into an invalid
# state.
#
+ # NOTE: This validation will not fail while using it with an association
+ # if the latter was assigned but not valid. If you want to ensure that
+ # it is both present and valid, you also need to use +validates_associated+.
+ #
# Configuration options:
# * <tt>:message</tt> - A custom error message (default is: "can't be blank").
# * <tt>:on</tt> - Specifies the contexts where this validation is active.
diff --git a/activerecord/lib/active_record/validations/uniqueness.rb b/activerecord/lib/active_record/validations/uniqueness.rb
index 9be4b10a55..5106f4e127 100644
--- a/activerecord/lib/active_record/validations/uniqueness.rb
+++ b/activerecord/lib/active_record/validations/uniqueness.rb
@@ -76,6 +76,8 @@ module ActiveRecord
klass.connection.case_sensitive_comparison(table, attribute, column, value)
end
klass.unscoped.where(comparison)
+ rescue RangeError
+ klass.none
end
def scope_relation(record, table, relation)
diff --git a/activerecord/test/cases/adapters/mysql/charset_collation_test.rb b/activerecord/test/cases/adapters/mysql/charset_collation_test.rb
new file mode 100644
index 0000000000..c8dd49d00a
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql/charset_collation_test.rb
@@ -0,0 +1,54 @@
+require "cases/helper"
+require 'support/schema_dumping_helper'
+
+class CharsetCollationTest < ActiveRecord::TestCase
+ 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/mysql2/charset_collation_test.rb b/activerecord/test/cases/adapters/mysql2/charset_collation_test.rb
new file mode 100644
index 0000000000..c8dd49d00a
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql2/charset_collation_test.rb
@@ -0,0 +1,54 @@
+require "cases/helper"
+require 'support/schema_dumping_helper'
+
+class CharsetCollationTest < ActiveRecord::TestCase
+ 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/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb
index 47fd7345c8..ba90c61d65 100644
--- a/activerecord/test/cases/associations/belongs_to_associations_test.rb
+++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb
@@ -124,9 +124,9 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
where("id = :inc", :inc => counter)
}
- has_many :comments, :class => comments
+ has_many :comments, :anonymous_class => comments
}
- belongs_to :post, :class => posts, :inverse_of => false
+ belongs_to :post, :anonymous_class => posts, :inverse_of => false
}
assert_equal 0, counter
@@ -422,6 +422,24 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
assert_queries(1) { line_item.touch }
end
+ def test_belongs_to_with_touch_on_multiple_records
+ line_item = LineItem.create!(amount: 1)
+ line_item2 = LineItem.create!(amount: 2)
+ Invoice.create!(line_items: [line_item, line_item2])
+
+ assert_queries(1) do
+ LineItem.transaction do
+ line_item.touch
+ line_item2.touch
+ end
+ end
+
+ assert_queries(2) do
+ line_item.touch
+ line_item2.touch
+ end
+ end
+
def test_belongs_to_with_touch_option_on_touch_without_updated_at_attributes
assert_not LineItem.column_names.include?("updated_at")
diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb
index 7d8b933992..0ecf2ddfd1 100644
--- a/activerecord/test/cases/associations/eager_test.rb
+++ b/activerecord/test/cases/associations/eager_test.rb
@@ -759,6 +759,23 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
end
+ def test_eager_with_default_scope_as_class_method_using_find_method
+ david = developers(:david)
+ developer = EagerDeveloperWithClassMethodDefaultScope.find(david.id)
+ projects = Project.order(:id).to_a
+ assert_no_queries do
+ assert_equal(projects, developer.projects)
+ end
+ end
+
+ def test_eager_with_default_scope_as_class_method_using_find_by_method
+ developer = EagerDeveloperWithClassMethodDefaultScope.find_by(name: 'David')
+ projects = Project.order(:id).to_a
+ assert_no_queries do
+ assert_equal(projects, developer.projects)
+ end
+ end
+
def test_eager_with_default_scope_as_lambda
developer = EagerDeveloperWithLambdaDefaultScope.where(:name => 'David').first
projects = Project.order(:id).to_a
diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb
index 290b2a0d6b..14cdf37f46 100644
--- a/activerecord/test/cases/associations/has_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -119,9 +119,9 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
developer_project = Class.new(ActiveRecord::Base) {
self.table_name = 'developers_projects'
- belongs_to :developer, :class => dev
+ belongs_to :developer, :anonymous_class => dev
}
- has_many :developer_projects, :class => developer_project, :foreign_key => 'developer_id'
+ has_many :developer_projects, :anonymous_class => developer_project, :foreign_key => 'developer_id'
}
dev = developer.first
named = Developer.find(dev.id)
@@ -140,13 +140,13 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
comments = Class.new(ActiveRecord::Base) {
self.table_name = 'comments'
self.inheritance_column = 'not_there'
- belongs_to :post, :class => post
+ belongs_to :post, :anonymous_class => post
default_scope -> {
counter += 1
where("id = :inc", :inc => counter)
}
}
- has_many :comments, :class => comments, :foreign_key => 'post_id'
+ has_many :comments, :anonymous_class => comments, :foreign_key => 'post_id'
}
assert_equal 0, counter
post = posts.first
@@ -1503,6 +1503,8 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_queries(0, ignore_none: true) do
firm.clients = []
end
+
+ assert_equal [], firm.send('clients=', [])
end
def test_transactions_when_replacing_on_persisted
diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb
index 5f52c65412..9734ea2217 100644
--- a/activerecord/test/cases/associations/has_many_through_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb
@@ -84,11 +84,11 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
subscriber = make_model "Subscriber"
subscriber.primary_key = 'nick'
- subscription.belongs_to :book, class: book
- subscription.belongs_to :subscriber, class: subscriber
+ subscription.belongs_to :book, anonymous_class: book
+ subscription.belongs_to :subscriber, anonymous_class: subscriber
- book.has_many :subscriptions, class: subscription
- book.has_many :subscribers, through: :subscriptions, class: subscriber
+ book.has_many :subscriptions, anonymous_class: subscription
+ book.has_many :subscribers, through: :subscriptions, anonymous_class: subscriber
anonbook = book.first
namebook = Book.find anonbook.id
@@ -154,10 +154,10 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
lesson_student = make_model 'LessonStudent'
lesson_student.table_name = 'lessons_students'
- lesson_student.belongs_to :lesson, :class => lesson
- lesson_student.belongs_to :student, :class => student
- lesson.has_many :lesson_students, :class => lesson_student
- lesson.has_many :students, :through => :lesson_students, :class => student
+ lesson_student.belongs_to :lesson, :anonymous_class => lesson
+ lesson_student.belongs_to :student, :anonymous_class => student
+ lesson.has_many :lesson_students, :anonymous_class => lesson_student
+ lesson.has_many :students, :through => :lesson_students, :anonymous_class => student
[lesson, lesson_student, student]
end
diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb
index 8f0d7bd037..80b5a0004d 100644
--- a/activerecord/test/cases/autosave_association_test.rb
+++ b/activerecord/test/cases/autosave_association_test.rb
@@ -43,7 +43,7 @@ class TestAutosaveAssociationsInGeneral < ActiveRecord::TestCase
reference = Class.new(ActiveRecord::Base) {
self.table_name = "references"
def self.name; 'Reference'; end
- belongs_to :person, autosave: true, class: person
+ belongs_to :person, autosave: true, anonymous_class: person
}
u = person.create!(first_name: 'cool')
@@ -1278,6 +1278,16 @@ module AutosaveAssociationOnACollectionAssociationTests
assert_equal new_names, @pirate.reload.send(@association_name).map(&:name)
end
+ def test_should_update_children_when_autosave_is_true_and_parent_is_new_but_child_is_not
+ parrot = Parrot.create!(name: "Polly")
+ parrot.name = "Squawky"
+ pirate = Pirate.new(parrots: [parrot], catchphrase: "Arrrr")
+
+ pirate.save!
+
+ assert_equal "Squawky", parrot.reload.name
+ end
+
def test_should_automatically_validate_the_associated_models
@pirate.send(@association_name).each { |child| child.name = '' }
diff --git a/activerecord/test/cases/batches_test.rb b/activerecord/test/cases/batches_test.rb
index 9e428098e4..0791dde1f2 100644
--- a/activerecord/test/cases/batches_test.rb
+++ b/activerecord/test/cases/batches_test.rb
@@ -190,8 +190,9 @@ class EachTest < ActiveRecord::TestCase
def test_find_in_batches_should_use_any_column_as_primary_key_when_start_is_not_specified
assert_queries(Subscriber.count + 1) do
- Subscriber.find_each(:batch_size => 1) do |subscriber|
- assert_kind_of Subscriber, subscriber
+ Subscriber.find_in_batches(batch_size: 1) do |batch|
+ assert_kind_of Array, batch
+ assert_kind_of Subscriber, batch.first
end
end
end
diff --git a/activerecord/test/cases/connection_management_test.rb b/activerecord/test/cases/connection_management_test.rb
index f53c496ecd..bab624b78a 100644
--- a/activerecord/test/cases/connection_management_test.rb
+++ b/activerecord/test/cases/connection_management_test.rb
@@ -110,7 +110,7 @@ module ActiveRecord
assert ActiveRecord::Base.connection_handler.active_connections?
end
- test "proxy is polite to it's body and responds to it" do
+ test "proxy is polite to its body and responds to it" do
body = Class.new(String) { def to_path; "/path"; end }.new
app = lambda { |_| [200, {}, body] }
response_body = ConnectionManagement.new(app).call(@env)[2]
diff --git a/activerecord/test/cases/connection_pool_test.rb b/activerecord/test/cases/connection_pool_test.rb
index 8d15a76735..aa50efc979 100644
--- a/activerecord/test/cases/connection_pool_test.rb
+++ b/activerecord/test/cases/connection_pool_test.rb
@@ -204,13 +204,13 @@ module ActiveRecord
end
# The connection pool is "fair" if threads waiting for
- # connections receive them the order in which they began
+ # connections receive them in the order in which they began
# waiting. This ensures that we don't timeout one HTTP request
# even while well under capacity in a multi-threaded environment
# such as a Java servlet container.
#
# We don't need strict fairness: if two connections become
- # available at the same time, it's fine of two threads that were
+ # available at the same time, it's fine if two threads that were
# waiting acquire the connections out of order.
#
# Thus this test prepares waiting threads and then trickles in
diff --git a/activerecord/test/cases/disconnected_test.rb b/activerecord/test/cases/disconnected_test.rb
index 55f0e51717..c25089a420 100644
--- a/activerecord/test/cases/disconnected_test.rb
+++ b/activerecord/test/cases/disconnected_test.rb
@@ -21,7 +21,9 @@ class TestDisconnectedAdapter < ActiveRecord::TestCase
@connection.execute "SELECT count(*) from products"
@connection.disconnect!
assert_raises(ActiveRecord::StatementInvalid) do
- @connection.execute "SELECT count(*) from products"
+ silence_warnings do
+ @connection.execute "SELECT count(*) from products"
+ end
end
end
end
diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb
index f8acdcb51e..97ba178b4d 100644
--- a/activerecord/test/cases/fixtures_test.rb
+++ b/activerecord/test/cases/fixtures_test.rb
@@ -279,10 +279,10 @@ class HasManyThroughFixture < ActiveSupport::TestCase
treasure = make_model "Treasure"
pt.table_name = "parrots_treasures"
- pt.belongs_to :parrot, :class => parrot
- pt.belongs_to :treasure, :class => treasure
+ pt.belongs_to :parrot, :anonymous_class => parrot
+ pt.belongs_to :treasure, :anonymous_class => treasure
- parrot.has_many :parrot_treasures, :class => pt
+ parrot.has_many :parrot_treasures, :anonymous_class => pt
parrot.has_many :treasures, :through => :parrot_treasures
parrots = File.join FIXTURES_ROOT, 'parrots'
@@ -297,10 +297,10 @@ class HasManyThroughFixture < ActiveSupport::TestCase
parrot = make_model "Parrot"
treasure = make_model "Treasure"
- pt.belongs_to :parrot, :class => parrot
- pt.belongs_to :treasure, :class => treasure
+ pt.belongs_to :parrot, :anonymous_class => parrot
+ pt.belongs_to :treasure, :anonymous_class => treasure
- parrot.has_many :parrot_treasures, :class => pt
+ parrot.has_many :parrot_treasures, :anonymous_class => pt
parrot.has_many :treasures, :through => :parrot_treasures
parrots = File.join FIXTURES_ROOT, 'parrots'
diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb
index 9e4998a946..dbdcc84b7d 100644
--- a/activerecord/test/cases/locking_test.rb
+++ b/activerecord/test/cases/locking_test.rb
@@ -177,6 +177,16 @@ class OptimisticLockingTest < ActiveRecord::TestCase
assert_equal 1, p1.lock_version
end
+ def test_touch_stale_object
+ person = Person.create!(first_name: 'Mehmet Emin')
+ stale_person = Person.find(person.id)
+ person.update_attribute(:gender, 'M')
+
+ assert_raises(ActiveRecord::StaleObjectError) do
+ stale_person.touch
+ end
+ end
+
def test_lock_column_name_existing
t1 = LegacyThing.find(1)
t2 = LegacyThing.find(1)
diff --git a/activerecord/test/cases/migration/references_foreign_key_test.rb b/activerecord/test/cases/migration/references_foreign_key_test.rb
index 17ac72a109..1594f99852 100644
--- a/activerecord/test/cases/migration/references_foreign_key_test.rb
+++ b/activerecord/test/cases/migration/references_foreign_key_test.rb
@@ -105,7 +105,49 @@ module ActiveRecord
@connection.remove_reference :testings, :testing_parent, foreign_key: true
end
end
+
+ test "foreign key methods respect pluralize_table_names" do
+ begin
+ original_pluralize_table_names = ActiveRecord::Base.pluralize_table_names
+ ActiveRecord::Base.pluralize_table_names = false
+ @connection.create_table :testing
+ @connection.change_table :testing_parents do |t|
+ t.references :testing, foreign_key: true
+ end
+
+ fk = @connection.foreign_keys("testing_parents").first
+ assert_equal "testing_parents", fk.from_table
+ assert_equal "testing", fk.to_table
+
+ assert_difference "@connection.foreign_keys('testing_parents').size", -1 do
+ @connection.remove_reference :testing_parents, :testing, foreign_key: true
+ end
+ ensure
+ ActiveRecord::Base.pluralize_table_names = original_pluralize_table_names
+ @connection.drop_table "testing", if_exists: true
+ end
+ end
end
end
end
+else
+class ReferencesWithoutForeignKeySupportTest < ActiveRecord::TestCase
+ setup do
+ @connection = ActiveRecord::Base.connection
+ @connection.create_table(:testing_parents, force: true)
+ end
+
+ teardown do
+ @connection.drop_table("testings", if_exists: true)
+ @connection.drop_table("testing_parents", if_exists: true)
+ end
+
+ test "ignores foreign keys defined with the table" do
+ @connection.create_table :testings do |t|
+ t.references :testing_parent, foreign_key: true
+ end
+
+ assert_includes @connection.tables, "testings"
+ end
+end
end
diff --git a/activerecord/test/cases/persistence_test.rb b/activerecord/test/cases/persistence_test.rb
index 2370077eb0..1e93e2a05c 100644
--- a/activerecord/test/cases/persistence_test.rb
+++ b/activerecord/test/cases/persistence_test.rb
@@ -924,7 +924,8 @@ class PersistenceTest < ActiveRecord::TestCase
assert_equal instance.created_at, created_at
assert_equal instance.updated_at, updated_at
ensure
- ActiveRecord::Base.connection.drop_table :widgets
+ ActiveRecord::Base.connection.drop_table widget.table_name
+ widget.reset_column_information
end
end
end
diff --git a/activerecord/test/cases/primary_keys_test.rb b/activerecord/test/cases/primary_keys_test.rb
index 3664a2af70..83be9a75d8 100644
--- a/activerecord/test/cases/primary_keys_test.rb
+++ b/activerecord/test/cases/primary_keys_test.rb
@@ -260,7 +260,8 @@ if current_adapter?(:PostgreSQLAdapter, :MysqlAdapter, :Mysql2Adapter)
end
teardown do
- @connection.drop_table 'widgets', if_exists: true
+ @connection.drop_table :widgets, if_exists: true
+ Widget.reset_column_information
end
test "primary key column type with bigserial" do
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index 0cf44388fa..b8e2041b6d 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -1657,6 +1657,10 @@ class RelationTest < ActiveRecord::TestCase
assert_sql(/^((?!ORDER).)*$/) { Post.all.find_by(author_id: 2) }
end
+ test "find_by requires at least one argument" do
+ assert_raises(ArgumentError) { Post.all.find_by }
+ end
+
test "find_by! with hash conditions returns the first matching record" do
assert_equal posts(:eager_other), Post.order(:id).find_by!(author_id: 2)
end
@@ -1679,6 +1683,10 @@ class RelationTest < ActiveRecord::TestCase
end
end
+ test "find_by! requires at least one argument" do
+ assert_raises(ArgumentError) { Post.all.find_by! }
+ end
+
test "loaded relations cannot be mutated by multi value methods" do
relation = Post.all
relation.to_a
diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb
index 6c099719c0..63612e33af 100644
--- a/activerecord/test/cases/schema_dumper_test.rb
+++ b/activerecord/test/cases/schema_dumper_test.rb
@@ -73,7 +73,7 @@ class SchemaDumperTest < ActiveRecord::TestCase
next if column_set.empty?
lengths = column_set.map do |column|
- if match = column.match(/t\.(?:integer|decimal|float|datetime|timestamp|time|date|text|binary|string|boolean|xml|uuid|point)\s+"/)
+ if match = column.match(/\bt\.\w+\s+"/)
match[0].length
end
end.compact
diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb
index 7c89b4b9e8..5dab32995c 100644
--- a/activerecord/test/cases/timestamp_test.rb
+++ b/activerecord/test/cases/timestamp_test.rb
@@ -446,6 +446,17 @@ class TimestampTest < ActiveRecord::TestCase
toy = Toy.first
assert_equal [:created_at, :updated_at], toy.send(:all_timestamp_attributes_in_model)
end
+
+ def test_index_is_created_for_both_timestamps
+ ActiveRecord::Base.connection.create_table(:foos, force: true) do |t|
+ t.timestamps(:foos, null: true, index: true)
+ end
+
+ indexes = ActiveRecord::Base.connection.indexes('foos')
+ assert_equal ['created_at', 'updated_at'], indexes.flat_map(&:columns).sort
+ ensure
+ ActiveRecord::Base.connection.drop_table(:foos)
+ end
end
class TimestampsWithoutTransactionTest < ActiveRecord::TestCase
diff --git a/activerecord/test/cases/touch_later_test.rb b/activerecord/test/cases/touch_later_test.rb
new file mode 100644
index 0000000000..11804ff90b
--- /dev/null
+++ b/activerecord/test/cases/touch_later_test.rb
@@ -0,0 +1,93 @@
+require 'cases/helper'
+require 'models/invoice'
+require 'models/line_item'
+require 'models/topic'
+
+class TouchLaterTest < ActiveRecord::TestCase
+
+ def test_touch_laster_raise_if_non_persisted
+ invoice = Invoice.new
+ Invoice.transaction do
+ refute invoice.persisted?
+ assert_raises(ActiveRecord::ActiveRecordError) do
+ invoice.touch_later
+ end
+ end
+ end
+
+ def test_touch_later_dont_set_dirty_attributes
+ invoice = Invoice.create!
+ invoice.touch_later
+ refute invoice.changed?
+ end
+
+ def test_touch_later_update_the_attributes
+ time = Time.now.utc - 25.days
+ topic = Topic.create!(updated_at: time, created_at: time)
+ assert_equal time.to_i, topic.updated_at.to_i
+ assert_equal time.to_i, topic.created_at.to_i
+
+ Topic.transaction do
+ topic.touch_later(:created_at)
+ assert_not_equal time.to_i, topic.updated_at.to_i
+ assert_not_equal time.to_i, topic.created_at.to_i
+
+ assert_equal time.to_i, topic.reload.updated_at.to_i
+ assert_equal time.to_i, topic.reload.created_at.to_i
+ end
+ assert_not_equal time.to_i, topic.reload.updated_at.to_i
+ assert_not_equal time.to_i, topic.reload.created_at.to_i
+ end
+
+ def test_touch_touches_immediately
+ time = Time.now.utc - 25.days
+ topic = Topic.create!(updated_at: time, created_at: time)
+ assert_equal time.to_i, topic.updated_at.to_i
+ assert_equal time.to_i, topic.created_at.to_i
+
+ Topic.transaction do
+ topic.touch_later(:created_at)
+ topic.touch
+
+ assert_not_equal time, topic.reload.updated_at
+ assert_not_equal time, topic.reload.created_at
+ end
+ end
+
+ def test_touch_later_an_association_dont_autosave_parent
+ time = Time.now.utc - 25.days
+ line_item = LineItem.create!(amount: 1)
+ invoice = Invoice.create!(line_items: [line_item])
+ invoice.touch(time: time)
+
+ Invoice.transaction do
+ line_item.update(amount: 2)
+ assert_equal time.to_i, invoice.reload.updated_at.to_i
+ end
+
+ assert_not_equal time.to_i, invoice.updated_at.to_i
+ end
+
+ def test_touch_touches_immediately_with_a_custom_time
+ time = Time.now.utc - 25.days
+ topic = Topic.create!(updated_at: time, created_at: time)
+ assert_equal time, topic.updated_at
+ assert_equal time, topic.created_at
+
+ Topic.transaction do
+ topic.touch_later(:created_at)
+ time = Time.now.utc - 2.days
+ topic.touch(time: time)
+
+ assert_equal time.to_i, topic.reload.updated_at.to_i
+ assert_equal time.to_i, topic.reload.created_at.to_i
+ end
+ end
+
+ def test_touch_later_dont_hit_the_db
+ invoice = Invoice.create!
+ assert_queries(0) do
+ invoice.touch_later
+ end
+ end
+end
diff --git a/activerecord/test/cases/validations/uniqueness_validation_test.rb b/activerecord/test/cases/validations/uniqueness_validation_test.rb
index 062bc733f9..2608c84be2 100644
--- a/activerecord/test/cases/validations/uniqueness_validation_test.rb
+++ b/activerecord/test/cases/validations/uniqueness_validation_test.rb
@@ -34,7 +34,22 @@ class TopicWithUniqEvent < Topic
validates :event, uniqueness: true
end
+class BigIntTest < ActiveRecord::Base
+ INT_MAX_VALUE = 2147483647
+ self.table_name = 'cars'
+ validates :engines_count, uniqueness: true, inclusion: { in: 0..INT_MAX_VALUE }
+end
+
+class BigIntReverseTest < ActiveRecord::Base
+ INT_MAX_VALUE = 2147483647
+ self.table_name = 'cars'
+ validates :engines_count, inclusion: { in: 0..INT_MAX_VALUE }
+ validates :engines_count, uniqueness: true
+end
+
class UniquenessValidationTest < ActiveRecord::TestCase
+ INT_MAX_VALUE = 2147483647
+
fixtures :topics, 'warehouse-things'
repair_validations(Topic, Reply)
@@ -86,6 +101,16 @@ class UniquenessValidationTest < ActiveRecord::TestCase
assert t2.errors[:title]
end
+ def test_validate_uniqueness_when_integer_out_of_range
+ entry = BigIntTest.create(engines_count: INT_MAX_VALUE + 1)
+ assert_equal entry.errors[:engines_count], ['is not included in the list']
+ end
+
+ def test_validate_uniqueness_when_integer_out_of_range_show_order_does_not_matter
+ entry = BigIntReverseTest.create(engines_count: INT_MAX_VALUE + 1)
+ assert_equal entry.errors[:engines_count], ['is not included in the list']
+ end
+
def test_validates_uniqueness_with_newline_chars
Topic.validates_uniqueness_of(:title, :case_sensitive => false)
diff --git a/activerecord/test/schema/mysql2_specific_schema.rb b/activerecord/test/schema/mysql2_specific_schema.rb
index d6fd0c4ab0..52d3290c84 100644
--- a/activerecord/test/schema/mysql2_specific_schema.rb
+++ b/activerecord/test/schema/mysql2_specific_schema.rb
@@ -24,6 +24,11 @@ ActiveRecord::Schema.define do
add_index :key_tests, :pizza, :using => :btree, :name => 'index_key_tests_on_pizza'
add_index :key_tests, :snacks, :name => 'index_key_tests_on_snack'
+ create_table :collation_tests, id: false, force: true do |t|
+ t.string :string_cs_column, limit: 1, collation: 'utf8_bin'
+ t.string :string_ci_column, limit: 1, collation: 'utf8_general_ci'
+ end
+
ActiveRecord::Base.connection.execute <<-SQL
DROP PROCEDURE IF EXISTS ten;
SQL
@@ -35,15 +40,6 @@ BEGIN
END
SQL
- ActiveRecord::Base.connection.drop_table "collation_tests", if_exists: true
-
- ActiveRecord::Base.connection.execute <<-SQL
-CREATE TABLE collation_tests (
- string_cs_column VARCHAR(1) COLLATE utf8_bin,
- string_ci_column VARCHAR(1) COLLATE utf8_general_ci
-) CHARACTER SET utf8 COLLATE utf8_general_ci
-SQL
-
ActiveRecord::Base.connection.drop_table "enum_tests", if_exists: true
ActiveRecord::Base.connection.execute <<-SQL
diff --git a/activerecord/test/schema/mysql_specific_schema.rb b/activerecord/test/schema/mysql_specific_schema.rb
index b5378341b5..90f5a60d7b 100644
--- a/activerecord/test/schema/mysql_specific_schema.rb
+++ b/activerecord/test/schema/mysql_specific_schema.rb
@@ -24,6 +24,11 @@ ActiveRecord::Schema.define do
add_index :key_tests, :pizza, :using => :btree, :name => 'index_key_tests_on_pizza'
add_index :key_tests, :snacks, :name => 'index_key_tests_on_snack'
+ create_table :collation_tests, id: false, force: true do |t|
+ t.string :string_cs_column, limit: 1, collation: 'utf8_bin'
+ t.string :string_ci_column, limit: 1, collation: 'utf8_general_ci'
+ end
+
ActiveRecord::Base.connection.execute <<-SQL
DROP PROCEDURE IF EXISTS ten;
SQL
@@ -46,15 +51,6 @@ BEGIN
END
SQL
- ActiveRecord::Base.connection.drop_table "collation_tests", if_exists: true
-
- ActiveRecord::Base.connection.execute <<-SQL
-CREATE TABLE collation_tests (
- string_cs_column VARCHAR(1) COLLATE utf8_bin,
- string_ci_column VARCHAR(1) COLLATE utf8_general_ci
-) CHARACTER SET utf8 COLLATE utf8_general_ci
-SQL
-
ActiveRecord::Base.connection.drop_table "enum_tests", if_exists: true
ActiveRecord::Base.connection.execute <<-SQL
diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md
index 49088527ae..ac27dc640e 100644
--- a/activesupport/CHANGELOG.md
+++ b/activesupport/CHANGELOG.md
@@ -1,4 +1,41 @@
-* Deprecate `alias_method_chain` in favour of `Module#prepend` introduced in Ruby 2.0
+* Encoding ActiveSupport::TimeWithZone to YAML now preserves the timezone information.
+
+ Fixes #9183.
+
+ *Andrew White*
+
+* Added `ActiveSupport::TimeZone#strptime` to allow parsing times as if
+ from a given timezone.
+
+ *Paul A Jungwirth*
+
+* `ActiveSupport::Callbacks#skip_callback` now raises an `ArgumentError` if
+ an unrecognized callback is removed.
+
+ *Iain Beeston*
+
+* Added `ActiveSupport::ArrayInquirer` and `Array#inquiry`.
+
+ Wrapping an array in an `ArrayInquirer` gives a friendlier way to check its
+ contents:
+
+ variants = ActiveSupport::ArrayInquirer.new([:phone, :tablet])
+
+ variants.phone? # => true
+ variants.tablet? # => true
+ variants.desktop? # => false
+
+ variants.any?(:phone, :tablet) # => true
+ variants.any?(:phone, :desktop) # => true
+ variants.any?(:desktop, :watch) # => false
+
+ `Array#inquiry` is a shortcut for wrapping the receiving array in an
+ `ArrayInquirer`.
+
+ *George Claghorn*
+
+* Deprecate `alias_method_chain` in favour of `Module#prepend` introduced in
+ Ruby 2.0.
*Kir Shatrov*
diff --git a/activesupport/activesupport.gemspec b/activesupport/activesupport.gemspec
index 2cb455cb41..12c6a4d449 100644
--- a/activesupport/activesupport.gemspec
+++ b/activesupport/activesupport.gemspec
@@ -7,7 +7,7 @@ Gem::Specification.new do |s|
s.summary = 'A toolkit of support libraries and Ruby core extensions extracted from the Rails framework.'
s.description = 'A toolkit of support libraries and Ruby core extensions extracted from the Rails framework. Rich support for multibyte strings, internationalization, time zones, and testing.'
- s.required_ruby_version = '>= 2.2.1'
+ s.required_ruby_version = '>= 2.2.2'
s.license = 'MIT'
diff --git a/activesupport/lib/active_support.rb b/activesupport/lib/active_support.rb
index 290920dbf8..588d6c49f9 100644
--- a/activesupport/lib/active_support.rb
+++ b/activesupport/lib/active_support.rb
@@ -59,6 +59,7 @@ module ActiveSupport
autoload :StringInquirer
autoload :TaggedLogging
autoload :XmlMini
+ autoload :ArrayInquirer
end
autoload :Rescuable
@@ -72,6 +73,14 @@ module ActiveSupport
end
cattr_accessor :test_order # :nodoc:
+
+ def self.halt_callback_chains_on_return_false
+ Callbacks::CallbackChain.halt_and_display_warning_on_return_false
+ end
+
+ def self.halt_callback_chains_on_return_false=(value)
+ Callbacks::CallbackChain.halt_and_display_warning_on_return_false = value
+ end
end
autoload :I18n, "active_support/i18n"
diff --git a/activesupport/lib/active_support/array_inquirer.rb b/activesupport/lib/active_support/array_inquirer.rb
new file mode 100644
index 0000000000..0ae534da00
--- /dev/null
+++ b/activesupport/lib/active_support/array_inquirer.rb
@@ -0,0 +1,38 @@
+module ActiveSupport
+ # Wrapping an array in an +ArrayInquirer+ gives a friendlier way to check
+ # its string-like contents:
+ #
+ # variants = ActiveSupport::ArrayInquirer.new([:phone, :tablet])
+ #
+ # variants.phone? # => true
+ # variants.tablet? # => true
+ # variants.desktop? # => false
+ #
+ # variants.any?(:phone, :tablet) # => true
+ # variants.any?(:phone, :desktop) # => true
+ # variants.any?(:desktop, :watch) # => false
+ class ArrayInquirer < Array
+ def any?(*candidates, &block)
+ if candidates.none?
+ super
+ else
+ candidates.any? do |candidate|
+ include?(candidate) || include?(candidate.to_sym)
+ end
+ end
+ end
+
+ private
+ def respond_to_missing?(name, include_private = false)
+ name[-1] == '?'
+ end
+
+ def method_missing(name, *args)
+ if name[-1] == '?'
+ any?(name[0..-2])
+ else
+ super
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/cache/file_store.rb b/activesupport/lib/active_support/cache/file_store.rb
index d08ecd2f7d..e6a8b84214 100644
--- a/activesupport/lib/active_support/cache/file_store.rb
+++ b/activesupport/lib/active_support/cache/file_store.rb
@@ -29,6 +29,7 @@ module ActiveSupport
def clear(options = nil)
root_dirs = Dir.entries(cache_path).reject {|f| (EXCLUDED_DIRS + [".gitkeep"]).include?(f)}
FileUtils.rm_r(root_dirs.collect{|f| File.join(cache_path, f)})
+ rescue Errno::ENOENT
end
# Preemptively iterates through all stored keys and removes the ones which have expired.
diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb
index 08520b1077..814fd288cf 100644
--- a/activesupport/lib/active_support/callbacks.rb
+++ b/activesupport/lib/active_support/callbacks.rb
@@ -80,14 +80,10 @@ module ActiveSupport
# save
# end
def run_callbacks(kind, &block)
- send "_run_#{kind}_callbacks", &block
- end
-
- private
+ callbacks = send("_#{kind}_callbacks")
- def _run_callbacks(callbacks, &block)
if callbacks.empty?
- block.call if block
+ yield if block_given?
else
runner = callbacks.compile
e = Filters::Environment.new(self, false, nil, block)
@@ -95,6 +91,8 @@ module ActiveSupport
end
end
+ private
+
# A hook invoked every time a before callback is halted.
# This can be overridden in AS::Callback implementors in order
# to provide better debugging/logging.
@@ -663,10 +661,12 @@ module ActiveSupport
#
# ===== Options
#
- # * <tt>:if</tt> - A symbol naming an instance method or a proc; the
- # callback will be called only when it returns a +true+ value.
- # * <tt>:unless</tt> - A symbol naming an instance method or a proc; the
- # callback will be called only when it returns a +false+ value.
+ # * <tt>:if</tt> - A symbol, a string or an array of symbols and strings,
+ # each naming an instance method or a proc; the callback will be called
+ # only when they all return a true value.
+ # * <tt>:unless</tt> - A symbol, a string or an array of symbols and
+ # strings, each naming an instance method or a proc; the callback will
+ # be called only when they all return a false value.
# * <tt>:prepend</tt> - If +true+, the callback will be prepended to the
# existing chain rather than appended.
def set_callback(name, *filter_list, &block)
@@ -689,19 +689,27 @@ module ActiveSupport
# class Writer < Person
# skip_callback :validate, :before, :check_membership, if: -> { self.age > 18 }
# end
+ #
+ # An <tt>ArgumentError</tt> will be raised if the callback has not
+ # already been set (unless the <tt>:raise</tt> option is set to <tt>false</tt>).
def skip_callback(name, *filter_list, &block)
type, filters, options = normalize_callback_params(filter_list, block)
+ options[:raise] = true unless options.key?(:raise)
__update_callbacks(name) do |target, chain|
filters.each do |filter|
- filter = chain.find {|c| c.matches?(type, filter) }
+ callback = chain.find {|c| c.matches?(type, filter) }
+
+ if !callback && options[:raise]
+ raise ArgumentError, "#{type.to_s.capitalize} #{name} callback #{filter.inspect} has not been defined"
+ end
- if filter && options.any?
- new_filter = filter.merge_conditional_options(chain, if_option: options[:if], unless_option: options[:unless])
- chain.insert(chain.index(filter), new_filter)
+ if callback && (options.key?(:if) || options.key?(:unless))
+ new_callback = callback.merge_conditional_options(chain, if_option: options[:if], unless_option: options[:unless])
+ chain.insert(chain.index(callback), new_callback)
end
- chain.delete(filter)
+ chain.delete(callback)
end
target.set_callbacks name, chain
end
@@ -798,12 +806,6 @@ module ActiveSupport
names.each do |name|
class_attribute "_#{name}_callbacks"
set_callbacks name, CallbackChain.new(name, options)
-
- module_eval <<-RUBY, __FILE__, __LINE__ + 1
- def _run_#{name}_callbacks(&block)
- _run_callbacks(_#{name}_callbacks, &block)
- end
- RUBY
end
end
diff --git a/activesupport/lib/active_support/core_ext/array.rb b/activesupport/lib/active_support/core_ext/array.rb
index 7d0c1e4c8d..7551551bd7 100644
--- a/activesupport/lib/active_support/core_ext/array.rb
+++ b/activesupport/lib/active_support/core_ext/array.rb
@@ -4,3 +4,4 @@ require 'active_support/core_ext/array/conversions'
require 'active_support/core_ext/array/extract_options'
require 'active_support/core_ext/array/grouping'
require 'active_support/core_ext/array/prepend_and_append'
+require 'active_support/core_ext/array/inquiry'
diff --git a/activesupport/lib/active_support/core_ext/array/inquiry.rb b/activesupport/lib/active_support/core_ext/array/inquiry.rb
new file mode 100644
index 0000000000..e8f44cc378
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/array/inquiry.rb
@@ -0,0 +1,17 @@
+require 'active_support/array_inquirer'
+
+class Array
+ # Wraps the array in an +ArrayInquirer+ object, which gives a friendlier way
+ # to check its string-like contents.
+ #
+ # pets = [:cat, :dog].inquiry
+ #
+ # pets.cat? # => true
+ # pets.ferret? # => false
+ #
+ # pets.any?(:cat, :ferret) # => true
+ # pets.any?(:ferret, :alligator) # => false
+ def inquiry
+ ActiveSupport::ArrayInquirer.new(self)
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/array/wrap.rb b/activesupport/lib/active_support/core_ext/array/wrap.rb
index 152eb02218..b611d34c27 100644
--- a/activesupport/lib/active_support/core_ext/array/wrap.rb
+++ b/activesupport/lib/active_support/core_ext/array/wrap.rb
@@ -3,7 +3,7 @@ class Array
#
# Specifically:
#
- # * If the argument is +nil+ an empty list is returned.
+ # * If the argument is +nil+ an empty array is returned.
# * Otherwise, if the argument responds to +to_ary+ it is invoked, and its result returned.
# * Otherwise, returns an array with the argument as its single element.
#
@@ -15,12 +15,13 @@ class Array
#
# * If the argument responds to +to_ary+ the method is invoked. <tt>Kernel#Array</tt>
# moves on to try +to_a+ if the returned value is +nil+, but <tt>Array.wrap</tt> returns
- # +nil+ right away.
+ # an array with the argument as its single element right away.
# * If the returned value from +to_ary+ is neither +nil+ nor an +Array+ object, <tt>Kernel#Array</tt>
# raises an exception, while <tt>Array.wrap</tt> does not, it just returns the value.
- # * It does not call +to_a+ on the argument, but returns an empty array if argument is +nil+.
+ # * It does not call +to_a+ on the argument, if the argument does not respond to +to_ary+
+ # it returns an array with the argument as its single element.
#
- # The second point is easily explained with some enumerables:
+ # The last point is easily explained with some enumerables:
#
# Array(foo: :bar) # => [[:foo, :bar]]
# Array.wrap(foo: :bar) # => [{:foo=>:bar}]
diff --git a/activesupport/lib/active_support/core_ext/module/aliasing.rb b/activesupport/lib/active_support/core_ext/module/aliasing.rb
index dcc1cd5ba9..b6934b9c54 100644
--- a/activesupport/lib/active_support/core_ext/module/aliasing.rb
+++ b/activesupport/lib/active_support/core_ext/module/aliasing.rb
@@ -1,6 +1,7 @@
-require 'active_support/deprecation'
-
class Module
+ # NOTE: This method is deprecated. Please use <tt>Module#prepend</tt> that
+ # comes with Ruby 2.0 or newer instead.
+ #
# Encapsulates the common pattern of:
#
# alias_method :foo_without_feature, :foo
@@ -47,7 +48,7 @@ class Module
end
# Allows you to make aliases for attributes, which includes
- # getter, setter, and query methods.
+ # getter, setter, and a predicate.
#
# class Content < ActiveRecord::Base
# # has a title attribute
diff --git a/activesupport/lib/active_support/core_ext/module/concerning.rb b/activesupport/lib/active_support/core_ext/module/concerning.rb
index 07a392404e..e26b594fc4 100644
--- a/activesupport/lib/active_support/core_ext/module/concerning.rb
+++ b/activesupport/lib/active_support/core_ext/module/concerning.rb
@@ -63,10 +63,10 @@ class Module
#
# == Mix-in noise exiled to its own file:
#
- # Once our chunk of behavior starts pushing the scroll-to-understand it's
+ # Once our chunk of behavior starts pushing the scroll-to-understand-it
# boundary, we give in and move it to a separate file. At this size, the
- # overhead feels in good proportion to the size of our extraction, despite
- # diluting our at-a-glance sense of how things really work.
+ # increased overhead can be a reasonable tradeoff even if it reduces our
+ # at-a-glance perception of how things work.
#
# class Todo
# # Other todo implementation
diff --git a/activesupport/lib/active_support/core_ext/module/deprecation.rb b/activesupport/lib/active_support/core_ext/module/deprecation.rb
index 5134b5ad41..56d670fbe8 100644
--- a/activesupport/lib/active_support/core_ext/module/deprecation.rb
+++ b/activesupport/lib/active_support/core_ext/module/deprecation.rb
@@ -1,5 +1,3 @@
-require 'active_support/deprecation'
-
class Module
# deprecate :foo
# deprecate bar: 'message'
diff --git a/activesupport/lib/active_support/core_ext/object/with_options.rb b/activesupport/lib/active_support/core_ext/object/with_options.rb
index 7d38e1d134..513c8b1d55 100644
--- a/activesupport/lib/active_support/core_ext/object/with_options.rb
+++ b/activesupport/lib/active_support/core_ext/object/with_options.rb
@@ -7,7 +7,7 @@ class Object
# provided. Each method called on the block variable must take an options
# hash as its final argument.
#
- # Without <tt>with_options></tt>, this code contains duplication:
+ # Without <tt>with_options</tt>, this code contains duplication:
#
# class Account < ActiveRecord::Base
# has_many :customers, dependent: :destroy
diff --git a/activesupport/lib/active_support/core_ext/range/each.rb b/activesupport/lib/active_support/core_ext/range/each.rb
index f666480fe6..dc6dad5ced 100644
--- a/activesupport/lib/active_support/core_ext/range/each.rb
+++ b/activesupport/lib/active_support/core_ext/range/each.rb
@@ -1,27 +1,21 @@
-class Range #:nodoc:
+module ActiveSupport
+ module EachTimeWithZone #:nodoc:
+ def each(&block)
+ ensure_iteration_allowed
+ super
+ end
- def each_with_time_with_zone(&block)
- ensure_iteration_allowed
- each_without_time_with_zone(&block)
- end
- # TODO: change to Module#prepend as soon as the fix is backported to MRI 2.2:
- # https://bugs.ruby-lang.org/issues/10847
- alias_method :each_without_time_with_zone, :each
- alias_method :each, :each_with_time_with_zone
+ def step(n = 1, &block)
+ ensure_iteration_allowed
+ super
+ end
- def step_with_time_with_zone(n = 1, &block)
- ensure_iteration_allowed
- step_without_time_with_zone(n, &block)
- end
- # TODO: change to Module#prepend as soon as the fix is backported to MRI 2.2:
- # https://bugs.ruby-lang.org/issues/10847
- alias_method :step_without_time_with_zone, :step
- alias_method :step, :step_with_time_with_zone
+ private
- private
- def ensure_iteration_allowed
- if first.is_a?(Time)
- raise TypeError, "can't iterate from #{first.class}"
- end
+ def ensure_iteration_allowed
+ raise TypeError, "can't iterate from #{first.class}" if first.is_a?(Time)
+ end
end
end
+
+Range.prepend(ActiveSupport::EachTimeWithZone)
diff --git a/activesupport/lib/active_support/core_ext/range/include_range.rb b/activesupport/lib/active_support/core_ext/range/include_range.rb
index 9d20920dd0..c69e1e3fb9 100644
--- a/activesupport/lib/active_support/core_ext/range/include_range.rb
+++ b/activesupport/lib/active_support/core_ext/range/include_range.rb
@@ -1,23 +1,23 @@
-class Range
- # Extends the default Range#include? to support range comparisons.
- # (1..5).include?(1..5) # => true
- # (1..5).include?(2..3) # => true
- # (1..5).include?(2..6) # => false
- #
- # The native Range#include? behavior is untouched.
- # ('a'..'f').include?('c') # => true
- # (5..9).include?(11) # => false
- def include_with_range?(value)
- if value.is_a?(::Range)
- # 1...10 includes 1..9 but it does not include 1..10.
- operator = exclude_end? && !value.exclude_end? ? :< : :<=
- include_without_range?(value.first) && value.last.send(operator, last)
- else
- include_without_range?(value)
+module ActiveSupport
+ module IncludeWithRange #:nodoc:
+ # Extends the default Range#include? to support range comparisons.
+ # (1..5).include?(1..5) # => true
+ # (1..5).include?(2..3) # => true
+ # (1..5).include?(2..6) # => false
+ #
+ # The native Range#include? behavior is untouched.
+ # ('a'..'f').include?('c') # => true
+ # (5..9).include?(11) # => false
+ def include?(value)
+ if value.is_a?(::Range)
+ # 1...10 includes 1..9 but it does not include 1..10.
+ operator = exclude_end? && !value.exclude_end? ? :< : :<=
+ super(value.first) && value.last.send(operator, last)
+ else
+ super
+ end
end
end
- # TODO: change to Module#prepend as soon as the fix is backported to MRI 2.2:
- # https://bugs.ruby-lang.org/issues/10847
- alias_method :include_without_range?, :include?
- alias_method :include?, :include_with_range?
end
+
+Range.prepend(ActiveSupport::IncludeWithRange)
diff --git a/activesupport/lib/active_support/core_ext/string/filters.rb b/activesupport/lib/active_support/core_ext/string/filters.rb
index 7461d03acc..375ec1aef8 100644
--- a/activesupport/lib/active_support/core_ext/string/filters.rb
+++ b/activesupport/lib/active_support/core_ext/string/filters.rb
@@ -17,9 +17,8 @@ class String
# str.squish! # => "foo bar boo"
# str # => "foo bar boo"
def squish!
- gsub!(/\A[[:space:]]+/, '')
- gsub!(/[[:space:]]+\z/, '')
gsub!(/[[:space:]]+/, ' ')
+ strip!
self
end
diff --git a/activesupport/lib/active_support/core_ext/time/calculations.rb b/activesupport/lib/active_support/core_ext/time/calculations.rb
index 6f1b653639..1ce68ea7c7 100644
--- a/activesupport/lib/active_support/core_ext/time/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/time/calculations.rb
@@ -246,8 +246,10 @@ class Time
# Layers additional behavior on Time#<=> so that DateTime and ActiveSupport::TimeWithZone instances
# can be chronologically compared with a Time
def compare_with_coercion(other)
- # we're avoiding Time#to_datetime cause it's expensive
- if other.is_a?(Time)
+ # we're avoiding Time#to_datetime and Time#to_time because they're expensive
+ if other.class == Time
+ compare_without_coercion(other)
+ elsif other.is_a?(Time)
compare_without_coercion(other.to_time)
else
to_datetime <=> other
diff --git a/activesupport/lib/active_support/deprecation/proxy_wrappers.rb b/activesupport/lib/active_support/deprecation/proxy_wrappers.rb
index a03a66b96b..dedcdfdb60 100644
--- a/activesupport/lib/active_support/deprecation/proxy_wrappers.rb
+++ b/activesupport/lib/active_support/deprecation/proxy_wrappers.rb
@@ -25,15 +25,17 @@ module ActiveSupport
end
end
- # This DeprecatedObjectProxy transforms object to deprecated object.
+ # DeprecatedObjectProxy transforms an object into a deprecated object. It takes an object,
+ # a deprecation message, and optionally a deprecator. The deprecator defaults to
+ # <tt>ActiveSupport::Deprecator</tt> if none is specified.
#
- # @old_object = DeprecatedObjectProxy.new(Object.new, "Don't use this object anymore!")
- # @old_object = DeprecatedObjectProxy.new(Object.new, "Don't use this object anymore!", deprecator_instance)
+ # deprecated_object = ActiveSupport::Deprecation::DeprecatedObjectProxy.new(Object.new, "This object is now deprecated")
+ # # => <Object:0x007fb9b34c34b0>
#
- # When someone executes any method except +inspect+ on proxy object this will
- # trigger +warn+ method on +deprecator_instance+.
- #
- # Default deprecator is <tt>ActiveSupport::Deprecation</tt>
+ # deprecated_object.to_s
+ # DEPRECATION WARNING: This object is now deprecated.
+ # (Backtrace)
+ # # => "<Object:0x007fb9b34c34b0>"
class DeprecatedObjectProxy < DeprecationProxy
def initialize(object, message, deprecator = ActiveSupport::Deprecation.instance)
@object = object
@@ -51,13 +53,15 @@ module ActiveSupport
end
end
- # This DeprecatedInstanceVariableProxy transforms instance variable to
- # deprecated instance variable.
+ # DeprecatedInstanceVariableProxy transforms an instance variable into a deprecated
+ # instance variable. It takes an instance of a class, a method on that class, and an
+ # instance variable. It optionally takes a deprecator as the last argument. The deprecator
+ # defaults to <tt>ActiveSupport::Deprecator</tt> if none is specified.
#
# class Example
- # def initialize(deprecator)
+ # def initialize
# @request = ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy.new(self, :request, :@request, deprecator)
- # @_request = :a_request
+ # @_request = :special_request
# end
#
# def request
@@ -69,12 +73,17 @@ module ActiveSupport
# end
# end
#
- # When someone execute any method on @request variable this will trigger
- # +warn+ method on +deprecator_instance+ and will fetch <tt>@_request</tt>
- # variable via +request+ method and execute the same method on non-proxy
- # instance variable.
+ # example = Example.new
+ # # => #<Example:0x007fb9b31090b8 @_request=:special_request, @request=:special_request>
+ #
+ # example.old_request.to_s
+ # # => DEPRECATION WARNING: @request is deprecated! Call request.to_s instead of
+ # @request.to_s
+ # (Bactrace information…)
+ # "special_request"
#
- # Default deprecator is <tt>ActiveSupport::Deprecation</tt>.
+ # example.request.to_s
+ # # => "special_request"
class DeprecatedInstanceVariableProxy < DeprecationProxy
def initialize(instance, method, var = "@#{method}", deprecator = ActiveSupport::Deprecation.instance)
@instance = instance
@@ -93,15 +102,22 @@ module ActiveSupport
end
end
- # This DeprecatedConstantProxy transforms constant to deprecated constant.
+ # DeprecatedConstantProxy transforms a constant into a deprecated constant. It takes the names of an old
+ # (deprecated) constant and a new contstant (both in string form), and optionally a deprecator. The
+ # deprecator defaults to <tt>ActiveSupport::Deprecator</tt> if none is specified. The deprecated constant
+ # now returns the return value of the new constant.
+ #
+ # PLANETS = %w(mercury venus earth mars jupiter saturn uranus neptune pluto)
#
- # OLD_CONST = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('OLD_CONST', 'NEW_CONST')
- # OLD_CONST = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('OLD_CONST', 'NEW_CONST', deprecator_instance)
+ # (In a later update, the orignal implementation of `PLANETS` has been removed.)
#
- # When someone use old constant this will trigger +warn+ method on
- # +deprecator_instance+.
+ # PLANETS_POST_2006 = %w(mercury venus earth mars jupiter saturn uranus neptune)
+ # PLANETS = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('PLANETS', 'PLANETS_POST_2006')
#
- # Default deprecator is <tt>ActiveSupport::Deprecation</tt>.
+ # PLANETS.map { |planet| planet.capitalize }
+ # # => DEPRECATION WARNING: PLANETS is deprecated! Use PLANETS_POST_2006 instead.
+ # (Bactrace information…)
+ # ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
class DeprecatedConstantProxy < DeprecationProxy
def initialize(old_const, new_const, deprecator = ActiveSupport::Deprecation.instance)
@old_const = old_const
diff --git a/activesupport/lib/active_support/inflector/methods.rb b/activesupport/lib/active_support/inflector/methods.rb
index fe8a2ac9ba..a08c655d69 100644
--- a/activesupport/lib/active_support/inflector/methods.rb
+++ b/activesupport/lib/active_support/inflector/methods.rb
@@ -73,7 +73,7 @@ module ActiveSupport
string = string.sub(/^(?:#{inflections.acronym_regex}(?=\b|[A-Z_])|\w)/) { $&.downcase }
end
string.gsub!(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{inflections.acronyms[$2] || $2.capitalize}" }
- string.gsub!(/\//, '::')
+ string.gsub!('/'.freeze, '::'.freeze)
string
end
@@ -90,7 +90,7 @@ module ActiveSupport
# camelize(underscore('SSLError')) # => "SslError"
def underscore(camel_cased_word)
return camel_cased_word unless camel_cased_word =~ /[A-Z-]|::/
- word = camel_cased_word.to_s.gsub(/::/, '/')
+ word = camel_cased_word.to_s.gsub('::'.freeze, '/'.freeze)
word.gsub!(/(?:(?<=([A-Za-z\d]))|\b)(#{inflections.acronym_regex})(?=\b|[^a-z])/) { "#{$1 && '_'}#{$2.downcase}" }
word.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2')
word.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
diff --git a/activesupport/lib/active_support/number_helper/number_to_currency_converter.rb b/activesupport/lib/active_support/number_helper/number_to_currency_converter.rb
index ce03700de1..cd5a2b3cbb 100644
--- a/activesupport/lib/active_support/number_helper/number_to_currency_converter.rb
+++ b/activesupport/lib/active_support/number_helper/number_to_currency_converter.rb
@@ -13,7 +13,7 @@ module ActiveSupport
end
rounded_number = NumberToRoundedConverter.convert(number, options)
- format.gsub(/%n/, rounded_number).gsub(/%u/, options[:unit])
+ format.gsub('%n'.freeze, rounded_number).gsub('%u'.freeze, options[:unit])
end
private
diff --git a/activesupport/lib/active_support/number_helper/number_to_human_converter.rb b/activesupport/lib/active_support/number_helper/number_to_human_converter.rb
index 6940beb318..5c6fe2df83 100644
--- a/activesupport/lib/active_support/number_helper/number_to_human_converter.rb
+++ b/activesupport/lib/active_support/number_helper/number_to_human_converter.rb
@@ -23,7 +23,7 @@ module ActiveSupport
unit = determine_unit(units, exponent)
rounded_number = NumberToRoundedConverter.convert(number, options)
- format.gsub(/%n/, rounded_number).gsub(/%u/, unit).strip
+ format.gsub('%n'.freeze, rounded_number).gsub('%u'.freeze, unit).strip
end
private
diff --git a/activesupport/lib/active_support/number_helper/number_to_human_size_converter.rb b/activesupport/lib/active_support/number_helper/number_to_human_size_converter.rb
index 78d2c9ae6e..ac0d20b454 100644
--- a/activesupport/lib/active_support/number_helper/number_to_human_size_converter.rb
+++ b/activesupport/lib/active_support/number_helper/number_to_human_size_converter.rb
@@ -20,7 +20,7 @@ module ActiveSupport
human_size = number / (base ** exponent)
number_to_format = NumberToRoundedConverter.convert(human_size, options)
end
- conversion_format.gsub(/%n/, number_to_format).gsub(/%u/, unit)
+ conversion_format.gsub('%n'.freeze, number_to_format).gsub('%u'.freeze, unit)
end
private
diff --git a/activesupport/lib/active_support/number_helper/number_to_percentage_converter.rb b/activesupport/lib/active_support/number_helper/number_to_percentage_converter.rb
index 1af294a03e..4c04d40c19 100644
--- a/activesupport/lib/active_support/number_helper/number_to_percentage_converter.rb
+++ b/activesupport/lib/active_support/number_helper/number_to_percentage_converter.rb
@@ -5,7 +5,7 @@ module ActiveSupport
def convert
rounded_number = NumberToRoundedConverter.convert(number, options)
- options[:format].gsub(/%n/, rounded_number)
+ options[:format].gsub('%n'.freeze, rounded_number)
end
end
end
diff --git a/activesupport/lib/active_support/rails.rb b/activesupport/lib/active_support/rails.rb
index b05c3ff126..c8e3a4bf53 100644
--- a/activesupport/lib/active_support/rails.rb
+++ b/activesupport/lib/active_support/rails.rb
@@ -1,8 +1,8 @@
# This is private interface.
#
# Rails components cherry pick from Active Support as needed, but there are a
-# few features that are used for sure some way or another and it is not worth
-# to put individual requires absolutely everywhere. Think blank? for example.
+# few features that are used for sure in some way or another and it is not worth
+# putting individual requires absolutely everywhere. Think blank? for example.
#
# This file is loaded by every Rails component except Active Support itself,
# but it does not belong to the Rails public interface. It is internal to
diff --git a/activesupport/lib/active_support/railtie.rb b/activesupport/lib/active_support/railtie.rb
index ef22433491..cd0fb51009 100644
--- a/activesupport/lib/active_support/railtie.rb
+++ b/activesupport/lib/active_support/railtie.rb
@@ -13,13 +13,6 @@ module ActiveSupport
end
end
- initializer "active_support.halt_callback_chains_on_return_false", after: :load_config_initializers do |app|
- if app.config.active_support.key? :halt_callback_chains_on_return_false
- ActiveSupport::Callbacks::CallbackChain.halt_and_display_warning_on_return_false = \
- app.config.active_support.halt_callback_chains_on_return_false
- end
- end
-
# Sets the default value for Time.zone
# If assigned value cannot be matched to a TimeZone, an exception will be raised.
initializer "active_support.initialize_time_zone" do |app|
diff --git a/activesupport/lib/active_support/rescuable.rb b/activesupport/lib/active_support/rescuable.rb
index 67aac32742..fcf5553061 100644
--- a/activesupport/lib/active_support/rescuable.rb
+++ b/activesupport/lib/active_support/rescuable.rb
@@ -68,7 +68,7 @@ module ActiveSupport
raise ArgumentError, "#{klass} is neither an Exception nor a String"
end
- # put the new handler at the end because the list is read in reverse
+ # Put the new handler at the end because the list is read in reverse.
self.rescue_handlers += [[key, options[:with]]]
end
end
diff --git a/activesupport/lib/active_support/subscriber.rb b/activesupport/lib/active_support/subscriber.rb
index 8db423f0e9..1cd4b807ad 100644
--- a/activesupport/lib/active_support/subscriber.rb
+++ b/activesupport/lib/active_support/subscriber.rb
@@ -5,7 +5,7 @@ module ActiveSupport
# ActiveSupport::Notifications. The subscriber dispatches notifications to
# a registered object based on its given namespace.
#
- # An example would be Active Record subscriber responsible for collecting
+ # An example would be an Active Record subscriber responsible for collecting
# statistics about queries:
#
# module ActiveRecord
@@ -61,7 +61,7 @@ module ActiveSupport
pattern = "#{event}.#{namespace}"
- # don't add multiple subscribers (eg. if methods are redefined)
+ # Don't add multiple subscribers (eg. if methods are redefined).
return if subscriber.patterns.include?(pattern)
subscriber.patterns << pattern
diff --git a/activesupport/lib/active_support/testing/isolation.rb b/activesupport/lib/active_support/testing/isolation.rb
index 247df7423b..1de0a19998 100644
--- a/activesupport/lib/active_support/testing/isolation.rb
+++ b/activesupport/lib/active_support/testing/isolation.rb
@@ -69,17 +69,17 @@ module ActiveSupport
else
Tempfile.open("isolation") do |tmpfile|
env = {
- ISOLATION_TEST: self.class.name,
- ISOLATION_OUTPUT: tmpfile.path
+ 'ISOLATION_TEST' => self.class.name,
+ 'ISOLATION_OUTPUT' => tmpfile.path
}
load_paths = $-I.map {|p| "-I\"#{File.expand_path(p)}\"" }.join(" ")
orig_args = ORIG_ARGV.join(" ")
test_opts = "-n#{self.class.name}##{self.name}"
- command = "#{Gem.ruby} #{load_paths} #{$0} #{orig_args} #{test_opts}"
+ command = "#{Gem.ruby} #{load_paths} #{$0} '#{orig_args}' #{test_opts}"
# IO.popen lets us pass env in a cross-platform way
- child = IO.popen([env, command])
+ child = IO.popen(env, command)
begin
Process.wait(child.pid)
diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb
index c28de4e21c..b0d7f3299f 100644
--- a/activesupport/lib/active_support/time_with_zone.rb
+++ b/activesupport/lib/active_support/time_with_zone.rb
@@ -169,12 +169,13 @@ module ActiveSupport
end
end
- def encode_with(coder)
- if coder.respond_to?(:represent_object)
- coder.represent_object(nil, utc)
- else
- coder.represent_scalar(nil, utc.strftime("%Y-%m-%d %H:%M:%S.%9NZ"))
- end
+ def init_with(coder) #:nodoc:
+ initialize(coder['utc'], coder['zone'], coder['time'])
+ end
+
+ def encode_with(coder) #:nodoc:
+ coder.tag = '!ruby/object:ActiveSupport::TimeWithZone'
+ coder.map = { 'utc' => utc, 'zone' => time_zone, 'time' => time }
end
# Returns a string of the object's date and time in the format used by
diff --git a/activesupport/lib/active_support/values/time_zone.rb b/activesupport/lib/active_support/values/time_zone.rb
index da39f0d245..2699a064d7 100644
--- a/activesupport/lib/active_support/values/time_zone.rb
+++ b/activesupport/lib/active_support/values/time_zone.rb
@@ -348,24 +348,31 @@ module ActiveSupport
#
# Time.zone.parse('Mar 2000') # => Wed, 01 Mar 2000 00:00:00 HST -10:00
def parse(str, now=now())
- parts = Date._parse(str, false)
- return if parts.empty?
-
- time = Time.new(
- parts.fetch(:year, now.year),
- parts.fetch(:mon, now.month),
- parts.fetch(:mday, parts[:year] || parts[:mon] ? 1 : now.day),
- parts.fetch(:hour, 0),
- parts.fetch(:min, 0),
- parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0),
- parts.fetch(:offset, 0)
- )
-
- if parts[:offset]
- TimeWithZone.new(time.utc, self)
- else
- TimeWithZone.new(nil, self, time)
- end
+ parts_to_time(Date._parse(str, false), now)
+ end
+
+ # Parses +str+ according to +format+ and returns an ActiveSupport::TimeWithZone.
+ #
+ # Assumes that +str+ is a time in the time zone +self+,
+ # unless +format+ includes an explicit time zone.
+ # (This is the same behavior as +parse+.)
+ # In either case, the returned TimeWithZone has the timezone of +self+.
+ #
+ # Time.zone = 'Hawaii' # => "Hawaii"
+ # Time.zone.strptime('1999-12-31 14:00:00', '%Y-%m-%d %H:%M:%S') # => Fri, 31 Dec 1999 14:00:00 HST -10:00
+ #
+ # If upper components are missing from the string, they are supplied from
+ # TimeZone#now:
+ #
+ # Time.zone.now # => Fri, 31 Dec 1999 14:00:00 HST -10:00
+ # Time.zone.strptime('22:30:00', '%H:%M:%S') # => Fri, 31 Dec 1999 22:30:00 HST -10:00
+ #
+ # However, if the date component is not provided, but any other upper
+ # components are supplied, then the day of the month defaults to 1:
+ #
+ # Time.zone.strptime('Mar 2000', '%b %Y') # => Wed, 01 Mar 2000 00:00:00 HST -10:00
+ def strptime(str, format, now=now())
+ parts_to_time(DateTime._strptime(str, format), now)
end
# Returns an ActiveSupport::TimeWithZone instance representing the current
@@ -421,7 +428,36 @@ module ActiveSupport
tzinfo.periods_for_local(time)
end
+ def init_with(coder) #:nodoc:
+ initialize(coder['name'])
+ end
+
+ def encode_with(coder) #:nodoc:
+ coder.tag ="!ruby/object:#{self.class}"
+ coder.map = { 'name' => tzinfo.name }
+ end
+
private
+ def parts_to_time(parts, now)
+ return if parts.empty?
+
+ time = Time.new(
+ parts.fetch(:year, now.year),
+ parts.fetch(:mon, now.month),
+ parts.fetch(:mday, parts[:year] || parts[:mon] ? 1 : now.day),
+ parts.fetch(:hour, 0),
+ parts.fetch(:min, 0),
+ parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0),
+ parts.fetch(:offset, 0)
+ )
+
+ if parts[:offset]
+ TimeWithZone.new(time.utc, self)
+ else
+ TimeWithZone.new(nil, self, time)
+ end
+ end
+
def time_now
Time.now
end
diff --git a/activesupport/test/array_inquirer_test.rb b/activesupport/test/array_inquirer_test.rb
new file mode 100644
index 0000000000..b25e5cca86
--- /dev/null
+++ b/activesupport/test/array_inquirer_test.rb
@@ -0,0 +1,36 @@
+require 'abstract_unit'
+require 'active_support/core_ext/array'
+
+class ArrayInquirerTest < ActiveSupport::TestCase
+ def setup
+ @array_inquirer = ActiveSupport::ArrayInquirer.new([:mobile, :tablet])
+ end
+
+ def test_individual
+ assert @array_inquirer.mobile?
+ assert @array_inquirer.tablet?
+ assert_not @array_inquirer.desktop?
+ end
+
+ def test_any
+ assert @array_inquirer.any?(:mobile, :desktop)
+ assert @array_inquirer.any?(:watch, :tablet)
+ assert_not @array_inquirer.any?(:desktop, :watch)
+ end
+
+ def test_any_with_block
+ assert @array_inquirer.any? { |v| v == :mobile }
+ assert_not @array_inquirer.any? { |v| v == :desktop }
+ end
+
+ def test_respond_to
+ assert_respond_to @array_inquirer, :development?
+ end
+
+ def test_inquiry
+ result = [:mobile, :tablet].inquiry
+
+ assert_instance_of ActiveSupport::ArrayInquirer, result
+ assert_equal @array_inquirer, result
+ end
+end
diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb
index 4953550c45..527538ed9a 100644
--- a/activesupport/test/caching_test.rb
+++ b/activesupport/test/caching_test.rb
@@ -684,6 +684,7 @@ class FileStoreTest < ActiveSupport::TestCase
def teardown
FileUtils.rm_r(cache_dir)
+ rescue Errno::ENOENT
end
def cache_dir
@@ -703,6 +704,11 @@ class FileStoreTest < ActiveSupport::TestCase
assert File.exist?(filepath)
end
+ def test_clear_without_cache_dir
+ FileUtils.rm_r(cache_dir)
+ @cache.clear
+ end
+
def test_long_keys
@cache.write("a"*10000, 1)
assert_equal 1, @cache.read("a"*10000)
diff --git a/activesupport/test/callbacks_test.rb b/activesupport/test/callbacks_test.rb
index f6abef8cee..cda9732cae 100644
--- a/activesupport/test/callbacks_test.rb
+++ b/activesupport/test/callbacks_test.rb
@@ -73,8 +73,8 @@ module CallbacksTest
class PersonSkipper < Person
skip_callback :save, :before, :before_save_method, :if => :yes
- skip_callback :save, :after, :before_save_method, :unless => :yes
- skip_callback :save, :after, :before_save_method, :if => :no
+ skip_callback :save, :after, :after_save_method, :unless => :yes
+ skip_callback :save, :after, :after_save_method, :if => :no
skip_callback :save, :before, :before_save_method, :unless => :no
skip_callback :save, :before, CallbackClass , :if => :yes
def yes; true; end
@@ -1021,7 +1021,7 @@ module CallbacksTest
define_callbacks :foo
n.times { set_callback :foo, :before, callback }
def run; run_callbacks :foo; end
- def self.skip(thing); skip_callback :foo, :before, thing; end
+ def self.skip(*things); skip_callback :foo, :before, *things; end
}
end
@@ -1070,11 +1070,11 @@ module CallbacksTest
}
end
- def test_skip_lambda # removes nothing
+ def test_skip_lambda # raises error
calls = []
callback = ->(o) { calls << o }
klass = build_class(callback)
- 10.times { klass.skip callback }
+ assert_raises(ArgumentError) { klass.skip callback }
klass.new.run
assert_equal 10, calls.length
end
@@ -1088,11 +1088,29 @@ module CallbacksTest
assert_equal 0, calls.length
end
- def test_skip_eval # removes nothing
+ def test_skip_string # raises error
calls = []
klass = build_class("bar")
klass.class_eval { define_method(:bar) { calls << klass } }
- klass.skip "bar"
+ assert_raises(ArgumentError) { klass.skip "bar" }
+ klass.new.run
+ assert_equal 1, calls.length
+ end
+
+ def test_skip_undefined_callback # raises error
+ calls = []
+ klass = build_class(:bar)
+ klass.class_eval { define_method(:bar) { calls << klass } }
+ assert_raises(ArgumentError) { klass.skip :qux }
+ klass.new.run
+ assert_equal 1, calls.length
+ end
+
+ def test_skip_without_raise # removes nothing
+ calls = []
+ klass = build_class(:bar)
+ klass.class_eval { define_method(:bar) { calls << klass } }
+ klass.skip :qux, raise: false
klass.new.run
assert_equal 1, calls.length
end
diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb
index 92c233d567..79d78c02cd 100644
--- a/activesupport/test/core_ext/time_with_zone_test.rb
+++ b/activesupport/test/core_ext/time_with_zone_test.rb
@@ -1,6 +1,7 @@
require 'abstract_unit'
require 'active_support/time'
require 'time_zone_test_helpers'
+require 'active_support/core_ext/string/strip'
class TimeWithZoneTest < ActiveSupport::TestCase
include TimeZoneTestHelpers
@@ -123,11 +124,53 @@ class TimeWithZoneTest < ActiveSupport::TestCase
end
def test_to_yaml
- assert_match(/^--- 2000-01-01 00:00:00(\.0+)?\s*Z\n/, @twz.to_yaml)
+ yaml = <<-EOF.strip_heredoc
+ --- !ruby/object:ActiveSupport::TimeWithZone
+ utc: 2000-01-01 00:00:00.000000000 Z
+ zone: !ruby/object:ActiveSupport::TimeZone
+ name: America/New_York
+ time: 1999-12-31 19:00:00.000000000 Z
+ EOF
+
+ assert_equal(yaml, @twz.to_yaml)
end
def test_ruby_to_yaml
- assert_match(/---\s*\n:twz: 2000-01-01 00:00:00(\.0+)?\s*Z\n/, {:twz => @twz}.to_yaml)
+ yaml = <<-EOF.strip_heredoc
+ ---
+ twz: !ruby/object:ActiveSupport::TimeWithZone
+ utc: 2000-01-01 00:00:00.000000000 Z
+ zone: !ruby/object:ActiveSupport::TimeZone
+ name: America/New_York
+ time: 1999-12-31 19:00:00.000000000 Z
+ EOF
+
+ assert_equal(yaml, { 'twz' => @twz }.to_yaml)
+ end
+
+ def test_yaml_load
+ yaml = <<-EOF.strip_heredoc
+ --- !ruby/object:ActiveSupport::TimeWithZone
+ utc: 2000-01-01 00:00:00.000000000 Z
+ zone: !ruby/object:ActiveSupport::TimeZone
+ name: America/New_York
+ time: 1999-12-31 19:00:00.000000000 Z
+ EOF
+
+ assert_equal(@twz, YAML.load(yaml))
+ end
+
+ def test_ruby_yaml_load
+ yaml = <<-EOF.strip_heredoc
+ ---
+ twz: !ruby/object:ActiveSupport::TimeWithZone
+ utc: 2000-01-01 00:00:00.000000000 Z
+ zone: !ruby/object:ActiveSupport::TimeZone
+ name: America/New_York
+ time: 1999-12-31 19:00:00.000000000 Z
+ EOF
+
+ assert_equal({ 'twz' => @twz }, YAML.load(yaml))
end
def test_httpdate
diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb
index 702e26859a..4a1d90bfd6 100644
--- a/activesupport/test/dependencies_test.rb
+++ b/activesupport/test/dependencies_test.rb
@@ -160,7 +160,7 @@ class DependenciesTest < ActiveSupport::TestCase
def test_ensures_the_expected_constant_is_defined
with_autoloading_fixtures do
e = assert_raise(LoadError) { Typo }
- assert_match %r{Unable to autoload constant Typo, expected .*activesupport/test/autoloading_fixtures/typo.rb to define it}, e.message
+ assert_match %r{Unable to autoload constant Typo, expected .*/test/autoloading_fixtures/typo.rb to define it}, e.message
end
end
@@ -178,7 +178,7 @@ class DependenciesTest < ActiveSupport::TestCase
assert_equal 1, TypO
e = assert_raise(LoadError) { Typo }
- assert_match %r{Unable to autoload constant Typo, expected .*activesupport/test/autoloading_fixtures/typo.rb to define it}, e.message
+ assert_match %r{Unable to autoload constant Typo, expected .*/test/autoloading_fixtures/typo.rb to define it}, e.message
end
end
diff --git a/activesupport/test/time_zone_test.rb b/activesupport/test/time_zone_test.rb
index 7888b9919b..5e0474f449 100644
--- a/activesupport/test/time_zone_test.rb
+++ b/activesupport/test/time_zone_test.rb
@@ -311,6 +311,80 @@ class TimeZoneTest < ActiveSupport::TestCase
end
end
+ def test_strptime
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ twz = zone.strptime('1999-12-31 12:00:00', '%Y-%m-%d %H:%M:%S')
+ assert_equal Time.utc(1999,12,31,17), twz
+ assert_equal Time.utc(1999,12,31,12), twz.time
+ assert_equal Time.utc(1999,12,31,17), twz.utc
+ assert_equal zone, twz.time_zone
+ end
+
+ def test_strptime_with_nondefault_time_zone
+ with_tz_default ActiveSupport::TimeZone['Pacific Time (US & Canada)'] do
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ twz = zone.strptime('1999-12-31 12:00:00', '%Y-%m-%d %H:%M:%S')
+ assert_equal Time.utc(1999,12,31,17), twz
+ assert_equal Time.utc(1999,12,31,12), twz.time
+ assert_equal Time.utc(1999,12,31,17), twz.utc
+ assert_equal zone, twz.time_zone
+ end
+ end
+
+ def test_strptime_with_explicit_time_zone_as_abbrev
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ twz = zone.strptime('1999-12-31 12:00:00 PST', '%Y-%m-%d %H:%M:%S %Z')
+ assert_equal Time.utc(1999,12,31,20), twz
+ assert_equal Time.utc(1999,12,31,15), twz.time
+ assert_equal Time.utc(1999,12,31,20), twz.utc
+ assert_equal zone, twz.time_zone
+ end
+
+ def test_strptime_with_explicit_time_zone_as_h_offset
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ twz = zone.strptime('1999-12-31 12:00:00 -08', '%Y-%m-%d %H:%M:%S %:::z')
+ assert_equal Time.utc(1999,12,31,20), twz
+ assert_equal Time.utc(1999,12,31,15), twz.time
+ assert_equal Time.utc(1999,12,31,20), twz.utc
+ assert_equal zone, twz.time_zone
+ end
+
+ def test_strptime_with_explicit_time_zone_as_hm_offset
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ twz = zone.strptime('1999-12-31 12:00:00 -08:00', '%Y-%m-%d %H:%M:%S %:z')
+ assert_equal Time.utc(1999,12,31,20), twz
+ assert_equal Time.utc(1999,12,31,15), twz.time
+ assert_equal Time.utc(1999,12,31,20), twz.utc
+ assert_equal zone, twz.time_zone
+ end
+
+ def test_strptime_with_explicit_time_zone_as_hms_offset
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ twz = zone.strptime('1999-12-31 12:00:00 -08:00:00', '%Y-%m-%d %H:%M:%S %::z')
+ assert_equal Time.utc(1999,12,31,20), twz
+ assert_equal Time.utc(1999,12,31,15), twz.time
+ assert_equal Time.utc(1999,12,31,20), twz.utc
+ assert_equal zone, twz.time_zone
+ end
+
+ def test_strptime_with_almost_explicit_time_zone
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ twz = zone.strptime('1999-12-31 12:00:00 %Z', '%Y-%m-%d %H:%M:%S %%Z')
+ assert_equal Time.utc(1999,12,31,17), twz
+ assert_equal Time.utc(1999,12,31,12), twz.time
+ assert_equal Time.utc(1999,12,31,17), twz.utc
+ assert_equal zone, twz.time_zone
+ end
+
+ def test_strptime_with_day_omitted
+ with_env_tz 'US/Eastern' do
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ assert_equal Time.local(2000, 2, 1), zone.strptime('Feb', '%b', Time.local(2000, 1, 1))
+ assert_equal Time.local(2005, 2, 1), zone.strptime('Feb 2005', '%b %Y', Time.local(2000, 1, 1))
+ assert_equal Time.local(2005, 2, 2), zone.strptime('2 Feb 2005', '%e %b %Y', Time.local(2000, 1, 1))
+ end
+ end
+
def test_utc_offset_lazy_loaded_from_tzinfo_when_not_passed_in_to_initialize
tzinfo = TZInfo::Timezone.get('America/New_York')
zone = ActiveSupport::TimeZone.create(tzinfo.name, nil, tzinfo)
@@ -413,4 +487,13 @@ class TimeZoneTest < ActiveSupport::TestCase
assert ActiveSupport::TimeZone.us_zones.include?(ActiveSupport::TimeZone["Hawaii"])
assert !ActiveSupport::TimeZone.us_zones.include?(ActiveSupport::TimeZone["Kuala Lumpur"])
end
+
+ def test_to_yaml
+ assert_equal("--- !ruby/object:ActiveSupport::TimeZone\nname: Pacific/Honolulu\n", ActiveSupport::TimeZone["Hawaii"].to_yaml)
+ assert_equal("--- !ruby/object:ActiveSupport::TimeZone\nname: Europe/London\n", ActiveSupport::TimeZone["Europe/London"].to_yaml)
+ end
+
+ def test_yaml_load
+ assert_equal(ActiveSupport::TimeZone["Pacific/Honolulu"], YAML.load("--- !ruby/object:ActiveSupport::TimeZone\nname: Pacific/Honolulu\n"))
+ end
end
diff --git a/guides/CHANGELOG.md b/guides/CHANGELOG.md
index dd5ca4b395..fd177b4238 100644
--- a/guides/CHANGELOG.md
+++ b/guides/CHANGELOG.md
@@ -1,3 +1,7 @@
+* New section in Configuring: Configuring Active Job
+
+ *Eliot Sykes*
+
* New section in Active Record Association Basics: Single Table Inheritance
*Andrey Nering*
diff --git a/guides/bug_report_templates/generic_gem.rb b/guides/bug_report_templates/generic_gem.rb
new file mode 100644
index 0000000000..3e3f8593d4
--- /dev/null
+++ b/guides/bug_report_templates/generic_gem.rb
@@ -0,0 +1,15 @@
+# Activate the gems you are reporting the issue against.
+gem 'activesupport', '4.2.0'
+require 'active_support'
+require 'active_support/core_ext/object/blank'
+require 'minitest/autorun'
+
+# Ensure backward compatibility with Minitest 4
+Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test)
+
+class BugTest < Minitest::Test
+ def test_stuff
+ assert "zomg".present?
+ refute "".present?
+ end
+end
diff --git a/guides/bug_report_templates/generic_master.rb b/guides/bug_report_templates/generic_master.rb
new file mode 100644
index 0000000000..d930482d4e
--- /dev/null
+++ b/guides/bug_report_templates/generic_master.rb
@@ -0,0 +1,26 @@
+unless File.exist?('Gemfile')
+ File.write('Gemfile', <<-GEMFILE)
+ source 'https://rubygems.org'
+ gem 'rails', github: 'rails/rails'
+ gem 'arel', github: 'rails/arel'
+ GEMFILE
+
+ system 'bundle'
+end
+
+require 'bundler'
+Bundler.setup(:default)
+
+require 'active_support'
+require 'active_support/core_ext/object/blank'
+require 'minitest/autorun'
+
+# Ensure backward compatibility with Minitest 4
+Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test)
+
+class BugTest < Minitest::Test
+ def test_stuff
+ assert "zomg".present?
+ refute "".present?
+ end
+end
diff --git a/guides/rails_guides/levenshtein.rb b/guides/rails_guides/levenshtein.rb
index 36183fd321..049f633258 100644
--- a/guides/rails_guides/levenshtein.rb
+++ b/guides/rails_guides/levenshtein.rb
@@ -14,10 +14,13 @@ module RailsGuides
d = (0..m).to_a
x = nil
- str1.each_char.each_with_index do |char1,i|
+ # avoid duplicating an enumerable object in the loop
+ str2_codepoint_enumerable = str2.each_codepoint
+
+ str1.each_codepoint.with_index do |char1, i|
e = i+1
- str2.each_char.each_with_index do |char2,j|
+ str2_codepoint_enumerable.with_index do |char2, j|
cost = (char1 == char2) ? 0 : 1
x = [
d[j+1] + 1, # insertion
diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md
index 684bd286bc..d5b3766a5b 100644
--- a/guides/source/4_2_release_notes.md
+++ b/guides/source/4_2_release_notes.md
@@ -214,9 +214,8 @@ end
Due to a [change in Rack](https://github.com/rack/rack/commit/28b014484a8ac0bbb388e7eaeeef159598ec64fc),
`rails server` now listens on `localhost` instead of `0.0.0.0` by default. This
-should have minimal impact on the standard development workflow as both
-http://127.0.0.1:3000 and http://localhost:3000 will continue to work as before
-on your own machine.
+should have minimal impact on the standard development workflow as http://localhost:3000
+will continue to work as before on your own machine.
However, with this change you will no longer be able to access the Rails
server from a different machine, for example if your development environment
diff --git a/guides/source/action_controller_overview.md b/guides/source/action_controller_overview.md
index 8c1551f4a1..fab0e20aba 100644
--- a/guides/source/action_controller_overview.md
+++ b/guides/source/action_controller_overview.md
@@ -667,11 +667,11 @@ You may notice in the above code that we're using `render xml: @users`, not `ren
Filters
-------
-Filters are methods that are run before, after or "around" a controller action.
+Filters are methods that are run "before", "after" or "around" a controller action.
Filters are inherited, so if you set a filter on `ApplicationController`, it will be run on every controller in your application.
-"Before" filters may halt the request cycle. A common "before" filter is one which requires that a user is logged in for an action to be run. You can define the filter method this way:
+"before" filters may halt the request cycle. A common "before" filter is one which requires that a user is logged in for an action to be run. You can define the filter method this way:
```ruby
class ApplicationController < ActionController::Base
@@ -704,9 +704,9 @@ Now, the `LoginsController`'s `new` and `create` actions will work as before wit
In addition to "before" filters, you can also run filters after an action has been executed, or both before and after.
-"After" filters are similar to "before" filters, but because the action has already been run they have access to the response data that's about to be sent to the client. Obviously, "after" filters cannot stop the action from running.
+"after" filters are similar to "before" filters, but because the action has already been run they have access to the response data that's about to be sent to the client. Obviously, "after" filters cannot stop the action from running.
-"Around" filters are responsible for running their associated actions by yielding, similar to how Rack middlewares work.
+"around" filters are responsible for running their associated actions by yielding, similar to how Rack middlewares work.
For example, in a website where changes have an approval workflow an administrator could be able to preview them easily, just apply them within a transaction:
diff --git a/guides/source/action_view_overview.md b/guides/source/action_view_overview.md
index 71f3f8882c..3541bbaa93 100644
--- a/guides/source/action_view_overview.md
+++ b/guides/source/action_view_overview.md
@@ -356,50 +356,51 @@ Supposing we use the same `_box` partial from above, this would produce the same
View Paths
----------
-TODO...
+When rendering a response, the controller needs to resolve where the different
+views are located. By default it only looks inside the `app/views` directory.
-Overview of helpers provided by Action View
--------------------------------------------
+We can add other locations and give them a certain precedence when resolving
+paths using the `prepend_view_path` and `append_view_path` methods.
-WIP: Not all the helpers are listed here. For a full list see the [API documentation](http://api.rubyonrails.org/classes/ActionView/Helpers.html)
+### Prepend view path
-The following is only a brief overview summary of the helpers available in Action View. It's recommended that you review the [API Documentation](http://api.rubyonrails.org/classes/ActionView/Helpers.html), which covers all of the helpers in more detail, but this should serve as a good starting point.
+This can be helpful for example, when we want to put views inside a different
+directory for subdomains.
-### AssetTagHelper
+We can do this by using:
-This module provides methods for generating HTML that links views to assets such as images, JavaScript files, stylesheets, and feeds.
+```ruby
+prepend_view_path "app/views/#{request.subdomain}"
+```
-By default, Rails links to these assets on the current host in the public folder, but you can direct Rails to link to assets from a dedicated assets server by setting `config.action_controller.asset_host` in the application configuration, typically in `config/environments/production.rb`. For example, let's say your asset host is `assets.example.com`:
+Then Action View will look first in this directory when resolving views.
+
+### Append view path
+
+Similarly, we can append paths:
```ruby
-config.action_controller.asset_host = "assets.example.com"
-image_tag("rails.png") # => <img src="http://assets.example.com/images/rails.png" alt="Rails" />
+append_view_path "app/views/direct"
```
-#### register_javascript_expansion
+This will add `app/views/direct` to the end of the lookup paths.
-Register one or more JavaScript files to be included when symbol is passed to javascript_include_tag. This method is typically intended to be called from plugin initialization to register JavaScript files that the plugin installed in `vendor/assets/javascripts`.
+Overview of helpers provided by Action View
+-------------------------------------------
-```ruby
-ActionView::Helpers::AssetTagHelper.register_javascript_expansion monkey: ["head", "body", "tail"]
+WIP: Not all the helpers are listed here. For a full list see the [API documentation](http://api.rubyonrails.org/classes/ActionView/Helpers.html)
-javascript_include_tag :monkey # =>
- <script src="/assets/head.js"></script>
- <script src="/assets/body.js"></script>
- <script src="/assets/tail.js"></script>
-```
+The following is only a brief overview summary of the helpers available in Action View. It's recommended that you review the [API Documentation](http://api.rubyonrails.org/classes/ActionView/Helpers.html), which covers all of the helpers in more detail, but this should serve as a good starting point.
-#### register_stylesheet_expansion
+### AssetTagHelper
-Register one or more stylesheet files to be included when symbol is passed to `stylesheet_link_tag`. This method is typically intended to be called from plugin initialization to register stylesheet files that the plugin installed in `vendor/assets/stylesheets`.
+This module provides methods for generating HTML that links views to assets such as images, JavaScript files, stylesheets, and feeds.
-```ruby
-ActionView::Helpers::AssetTagHelper.register_stylesheet_expansion monkey: ["head", "body", "tail"]
+By default, Rails links to these assets on the current host in the public folder, but you can direct Rails to link to assets from a dedicated assets server by setting `config.action_controller.asset_host` in the application configuration, typically in `config/environments/production.rb`. For example, let's say your asset host is `assets.example.com`:
-stylesheet_link_tag :monkey # =>
- <link href="/assets/head.css" media="screen" rel="stylesheet" />
- <link href="/assets/body.css" media="screen" rel="stylesheet" />
- <link href="/assets/tail.css" media="screen" rel="stylesheet" />
+```ruby
+config.action_controller.asset_host = "assets.example.com"
+image_tag("rails.png") # => <img src="http://assets.example.com/images/rails.png" alt="Rails" />
```
#### auto_discovery_link_tag
@@ -408,7 +409,7 @@ Returns a link tag that browsers and feed readers can use to auto-detect an RSS
```ruby
auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", { title: "RSS Feed" }) # =>
- <link rel="alternate" type="application/rss+xml" title="RSS Feed" href="http://www.example.com/feed" />
+ <link rel="alternate" type="application/rss+xml" title="RSS Feed" href="http://www.example.com/feed.rss" />
```
#### image_path
@@ -492,7 +493,7 @@ Returns a stylesheet link tag for the sources specified as arguments. If you don
stylesheet_link_tag "application" # => <link href="/assets/application.css" media="screen" rel="stylesheet" />
```
-You can also include all styles in the stylesheet directory using :all as the source:
+You can also include all styles in the stylesheet directory using `:all` as the source:
```ruby
stylesheet_link_tag :all
@@ -507,7 +508,7 @@ stylesheet_link_tag :all, cache: true
#### stylesheet_path
-Computes the path to a stylesheet asset in the `app/assets/stylesheets` directory. If the source filename has no extension, .css will be appended. Full paths from the document root will be passed through. Used internally by stylesheet_link_tag to build the stylesheet path.
+Computes the path to a stylesheet asset in the `app/assets/stylesheets` directory. If the source filename has no extension, `.css` will be appended. Full paths from the document root will be passed through. Used internally by stylesheet_link_tag to build the stylesheet path.
```ruby
stylesheet_path "application" # => /assets/application.css
@@ -808,9 +809,9 @@ third:
Form helpers are designed to make working with models much easier compared to using just standard HTML elements by providing a set of methods for creating forms based on your models. This helper generates the HTML for forms, providing a method for each sort of input (e.g., text, password, select, and so on). When the form is submitted (i.e., when the user hits the submit button or form.submit is called via JavaScript), the form inputs will be bundled into the params object and passed back to the controller.
-There are two types of form helpers: those that specifically work with model attributes and those that don't. This helper deals with those that work with model attributes; to see an example of form helpers that don't work with model attributes, check the ActionView::Helpers::FormTagHelper documentation.
+There are two types of form helpers: those that specifically work with model attributes and those that don't. This helper deals with those that work with model attributes; to see an example of form helpers that don't work with model attributes, check the `ActionView::Helpers::FormTagHelper` documentation.
-The core method of this helper, form_for, gives you the ability to create a form for a model instance; for example, let's say that you have a model Person and want to create a new instance of it:
+The core method of this helper, `form_for`, gives you the ability to create a form for a model instance; for example, let's say that you have a model Person and want to create a new instance of it:
```html+erb
# Note: a @person variable will have been created in the controller (e.g. @person = Person.new)
@@ -852,7 +853,7 @@ check_box("article", "validated")
#### fields_for
-Creates a scope around a specific model object like form_for, but doesn't create the form tags themselves. This makes fields_for suitable for specifying additional model objects in the same form:
+Creates a scope around a specific model object like `form_for`, but doesn't create the form tags themselves. This makes `fields_for` suitable for specifying additional model objects in the same form:
```html+erb
<%= form_for @person, url: { action: "update" } do |person_form| %>
@@ -1146,7 +1147,7 @@ Returns a string of option tags that have been compiled by iterating over the `c
# options_from_collection_for_select(collection, value_method, text_method, selected = nil)
```
-For example, imagine a loop iterating over each person in @project.people to generate an input tag:
+For example, imagine a loop iterating over each person in `@project.people` to generate an input tag:
```ruby
options_from_collection_for_select(@project.people, "id", "name")
@@ -1361,22 +1362,6 @@ date_field_tag "dob"
Provides functionality for working with JavaScript in your views.
-#### button_to_function
-
-Returns a button that'll trigger a JavaScript function using the onclick handler. Examples:
-
-```ruby
-button_to_function "Greeting", "alert('Hello world!')"
-button_to_function "Delete", "if (confirm('Really?')) do_delete()"
-button_to_function "Details" do |page|
- page[:details].visual_effect :toggle_slide
-end
-```
-
-#### define_javascript_functions
-
-Includes the Action Pack JavaScript libraries inside a single `script` tag.
-
#### escape_javascript
Escape carrier returns and single and double quotes for JavaScript segments.
@@ -1397,15 +1382,6 @@ alert('All is good')
</script>
```
-#### link_to_function
-
-Returns a link that will trigger a JavaScript function using the onclick handler and return false after the fact.
-
-```ruby
-link_to_function "Greeting", "alert('Hello world!')"
-# => <a onclick="alert('Hello world!'); return false;" href="#">Greeting</a>
-```
-
### NumberHelper
Provides methods for converting numbers into formatted strings. Methods are provided for phone numbers, currency, percentage, precision, positional notation, and file size.
@@ -1472,7 +1448,7 @@ This sanitize helper will HTML encode all tags and strip all attributes that are
sanitize @article.body
```
-If either the :attributes or :tags options are passed, only the mentioned tags and attributes are allowed and nothing else.
+If either the `:attributes` or `:tags` options are passed, only the mentioned tags and attributes are allowed and nothing else.
```ruby
sanitize @article.body, tags: %w(table tr td), attributes: %w(id class style)
diff --git a/guides/source/active_job_basics.md b/guides/source/active_job_basics.md
index 953c29719d..29d0c32b09 100644
--- a/guides/source/active_job_basics.md
+++ b/guides/source/active_job_basics.md
@@ -11,7 +11,7 @@ After reading this guide, you will know:
* How to create jobs.
* How to enqueue jobs.
* How to run jobs in the background.
-* How to send emails from your application async.
+* How to send emails from your application asynchronously.
--------------------------------------------------------------------------------
@@ -319,3 +319,10 @@ class GuestsCleanupJob < ActiveJob::Base
end
end
```
+
+
+Job Testing
+--------------
+
+You can find detailed instructions on how to test your jobs in the
+[testing guide](testing.html#testing-jobs).
diff --git a/guides/source/active_record_migrations.md b/guides/source/active_record_migrations.md
index de8bbc4174..7a994cc5de 100644
--- a/guides/source/active_record_migrations.md
+++ b/guides/source/active_record_migrations.md
@@ -501,7 +501,7 @@ If the helpers provided by Active Record aren't enough you can use the `execute`
method to execute arbitrary SQL:
```ruby
-Product.connection.execute('UPDATE `products` SET `price`=`free` WHERE 1')
+Product.connection.execute("UPDATE products SET price = 'free' WHERE 1=1")
```
For more details and examples of individual methods, check the API documentation.
diff --git a/guides/source/active_record_postgresql.md b/guides/source/active_record_postgresql.md
index 4d9c1776f4..66a11e5785 100644
--- a/guides/source/active_record_postgresql.md
+++ b/guides/source/active_record_postgresql.md
@@ -245,6 +245,7 @@ article.save!
* [type definition](http://www.postgresql.org/docs/9.3/static/datatype-uuid.html)
* [generator functions](http://www.postgresql.org/docs/9.3/static/uuid-ossp.html)
+NOTE: you need to enable the `uuid-ossp` extension to use uuid.
```ruby
# db/migrate/20131220144913_create_revisions.rb
@@ -263,6 +264,28 @@ revision = Revision.first
revision.identifier # => "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11"
```
+You can use `uuid` type to define references in migrations
+
+```ruby
+# db/migrate/20150418012400_create_blog.rb
+create_table :posts, id: :uuid
+
+create_table :comments, id: :uuid do |t|
+ # t.belongs_to :post, type: :uuid
+ t.references :post, type: :uuid
+end
+
+# app/models/post.rb
+class Post < ActiveRecord::Base
+ has_many :comments
+end
+
+# app/models/comment.rb
+class Comment < ActiveRecord::Base
+ belongs_to :post
+end
+```
+
### Bit String Types
* [type definition](http://www.postgresql.org/docs/9.3/static/datatype-bit.html)
diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md
index d6f3506aa5..2f10bc4e7c 100644
--- a/guides/source/active_record_querying.md
+++ b/guides/source/active_record_querying.md
@@ -317,7 +317,7 @@ end
The `find_each` method accepts most of the options allowed by the regular `find` method, except for `:order` and `:limit`, which are reserved for internal use by `find_each`.
-Two additional options, `:batch_size` and `:begin_at`, are available as well.
+Three additional options, `:batch_size`, `:begin_at` and `:end_at`, are available as well.
**`:batch_size`**
@@ -348,7 +348,7 @@ Another example would be if you wanted multiple workers handling the same proces
Similar to the `:begin_at` option, `:end_at` allows you to configure the last ID of the sequence whenever the highest ID is not the one you need.
This would be useful, for example, if you wanted to run a batch process, using a subset of records based on `:begin_at` and `:end_at`
-For example, to send newsletters only to users with the primary key starting from 2000 up to 10000 and to retrieve them in batches of 1000:
+For example, to send newsletters only to users with the primary key starting from 2000 up to 10000 and to retrieve them in batches of 5000:
```ruby
User.find_each(begin_at: 2000, end_at: 10000, batch_size: 5000) do |user|
@@ -529,7 +529,7 @@ Client.order("orders_count ASC, created_at DESC")
Client.order("orders_count ASC", "created_at DESC")
```
-If you want to call `order` multiple times e.g. in different context, new order will append previous one
+If you want to call `order` multiple times e.g. in different context, new order will append previous one:
```ruby
Client.order("orders_count ASC").order("created_at DESC")
@@ -655,7 +655,7 @@ GROUP BY status
Having
------
-SQL uses the `HAVING` clause to specify conditions on the `GROUP BY` fields. You can add the `HAVING` clause to the SQL fired by the `Model.find` by adding the `:having` option to the find.
+SQL uses the `HAVING` clause to specify conditions on the `GROUP BY` fields. You can add the `HAVING` clause to the SQL fired by the `Model.find` by adding the `having` method to the find.
For example:
diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md
index f3d8e05089..2a643680f7 100644
--- a/guides/source/active_support_core_extensions.md
+++ b/guides/source/active_support_core_extensions.md
@@ -475,7 +475,7 @@ The methods `silence_warnings` and `enable_warnings` change the value of `$VERBO
silence_warnings { Object.const_set "RAILS_DEFAULT_LOGGER", logger }
```
-Silencing exceptions is also possible with `suppress`. This method receives an arbitrary number of exception classes. If an exception is raised during the execution of the block and is `kind_of?` any of the arguments, `suppress` captures it and returns silently. Otherwise the exception is reraised:
+Silencing exceptions is also possible with `suppress`. This method receives an arbitrary number of exception classes. If an exception is raised during the execution of the block and is `kind_of?` any of the arguments, `suppress` captures it and returns silently. Otherwise the exception is not captured:
```ruby
# If the user is locked, the increment is lost, no big deal.
@@ -2188,7 +2188,7 @@ The method `without` returns a copy of an enumerable with the specified elements
removed:
```ruby
-people.without("Aaron", "Todd")
+["David", "Rafael", "Aaron", "Todd"].without("Aaron", "Todd") # => ["David", "Rafael"]
```
NOTE: Defined in `active_support/core_ext/enumerable.rb`.
@@ -2428,7 +2428,7 @@ The method `Array.wrap` wraps its argument in an array unless it is already an a
Specifically:
-* If the argument is `nil` an empty list is returned.
+* If the argument is `nil` an empty array is returned.
* Otherwise, if the argument responds to `to_ary` it is invoked, and if the value of `to_ary` is not `nil`, it is returned.
* Otherwise, an array with the argument as its single element is returned.
@@ -2440,9 +2440,9 @@ Array.wrap(0) # => [0]
This method is similar in purpose to `Kernel#Array`, but there are some differences:
-* If the argument responds to `to_ary` the method is invoked. `Kernel#Array` moves on to try `to_a` if the returned value is `nil`, but `Array.wrap` returns `nil` right away.
+* If the argument responds to `to_ary` the method is invoked. `Kernel#Array` moves on to try `to_a` if the returned value is `nil`, but `Array.wrap` returns an array with the argument as its single element right away.
* If the returned value from `to_ary` is neither `nil` nor an `Array` object, `Kernel#Array` raises an exception, while `Array.wrap` does not, it just returns the value.
-* It does not call `to_a` on the argument, though special-cases `nil` to return an empty array.
+* It does not call `to_a` on the argument, if the argument does not respond to +to_ary+ it returns an array with the argument as its single element.
The last point is particularly worth comparing for some enumerables:
@@ -3040,53 +3040,6 @@ The method `Range#overlaps?` says whether any two given ranges have non-void int
NOTE: Defined in `active_support/core_ext/range/overlaps.rb`.
-Extensions to `Proc`
---------------------
-
-### `bind`
-
-As you surely know Ruby has an `UnboundMethod` class whose instances are methods that belong to the limbo of methods without a self. The method `Module#instance_method` returns an unbound method for example:
-
-```ruby
-Hash.instance_method(:delete) # => #<UnboundMethod: Hash#delete>
-```
-
-An unbound method is not callable as is, you need to bind it first to an object with `bind`:
-
-```ruby
-clear = Hash.instance_method(:clear)
-clear.bind({a: 1}).call # => {}
-```
-
-Active Support defines `Proc#bind` with an analogous purpose:
-
-```ruby
-Proc.new { size }.bind([]).call # => 0
-```
-
-As you see that's callable and bound to the argument, the return value is indeed a `Method`.
-
-NOTE: To do so `Proc#bind` actually creates a method under the hood. If you ever see a method with a weird name like `__bind_1256598120_237302` in a stack trace you know now where it comes from.
-
-Action Pack uses this trick in `rescue_from` for example, which accepts the name of a method and also a proc as callbacks for a given rescued exception. It has to call them in either case, so a bound method is returned by `handler_for_rescue`, thus simplifying the code in the caller:
-
-```ruby
-def handler_for_rescue(exception)
- _, rescuer = Array(rescue_handlers).reverse.detect do |klass_name, handler|
- ...
- end
-
- case rescuer
- when Symbol
- method(rescuer)
- when Proc
- rescuer.bind(self)
- end
-end
-```
-
-NOTE: Defined in `active_support/core_ext/proc.rb`.
-
Extensions to `Date`
--------------------
diff --git a/guides/source/active_support_instrumentation.md b/guides/source/active_support_instrumentation.md
index 352da43b5f..1b14bedfbf 100644
--- a/guides/source/active_support_instrumentation.md
+++ b/guides/source/active_support_instrumentation.md
@@ -19,7 +19,7 @@ After reading this guide, you will know:
Introduction to instrumentation
-------------------------------
-The instrumentation API provided by Active Support allows developers to provide hooks which other developers may hook into. There are several of these within the Rails framework, as described below in (TODO: link to section detailing each hook point). With this API, developers can choose to be notified when certain events occur inside their application or another piece of Ruby code.
+The instrumentation API provided by Active Support allows developers to provide hooks which other developers may hook into. There are several of these within the [Rails framework](#rails-framework-hooks). With this API, developers can choose to be notified when certain events occur inside their application or another piece of Ruby code.
For example, there is a hook provided within Active Record that is called every time Active Record uses an SQL query on a database. This hook could be **subscribed** to, and used to track the number of queries during a certain action. There's another hook around the processing of an action of a controller. This could be used, for instance, to track how long a specific action has taken.
diff --git a/guides/source/asset_pipeline.md b/guides/source/asset_pipeline.md
index 9da0ef1eb3..4a610e8458 100644
--- a/guides/source/asset_pipeline.md
+++ b/guides/source/asset_pipeline.md
@@ -643,7 +643,7 @@ above. By default Rails assumes assets have been precompiled and will be
served as static assets by your web server.
During the precompilation phase an MD5 is generated from the contents of the
-compiled files, and inserted into the filenames as they are written to disc.
+compiled files, and inserted into the filenames as they are written to disk.
These fingerprinted names are used by the Rails helpers in place of the manifest
name.
@@ -790,41 +790,6 @@ location ~ ^/assets/ {
}
```
-#### GZip Compression
-
-When files are precompiled, Sprockets also creates a
-[gzipped](http://en.wikipedia.org/wiki/Gzip) (.gz) version of your assets. Web
-servers are typically configured to use a moderate compression ratio as a
-compromise, but since precompilation happens once, Sprockets uses the maximum
-compression ratio, thus reducing the size of the data transfer to the minimum.
-On the other hand, web servers can be configured to serve compressed content
-directly from disk, rather than deflating non-compressed files themselves.
-
-NGINX is able to do this automatically enabling `gzip_static`:
-
-```nginx
-location ~ ^/(assets)/ {
- root /path/to/public;
- gzip_static on; # to serve pre-gzipped version
- expires max;
- add_header Cache-Control public;
-}
-```
-
-This directive is available if the core module that provides this feature was
-compiled with the web server. Ubuntu/Debian packages, even `nginx-light`, have
-the module compiled. Otherwise, you may need to perform a manual compilation:
-
-```bash
-./configure --with-http_gzip_static_module
-```
-
-If you're compiling NGINX with Phusion Passenger you'll need to pass that option
-when prompted.
-
-A robust configuration for Apache is possible but tricky; please Google around.
-(Or help update this Guide if you have a good configuration example for Apache.)
-
### Local Precompilation
There are several reasons why you might want to precompile your assets locally.
diff --git a/guides/source/association_basics.md b/guides/source/association_basics.md
index ec6017ff73..412cfd198a 100644
--- a/guides/source/association_basics.md
+++ b/guides/source/association_basics.md
@@ -146,6 +146,17 @@ class CreateSuppliers < ActiveRecord::Migration
end
```
+Depending on the use case, you might also need to create a unique index and/or
+a foreign key constraint on the supplier column for the accounts table. In this
+case, the column definition might look like this:
+
+```ruby
+create_table :accounts do |t|
+ t.belongs_to :supplier, index: true, unique: true, foreign_key: true
+ # ...
+end
+```
+
### The `has_many` Association
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:
@@ -829,6 +840,7 @@ The `belongs_to` association supports these options:
* `:counter_cache`
* `:dependent`
* `:foreign_key`
+* `:primary_key`
* `:inverse_of`
* `:polymorphic`
* `:touch`
@@ -875,18 +887,26 @@ end
With this declaration, Rails will keep the cache value up to date, and then return that value in response to the `size` method.
-Although the `:counter_cache` option is specified on the model that includes the `belongs_to` declaration, the actual column must be added to the _associated_ model. In the case above, you would need to add a column named `orders_count` to the `Customer` model. You can override the default column name if you need to:
+Although the `:counter_cache` option is specified on the model that includes
+the `belongs_to` declaration, the actual column must be added to the
+_associated_ (`has_many`) model. In the case above, you would need to add a
+column named `orders_count` to the `Customer` model.
+
+You can override the default column name by specifying a custom column name in
+the `counter_cache` declaration instead of `true`. For example, to use
+`count_of_orders` instead of `orders_count`:
```ruby
class Order < ActiveRecord::Base
belongs_to :customer, counter_cache: :count_of_orders
end
class Customer < ActiveRecord::Base
- has_many :orders, counter_cache: :count_of_orders
+ has_many :orders
end
```
-NOTE: You only need to specify the :counter_cache option on the "has_many side" of the association when using a custom name for the counter cache.
+NOTE: You only need to specify the :counter_cache option on the `belongs_to`
+side of the association.
Counter cache columns are added to the containing model's list of read-only attributes through `attr_readonly`.
@@ -913,6 +933,26 @@ end
TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
+##### `:primary_key`
+
+By convention, Rails assumes that the `id` column is used to hold the primary key
+of its tables. The `:primary_key` option allows you to specify a different column.
+
+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
+ self.primary_key = 'guid' # primary key is guid and not id
+end
+
+class Todo < ActiveRecord::Base
+ belongs_to :user, primary_key: 'guid'
+end
+```
+
+When we execute `@user.todos.create` then the `@todo` record will have its
+`user_id` value as the `guid` value of `@user`.
+
##### `:inverse_of`
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.
@@ -1628,7 +1668,7 @@ You can use any of the standard [querying methods](active_record_querying.html)
* `order`
* `readonly`
* `select`
-* `uniq`
+* `distinct`
##### `where`
diff --git a/guides/source/autoloading_and_reloading_constants.md b/guides/source/autoloading_and_reloading_constants.md
index c6149abcba..2b6d7e4044 100644
--- a/guides/source/autoloading_and_reloading_constants.md
+++ b/guides/source/autoloading_and_reloading_constants.md
@@ -466,9 +466,7 @@ by adding this to `config/application.rb`:
config.autoload_paths << "#{Rails.root}/lib"
```
-`config.autoload_paths` is accessible from environment-specific configuration
-files, but any changes made to it outside `config/application.rb` don't have any
-effect.
+`config.autoload_paths` is not changeable from environment-specific configuration files.
The value of `autoload_paths` can be inspected. In a just generated application
it is (edited):
diff --git a/guides/source/command_line.md b/guides/source/command_line.md
index b409f20122..315d8c14b6 100644
--- a/guides/source/command_line.md
+++ b/guides/source/command_line.md
@@ -402,8 +402,8 @@ INFO: You can also use `rake -T` to get the list of tasks.
$ bin/rake about
About your application's environment
Rails version 5.0.0
-Ruby version 2.2.1 (x86_64-linux)
-RubyGems version 2.4.5
+Ruby version 2.2.2 (x86_64-linux)
+RubyGems version 2.4.6
Rack version 1.6
JavaScript Runtime Node.js (V8)
Middleware Rack::Sendfile, ActionDispatch::Static, Rack::Lock, #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x007ffd131a7c88>, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::DebugExceptions, ActionDispatch::RemoteIp, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::Migration::CheckPending, ActiveRecord::ConnectionAdapters::ConnectionManagement, ActiveRecord::QueryCache, ActionDispatch::Cookies, ActionDispatch::Session::CookieStore, ActionDispatch::Flash, ActionDispatch::ParamsParser, Rack::Head, Rack::ConditionalGet, Rack::ETag
@@ -423,7 +423,7 @@ If you want to clear `public/assets` completely, you can use `rake assets:clobbe
The most common tasks of the `db:` Rake namespace are `migrate` and `create`, and it will pay off to try out all of the migration rake tasks (`up`, `down`, `redo`, `reset`). `rake db:version` is useful when troubleshooting, telling you the current version of the database.
-More information about migrations can be found in the [Migrations](migrations.html) guide.
+More information about migrations can be found in the [Migrations](active_record_migrations.html) guide.
### `notes`
@@ -470,7 +470,7 @@ app/models/article.rb:
NOTE. When using specific annotations and custom annotations, the annotation name (FIXME, BUG etc) is not displayed in the output lines.
-By default, `rake notes` will look in the `app`, `config`, `lib`, `bin` and `test` directories. If you would like to search other directories, you can provide them as a comma separated list in an environment variable `SOURCE_ANNOTATION_DIRECTORIES`.
+By default, `rake notes` will look in the `app`, `config`, `db`, `lib` and `test` directories. If you would like to search other directories, you can provide them as a comma separated list in an environment variable `SOURCE_ANNOTATION_DIRECTORIES`.
```bash
$ export SOURCE_ANNOTATION_DIRECTORIES='spec,vendor'
diff --git a/guides/source/configuring.md b/guides/source/configuring.md
index 6f32e6484f..938ba2c89f 100644
--- a/guides/source/configuring.md
+++ b/guides/source/configuring.md
@@ -114,7 +114,7 @@ numbers. New applications filter out passwords by adding the following `config.f
defaults to `:debug` for all environments. The available log levels are: `:debug`,
`:info`, `:warn`, `:error`, `:fatal`, and `:unknown`.
-* `config.log_tags` accepts a list of methods that the `request` object responds to. This makes it easy to tag log lines with debug information like subdomain and request id - both very helpful in debugging multi-user production applications.
+* `config.log_tags` accepts a list of: methods that the `request` object responds to, a `Proc` that accepts the `request` object, or something that responds to `to_s`. This makes it easy to tag log lines with debug information like subdomain and request id - both very helpful in debugging multi-user production applications.
* `config.logger` accepts a logger conforming to the interface of Log4r or the default Ruby `Logger` class. Defaults to an instance of `ActiveSupport::Logger`.
@@ -424,13 +424,23 @@ encrypted cookies salt value. Defaults to `'signed encrypted cookie'`.
end
```
-* `config.action_view.default_form_builder` tells Rails which form builder to use by default. The default is `ActionView::Helpers::FormBuilder`. If you want your form builder class to be loaded after initialization (so it's reloaded on each request in development), you can pass it as a `String`
+* `config.action_view.default_form_builder` tells Rails which form builder to
+ use by default. The default is `ActionView::Helpers::FormBuilder`. If you
+ want your form builder class to be loaded after initialization (so it's
+ reloaded on each request in development), you can pass it as a `String`.
* `config.action_view.logger` accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Action View. Set to `nil` to disable logging.
* `config.action_view.erb_trim_mode` gives the trim mode to be used by ERB. It defaults to `'-'`, which turns on trimming of tail spaces and newline when using `<%= -%>` or `<%= =%>`. See the [Erubis documentation](http://www.kuwata-lab.com/erubis/users-guide.06.html#topics-trimspaces) for more information.
-* `config.action_view.embed_authenticity_token_in_remote_forms` allows you to set the default behavior for `authenticity_token` in forms with `:remote => true`. By default it's set to false, which means that remote forms will not include `authenticity_token`, which is helpful when you're fragment-caching the form. Remote forms get the authenticity from the `meta` tag, so embedding is unnecessary unless you support browsers without JavaScript. In such case you can either pass `:authenticity_token => true` as a form option or set this config setting to `true`
+* `config.action_view.embed_authenticity_token_in_remote_forms` allows you to
+ set the default behavior for `authenticity_token` in forms with `remote:
+ true`. By default it's set to false, which means that remote forms will not
+ include `authenticity_token`, which is helpful when you're fragment-caching
+ the form. Remote forms get the authenticity from the `meta` tag, so embedding
+ is unnecessary unless you support browsers without JavaScript. In such case
+ you can either pass `authenticity_token: true` as a form option or set this
+ config setting to `true`.
* `config.action_view.prefix_partial_path_with_controller_namespace` determines whether or not partials are looked up from a subdirectory in templates rendered from namespaced controllers. For example, consider a controller named `Admin::ArticlesController` which renders this template:
@@ -440,7 +450,8 @@ encrypted cookies salt value. Defaults to `'signed encrypted cookie'`.
The default setting is `true`, which uses the partial at `/admin/articles/_article.erb`. Setting the value to `false` would render `/articles/_article.erb`, which is the same behavior as rendering from a non-namespaced controller such as `ArticlesController`.
-* `config.action_view.raise_on_missing_translations` determines whether an error should be raised for missing translations
+* `config.action_view.raise_on_missing_translations` determines whether an
+ error should be raised for missing translations.
### Configuring Action Mailer
@@ -533,6 +544,58 @@ There are a few configuration options available in Active Support:
* `ActiveSupport::Deprecation.silenced` sets whether or not to display deprecation warnings.
+### Configuring Active Job
+
+`config.active_job` provides the following configuration options:
+
+* `config.active_job.queue_adapter` sets the adapter for the queueing backend. The default adapter is `:inline` which will perform jobs immediately. For an up-to-date list of built-in adapters see the [ActiveJob::QueueAdapters API documentation](http://api.rubyonrails.org/classes/ActiveJob/QueueAdapters.html).
+
+ ```ruby
+ # Be sure to have the adapter's gem in your Gemfile
+ # and follow the adapter's specific installation
+ # and deployment instructions.
+ config.active_job.queue_adapter = :sidekiq
+ ```
+
+* `config.active_job.default_queue_name` can be used to change the default queue name. By default this is `"default"`.
+
+ ```ruby
+ config.active_job.default_queue_name = :medium_priority
+ ```
+
+* `config.active_job.queue_name_prefix` allows you to set an optional, non-blank, queue name prefix for all jobs. By default it is blank and not used.
+
+ The following configuration would queue the given job on the `production_high_priority` queue when run in production:
+
+ ```ruby
+ config.active_job.queue_name_prefix = Rails.env
+ ```
+
+ ```ruby
+ class GuestsCleanupJob < ActiveJob::Base
+ queue_as :high_priority
+ #....
+ end
+ ```
+
+* `config.active_job.queue_name_delimiter` has a default value of `'_'`. If `queue_name_prefix` is set, then `queue_name_delimiter` joins the prefix and the non-prefixed queue name.
+
+ The following configuration would queue the provided job on the `video_server.low_priority` queue:
+
+ ```ruby
+ # prefix must be set for delimiter to be used
+ config.active_job.queue_name_prefix = 'video_server'
+ config.active_job.queue_name_delimiter = '.'
+ ```
+
+ ```ruby
+ class EncoderJob < ActiveJob::Base
+ queue_as :low_priority
+ #....
+ end
+ ```
+
+* `config.active_job.logger` accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Active Job. You can retrieve this logger by calling `logger` on either an Active Job class or an Active Job instance. Set to `nil` to disable logging.
### Configuring a Database
@@ -831,15 +894,6 @@ server {
Be sure to read the [NGINX documentation](http://nginx.org/en/docs/) for the most up-to-date information.
-#### Considerations when deploying to a subdirectory
-
-Deploying to a subdirectory in production has implications on various parts of
-Rails.
-
-* development environment:
-* testing environment:
-* serving static assets:
-* asset pipeline:
Rails Environment Settings
--------------------------
@@ -969,6 +1023,11 @@ Below is a comprehensive list of all the initializers found in Rails in the orde
* `active_record.set_dispatch_hooks` Resets all reloadable connections to the database if `config.cache_classes` is set to `false`.
+* `active_job.logger` Sets `ActiveJob::Base.logger` - if it's not already set -
+ to `Rails.logger`.
+
+* `active_job.set_configs` Sets up Active Job by using the settings in `config.active_job` by `send`'ing the method names as setters to `ActiveJob::Base` and passing the values through.
+
* `action_mailer.logger` Sets `ActionMailer::Base.logger` - if it's not already set - to `Rails.logger`.
* `action_mailer.set_configs` Sets up Action Mailer by using the settings in `config.action_mailer` by `send`'ing the method names as setters to `ActionMailer::Base` and passing the values through.
diff --git a/guides/source/contributing_to_ruby_on_rails.md b/guides/source/contributing_to_ruby_on_rails.md
index 018100c316..3d5f8906ca 100644
--- a/guides/source/contributing_to_ruby_on_rails.md
+++ b/guides/source/contributing_to_ruby_on_rails.md
@@ -32,15 +32,19 @@ Your issue report should contain a title and a clear description of the issue at
Then, don't get your hopes up! Unless you have a "Code Red, Mission Critical, the World is Coming to an End" kind of bug, you're creating this issue report in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the issue report will automatically see any activity or that others will jump to fix it. Creating an issue like this is mostly to help yourself start on the path of fixing the problem and for others to confirm it with an "I'm having this problem too" comment.
-### Create a Self-Contained gist for Active Record and Action Controller Issues
+### Create an Executable Test Case
-If you are filing a bug report, please use
-[Active Record template for gems](https://github.com/rails/rails/blob/master/guides/bug_report_templates/active_record_gem.rb) or
-[Action Controller template for gems](https://github.com/rails/rails/blob/master/guides/bug_report_templates/action_controller_gem.rb)
-if the bug is found in a published gem, and
-[Active Record template for master](https://github.com/rails/rails/blob/master/guides/bug_report_templates/active_record_master.rb) or
-[Action Controller template for master](https://github.com/rails/rails/blob/master/guides/bug_report_templates/action_controller_master.rb)
-if the bug happens in the master branch.
+Having a way to reproduce your issue will be very helpful for others to help confirm, investigate and ultimately fix your issue. You can do this by providing an executable test case. To make this process easier, we have prepared several bug report templates for you to use as a starting point:
+
+* Template for Active Record (models, database) issues: [gem](https://github.com/rails/rails/blob/master/guides/bug_report_templates/active_record_gem.rb) / [master](https://github.com/rails/rails/blob/master/guides/bug_report_templates/active_record_master.rb)
+* Template for Action Pack (controllers, routing) issues: [gem](https://github.com/rails/rails/blob/master/guides/bug_report_templates/action_controller_gem.rb) / [master](https://github.com/rails/rails/blob/master/guides/bug_report_templates/action_controller_master.rb)
+* Generic template for other issues: [gem](https://github.com/rails/rails/blob/master/guides/bug_report_templates/generic_gem.rb) / [master](https://github.com/rails/rails/blob/master/guides/bug_report_templates/generic_master.rb)
+
+These templates include the boilerplate code to set up a test case against either a released version of Rails (`*_gem.rb`) or edge Rails (`*_master.rb`).
+
+Simply copy the content of the appropriate template into a `.rb` file and make the necessary changes to demonstrate the issue. You can execute it by running `ruby the_file.rb` in your terminal. If all goes well, you should see your test case failing.
+
+You can then share your executable test case as a [gist](https://gist.github.com), or simply paste the content into the issue description.
### Special Treatment for Security Issues
@@ -355,9 +359,9 @@ $ RUBYOPT=-W0 bundle exec rake test
The CHANGELOG is an important part of every release. It keeps the list of changes for every Rails version.
-You should add an entry to the CHANGELOG of the framework that you modified if you're adding or removing a feature, committing a bug fix or adding deprecation notices. Refactorings and documentation changes generally should not go to the CHANGELOG.
+You should add an entry **to the top** of the CHANGELOG of the framework that you modified if you're adding or removing a feature, committing a bug fix or adding deprecation notices. Refactorings and documentation changes generally should not go to the CHANGELOG.
-A CHANGELOG entry should summarize what was changed and should end with author's name and it should go on top of a CHANGELOG. You can use multiple lines if you need more space and you can attach code examples indented with 4 spaces. If a change is related to a specific issue, you should attach the issue's number. Here is an example CHANGELOG entry:
+A CHANGELOG entry should summarize what was changed and should end with the author's name. You can use multiple lines if you need more space and you can attach code examples indented with 4 spaces. If a change is related to a specific issue, you should attach the issue's number. Here is an example CHANGELOG entry:
```
* Summary of a change that briefly describes what was changed. You can use multiple
@@ -374,7 +378,8 @@ A CHANGELOG entry should summarize what was changed and should end with author's
*Your Name*
```
-Your name can be added directly after the last word if you don't provide any code examples or don't need multiple paragraphs. Otherwise, it's best to make as a new paragraph.
+Your name can be added directly after the last word if there are no code
+examples or multiple paragraphs. Otherwise, it's best to make a new paragraph.
### Updating the Gemfile.lock
@@ -398,21 +403,27 @@ When you're happy with the code on your computer, you need to commit the changes
$ git commit -a
```
-At this point, your editor should be fired up and you can write a message for this commit. Well formatted and descriptive commit messages are extremely helpful for the others, especially when figuring out why given change was made, so please take the time to write it.
+This should fire up your editor to write a commit message. When you have
+finished, save and close to continue.
+
+A well-formatted and descriptive commit message is very helpful to others for
+understanding why the change was made, so please take the time to write it.
-Good commit message should be formatted according to the following example:
+A good commit message looks like this:
```
Short summary (ideally 50 characters or less)
-More detailed description, if necessary. It should be wrapped to 72
-characters. Try to be as descriptive as you can, even if you think that
-the commit content is obvious, it may not be obvious to others. You
-should add such description also if it's already present in bug tracker,
-it should not be necessary to visit a webpage to check the history.
+More detailed description, if necessary. It should be wrapped to
+72 characters. Try to be as descriptive as you can. Even if you
+think that the commit content is obvious, it may not be obvious
+to others. Add any description that is already present in the
+relevant issues; it should not be necessary to visit a webpage
+to check the history.
+
+The description section can have multiple paragraphs.
-Description can have multiple paragraphs and you can use code examples
-inside, just indent it with 4 spaces:
+Code examples can be embedded by indenting them with 4 spaces:
class ArticlesController
def index
@@ -422,13 +433,15 @@ inside, just indent it with 4 spaces:
You can also add bullet points:
-- you can use dashes or asterisks
+- make a bullet point by starting a line with either a dash (-)
+ or an asterisk (*)
-- also, try to indent next line of a point for readability, if it's too
- long to fit in 72 characters
+- wrap lines at 72 characters, and indent any additional lines
+ with 2 spaces for readability
```
-TIP. Please squash your commits into a single commit when appropriate. This simplifies future cherry picks, and also keeps the git log clean.
+TIP. Please squash your commits into a single commit when appropriate. This
+simplifies future cherry picks and keeps the git log clean.
### Update Your Branch
diff --git a/guides/source/debugging_rails_applications.md b/guides/source/debugging_rails_applications.md
index a9715fb837..c6863f68e6 100644
--- a/guides/source/debugging_rails_applications.md
+++ b/guides/source/debugging_rails_applications.md
@@ -129,9 +129,14 @@ TIP: By default, each log is created under `Rails.root/log/` and the log file is
### Log Levels
-When something is logged it's printed into the corresponding log if the log level of the message is equal or higher than the configured log level. If you want to know the current log level you can call the `Rails.logger.level` method.
-
-The available log levels are: `:debug`, `:info`, `:warn`, `:error`, `:fatal`, and `:unknown`, corresponding to the log level numbers from 0 up to 5 respectively. To change the default log level, use
+When something is logged, it's printed into the corresponding log if the log
+level of the message is equal or higher than the configured log level. If you
+want to know the current log level, you can call the `Rails.logger.level`
+method.
+
+The available log levels are: `:debug`, `:info`, `:warn`, `:error`, `:fatal`,
+and `:unknown`, corresponding to the log level numbers from 0 up to 5,
+respectively. To change the default log level, use
```ruby
config.log_level = :warn # In any environment initializer, or
diff --git a/guides/source/engines.md b/guides/source/engines.md
index 84017d5e13..bcb0ee7d5d 100644
--- a/guides/source/engines.md
+++ b/guides/source/engines.md
@@ -368,7 +368,7 @@ called `Blorgh::ArticlesController` (at
`app/controllers/blorgh/articles_controller.rb`) and its related views at
`app/views/blorgh/articles`. This generator also generates a test for the
controller (`test/controllers/blorgh/articles_controller_test.rb`) and a helper
-(`app/helpers/blorgh/articles_controller.rb`).
+(`app/helpers/blorgh/articles_helper.rb`).
Everything this generator has created is neatly namespaced. The controller's
class is defined within the `Blorgh` module:
@@ -402,15 +402,6 @@ Finally, the assets for this resource are generated in two files:
`app/assets/stylesheets/blorgh/articles.css`. You'll see how to use these a little
later.
-By default, the scaffold styling is not applied to the engine because the
-engine's layout file, `app/views/layouts/blorgh/application.html.erb`, doesn't
-load it. To make the scaffold styling apply, insert this line into the `<head>`
-tag of this layout:
-
-```erb
-<%= stylesheet_link_tag "scaffold" %>
-```
-
You can see what the engine has so far by running `rake db:migrate` at the root
of our engine to run the migration generated by the scaffold generator, and then
running `rails server` in `test/dummy`. When you open
@@ -831,11 +822,9 @@ Notice that only _one_ migration was copied over here. This is because the first
two migrations were copied over the first time this command was run.
```
-NOTE Migration [timestamp]_create_blorgh_articles.rb from blorgh has been
-skipped. Migration with the same name already exists. NOTE Migration
-[timestamp]_create_blorgh_comments.rb from blorgh has been skipped. Migration
-with the same name already exists. Copied migration
-[timestamp]_add_author_id_to_blorgh_articles.rb from blorgh
+NOTE Migration [timestamp]_create_blorgh_articles.rb from blorgh has been skipped. Migration with the same name already exists.
+NOTE Migration [timestamp]_create_blorgh_comments.rb from blorgh has been skipped. Migration with the same name already exists.
+Copied migration [timestamp]_add_author_id_to_blorgh_articles.rb from blorgh
```
Run the migration using:
@@ -1201,7 +1190,7 @@ end
```
```ruby
-# Blorgh/lib/concerns/models/article
+# Blorgh/lib/concerns/models/article.rb
module Blorgh::Concerns::Models::Article
extend ActiveSupport::Concern
diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md
index 922ec3922e..684a53e472 100644
--- a/guides/source/getting_started.md
+++ b/guides/source/getting_started.md
@@ -23,7 +23,7 @@ application from scratch. It does not assume that you have any prior experience
with Rails. However, to get the most out of it, you need to have some
prerequisites installed:
-* The [Ruby](https://www.ruby-lang.org/en/downloads) language version 1.9.3 or newer.
+* The [Ruby](https://www.ruby-lang.org/en/downloads) language version 2.2.2 or newer.
* The [RubyGems](https://rubygems.org) packaging system, which is installed with Ruby
versions 1.9 and later. To learn more about RubyGems, please read the [RubyGems Guides](http://guides.rubygems.org).
* A working installation of the [SQLite3 Database](https://www.sqlite.org).
@@ -50,7 +50,7 @@ code while accomplishing more than many other languages and frameworks.
Experienced Rails developers also report that it makes web application
development more fun.
-Rails is opinionated software. It makes the assumption that there is the "best"
+Rails is opinionated software. It makes the assumption that there is a "best"
way to do things, and it's designed to encourage that way - and in some cases to
discourage alternatives. If you learn "The Rails Way" you'll probably discover a
tremendous increase in productivity. If you persist in bringing old habits from
@@ -97,7 +97,7 @@ For more installation methods for most Operating Systems take a look at
```bash
$ ruby -v
-ruby 2.0.0p353
+ruby 2.2.2p95
```
Many popular UNIX-like OSes ship with an acceptable version of SQLite3.
@@ -1510,7 +1510,7 @@ comments on articles.
We're going to see the same generator that we used before when creating
the `Article` model. This time we'll create a `Comment` model to hold
-reference of article comments. Run this command in your terminal:
+reference to an article. Run this command in your terminal:
```bash
$ bin/rails generate model Comment commenter:string body:text article:references
diff --git a/guides/source/i18n.md b/guides/source/i18n.md
index e8d0a83dd0..348c60a9d8 100644
--- a/guides/source/i18n.md
+++ b/guides/source/i18n.md
@@ -201,7 +201,7 @@ end
If your application includes a locale switching menu, you would then have something like this in it:
```ruby
-link_to("Deutsch", "#{APP_CONFIG[:deutsch_website_url]}#{request.env['REQUEST_URI']}")
+link_to("Deutsch", "#{APP_CONFIG[:deutsch_website_url]}#{request.env['PATH_INFO']}")
```
assuming you would set `APP_CONFIG[:deutsch_website_url]` to some value like `http://www.application.de`.
@@ -489,7 +489,9 @@ NOTE: The default locale loading mechanism in Rails does not load locale files i
Overview of the I18n API Features
---------------------------------
-You should have good understanding of using the i18n library now, knowing all necessary aspects of internationalizing a basic Rails application. In the following chapters, we'll cover it's features in more depth.
+You should have a good understanding of using the i18n library now and know how
+to internationalize a basic Rails application. In the following chapters, we'll
+cover its features in more depth.
These chapters will show examples using both the `I18n.translate` method as well as the [`translate` view helper method](http://api.rubyonrails.org/classes/ActionView/Helpers/TranslationHelper.html#method-i-translate) (noting the additional feature provide by the view helper method).
diff --git a/guides/source/initialization.md b/guides/source/initialization.md
index 8fbb234698..199545a3b3 100644
--- a/guides/source/initialization.md
+++ b/guides/source/initialization.md
@@ -34,7 +34,7 @@ Launch!
Let's start to boot and initialize the app. A Rails application is usually
started by running `rails console` or `rails server`.
-### `railties/bin/rails`
+### `railties/exe/rails`
The `rails` in the command `rails server` is a ruby executable in your load
path. This executable contains the following lines:
@@ -45,7 +45,7 @@ load Gem.bin_path('railties', 'rails', version)
```
If you try out this command in a Rails console, you would see that this loads
-`railties/bin/rails`. A part of the file `railties/bin/rails.rb` has the
+`railties/exe/rails`. A part of the file `railties/exe/rails.rb` has the
following code:
```ruby
@@ -163,7 +163,7 @@ throwing an error message. If the command is valid, a method of the same name
is called.
```ruby
-COMMAND_WHITELIST = %(plugin generate destroy console server dbconsole application runner new version help)
+COMMAND_WHITELIST = %w(plugin generate destroy console server dbconsole application runner new version help)
def run_command!(command)
command = parse_command(command)
diff --git a/guides/source/layouts_and_rendering.md b/guides/source/layouts_and_rendering.md
index c57fa358d6..737f392995 100644
--- a/guides/source/layouts_and_rendering.md
+++ b/guides/source/layouts_and_rendering.md
@@ -123,8 +123,6 @@ Content-Type: */*; charset=utf-8
X-Runtime: 0.014297
Set-Cookie: _blog_session=...snip...; path=/; HttpOnly
Cache-Control: no-cache
-
-$
```
We see there is an empty response (no data after the `Cache-Control` line), but the request was successful because Rails has set the response to 200 OK. You can set the `:status` option on render to change this response. Rendering nothing can be useful for Ajax requests where all you want to send back to the browser is an acknowledgment that the request was completed.
@@ -1075,9 +1073,14 @@ One way to use partials is to treat them as the equivalent of subroutines: as a
<%= render "shared/footer" %>
```
-Here, the `_ad_banner.html.erb` and `_footer.html.erb` partials could contain content that is shared among many pages in your application. You don't need to see the details of these sections when you're concentrating on a particular page.
+Here, the `_ad_banner.html.erb` and `_footer.html.erb` partials could contain
+content that is shared by many pages in your application. You don't need to see
+the details of these sections when you're concentrating on a particular page.
-As you already could see from the previous sections of this guide, `yield` is a very powerful tool for cleaning up your layouts. Keep in mind that it's pure ruby, so you can use it almost everywhere. For example, we can use it to DRY form layout definition for several similar resources:
+As seen in the previous sections of this guide, `yield` is a very powerful tool
+for cleaning up your layouts. Keep in mind that it's pure Ruby, so you can use
+it almost everywhere. For example, we can use it to DRY up form layout
+definitions for several similar resources:
* `users/index.html.erb`
diff --git a/guides/source/routing.md b/guides/source/routing.md
index 7d0a3efbe7..4ccc50a4d9 100644
--- a/guides/source/routing.md
+++ b/guides/source/routing.md
@@ -807,6 +807,18 @@ As long as `Sprockets` responds to `call` and returns a `[status, headers, body]
NOTE: For the curious, `'articles#index'` actually expands out to `ArticlesController.action(:index)`, which returns a valid Rack application.
+If you specify a rack application as the endpoint for a matcher remember that the route will be unchanged in the receiving application. With the following route your rack application should expect the route to be '/admin':
+
+```ruby
+match '/admin', to: AdminApp, via: :all
+```
+
+If you would prefer to have your rack application receive requests at the root path instead use mount:
+
+```ruby
+mount AdminApp, at: '/admin'
+```
+
### Using `root`
You can specify what Rails should route `'/'` to with the `root` method:
diff --git a/guides/source/security.md b/guides/source/security.md
index e486edde31..91d520e997 100644
--- a/guides/source/security.md
+++ b/guides/source/security.md
@@ -449,14 +449,16 @@ Depending on your web application, there may be more ways to hijack the user's a
### CAPTCHAs
-INFO: _A CAPTCHA is a challenge-response test to determine that the response is not generated by a computer. It is often used to protect comment forms from automatic spam bots by asking the user to type the letters of a distorted image. The idea of a negative CAPTCHA is not for a user to prove that they are human, but reveal that a robot is a robot._
+INFO: _A CAPTCHA is a challenge-response test to determine that the response is not generated by a computer. It is often used to protect registration forms from attackers and comment forms from automatic spam bots by asking the user to type the letters of a distorted image. This is the positive CAPTCHA, but there is also the negative CAPTCHA. The idea of a negative CAPTCHA is not for a user to prove that they are human, but reveal that a robot is a robot._
-But not only spam robots (bots) are a problem, but also automatic login bots. A popular CAPTCHA API is [reCAPTCHA](http://recaptcha.net/) which displays two distorted images of words from old books. It also adds an angled line, rather than a distorted background and high levels of warping on the text as earlier CAPTCHAs did, because the latter were broken. As a bonus, using reCAPTCHA helps to digitize old books. [ReCAPTCHA](https://github.com/ambethia/recaptcha/) is also a Rails plug-in with the same name as the API.
+A popular positive CAPTCHA API is [reCAPTCHA](http://recaptcha.net/) which displays two distorted images of words from old books. It also adds an angled line, rather than a distorted background and high levels of warping on the text as earlier CAPTCHAs did, because the latter were broken. As a bonus, using reCAPTCHA helps to digitize old books. [ReCAPTCHA](https://github.com/ambethia/recaptcha/) is also a Rails plug-in with the same name as the API.
You will get two keys from the API, a public and a private key, which you have to put into your Rails environment. After that you can use the recaptcha_tags method in the view, and the verify_recaptcha method in the controller. Verify_recaptcha will return false if the validation fails.
-The problem with CAPTCHAs is, they are annoying. Additionally, some visually impaired users have found certain kinds of distorted CAPTCHAs difficult to read. The idea of negative CAPTCHAs is not to ask a user to proof that they are human, but reveal that a spam robot is a bot.
+The problem with CAPTCHAs is that they have a negative impact on the user experience. Additionally, some visually impaired users have found certain kinds of distorted CAPTCHAs difficult to read. Still, positive CAPTCHAs are one of the best methods to prevent all kinds of bots from submitting forms.
-Most bots are really dumb, they crawl the web and put their spam into every form's field they can find. Negative CAPTCHAs take advantage of that and include a "honeypot" field in the form which will be hidden from the human user by CSS or JavaScript.
+Most bots are really dumb. They crawl the web and put their spam into every form's field they can find. Negative CAPTCHAs take advantage of that and include a "honeypot" field in the form which will be hidden from the human user by CSS or JavaScript.
+
+Note that negative CAPTCHAs are only effective against dumb bots and won't suffice to protect critical applications from targeted bots. Still, the negative and positive CAPTCHAs can be combined to increase the performance, e.g., if the "honeypot" field is not empty (bot detected), you won't need to verify the positive CAPTCHA, which would require a HTTPS request to Google ReCaptcha before computing the response.
Here are some ideas how to hide honeypot fields by JavaScript and/or CSS:
@@ -710,7 +712,7 @@ The log files on www.attacker.com will read like this:
GET http://www.attacker.com/_app_session=836c1c25278e5b321d6bea4f19cb57e2
```
-You can mitigate these attacks (in the obvious way) by adding the [httpOnly](http://dev.rubyonrails.org/ticket/8895) flag to cookies, so that document.cookie may not be read by JavaScript. Http only cookies can be used from IE v6.SP1, Firefox v2.0.0.5 and Opera 9.5. Safari is still considering, it ignores the option. But other, older browsers (such as WebTV and IE 5.5 on Mac) can actually cause the page to fail to load. Be warned that cookies [will still be visible using Ajax](http://ha.ckers.org/blog/20070719/firefox-implements-httponly-and-is-vulnerable-to-xmlhttprequest/), though.
+You can mitigate these attacks (in the obvious way) by adding the **httpOnly** flag to cookies, so that document.cookie may not be read by JavaScript. Http only cookies can be used from IE v6.SP1, Firefox v2.0.0.5 and Opera 9.5. Safari is still considering, it ignores the option. But other, older browsers (such as WebTV and IE 5.5 on Mac) can actually cause the page to fail to load. Be warned that cookies [will still be visible using Ajax](http://ha.ckers.org/blog/20070719/firefox-implements-httponly-and-is-vulnerable-to-xmlhttprequest/), though.
##### Defacement
diff --git a/guides/source/testing.md b/guides/source/testing.md
index 752ef48b16..f12daf0dbc 100644
--- a/guides/source/testing.md
+++ b/guides/source/testing.md
@@ -141,32 +141,23 @@ users(:david).id
email(david.partner.email, david.location_tonight)
```
-### Rake Tasks for Running your Tests
-
-Rails comes with a number of built-in rake tasks to help with testing. The
-table below lists the commands included in the default Rakefile when a Rails
-project is created.
-
-| Tasks | Description |
-| ----------------------- | ----------- |
-| `rake test` | Runs all tests in the `test` directory. You can also run `rake` and Rails will run all tests by default |
-| `rake test:controllers` | Runs all the controller tests from `test/controllers` |
-| `rake test:functionals` | Runs all the functional tests from `test/controllers`, `test/mailers`, and `test/functional` |
-| `rake test:helpers` | Runs all the helper tests from `test/helpers` |
-| `rake test:integration` | Runs all the integration tests from `test/integration` |
-| `rake test:jobs` | Runs all the job tests from `test/jobs` |
-| `rake test:mailers` | Runs all the mailer tests from `test/mailers` |
-| `rake test:models` | Runs all the model tests from `test/models` |
-| `rake test:units` | Runs all the unit tests from `test/models`, `test/helpers`, and `test/unit` |
-| `rake test:db` | Runs all tests in the `test` directory and resets the db |
+### Console Tasks for Running your Tests
+
+Rails comes with a CLI command to run tests.
+Here are some examples of how to use it:
+
+```bash
+$ bin/rails test # run all tests in the `test` directory
+$ bin/rails test test/controllers # run all tests from specific directory
+$ bin/rails test test/models/post_test.rb # run specific test
+$ bin/rails test test/models/post_test.rb:44 # run specific test and line
+```
We will cover each of types Rails tests listed above in this guide.
Model Testing
------------------------
-In Rails, unit tests are what you write to test your models.
-
For this guide we will be using the application we built in the [Getting Started with Rails](getting_started.html) guide.
If you remember when you used the `rails generate scaffold` command from earlier. We created our first resource among other things it created a test stub in the `test/models` directory:
@@ -259,10 +250,10 @@ be rebuilt. This can be done by executing `bin/rake db:test:prepare`.
### Running Tests
-Running a test is as simple as invoking the file containing the test cases through `rake test` command.
+Running a test is as simple as invoking the file containing the test cases through `rails test` command.
```bash
-$ bin/rake test test/models/article_test.rb
+$ bin/rails test test/models/article_test.rb
.
Finished tests in 0.009262s, 107.9680 tests/s, 107.9680 assertions/s.
@@ -275,7 +266,7 @@ This will run all test methods from the test case.
You can also run a particular test method from the test case by running the test and providing the `test method name`.
```bash
-$ bin/rake test test/models/article_test.rb test_the_truth
+$ bin/rails test test/models/article_test.rb test_the_truth
.
Finished tests in 0.009064s, 110.3266 tests/s, 110.3266 assertions/s.
@@ -296,10 +287,10 @@ test "should not save article without title" do
end
```
-Let us run this newly added test.
+Let us run this newly added test (where `6` is the number of line where the test is defined).
```bash
-$ bin/rake test test/models/article_test.rb test_should_not_save_article_without_title
+$ bin/rails test test/models/article_test.rb:6
F
Finished tests in 0.044632s, 22.4054 tests/s, 22.4054 assertions/s.
@@ -339,7 +330,7 @@ end
Now the test should pass. Let us verify by running the test again:
```bash
-$ bin/rake test test/models/article_test.rb test_should_not_save_article_without_title
+$ bin/rails test test/models/article_test.rb:6
.
Finished tests in 0.047721s, 20.9551 tests/s, 20.9551 assertions/s.
@@ -368,7 +359,7 @@ end
Now you can see even more output in the console from running the tests:
```bash
-$ bin/rake test test/models/article_test.rb test_should_report_error
+$ bin/rails test test/models/article_test.rb
E
Finished tests in 0.030974s, 32.2851 tests/s, 0.0000 assertions/s.
@@ -393,11 +384,10 @@ When a test fails you are presented with the corresponding backtrace. By default
Rails filters that backtrace and will only print lines relevant to your
application. This eliminates the framework noise and helps to focus on your
code. However there are situations when you want to see the full
-backtrace. simply set the `BACKTRACE` environment variable to enable this
-behavior:
+backtrace. Simply set the `-b` (or `--backtrace`) argument to enable this behavior:
```bash
-$ BACKTRACE=1 bin/rake test test/models/article_test.rb
+$ bin/rails test -b test/models/article_test.rb
```
If we want this test to pass we can modify it to use `assert_raises` like so:
@@ -504,13 +494,13 @@ All the keyword arguments are optional.
Example: Calling the `:show` action, passing an `id` of 12 as the `params` and setting a `user_id` of 5 in the session:
```ruby
-get(:show, params: { 'id' => "12" }, session: { 'user_id' => 5 })
+get(:show, params: { id: 12 }, session: { user_id: 5 })
```
Another example: Calling the `:view` action, passing an `id` of 12 as the `params`, this time with no session, but with a flash message.
```ruby
-get(:view, params: { 'id' => '12' }, flash: { 'message' => 'booya!' })
+get(:view, params: { id: 12 }, flash: { message: 'booya!' })
```
NOTE: If you try running `test_should_create_article` test from `articles_controller_test.rb` it will fail on account of the newly added model level validation and rightly so.
@@ -666,7 +656,7 @@ end
If we run our test now, we should see a failure:
```bash
-$ bin/rake test test/controllers/articles_controller_test.rb test_should_create_article
+$ bin/rails test test/controllers/articles_controller_test.rb test_should_create_article
Run options: -n test_should_create_article --seed 32266
# Running:
@@ -704,7 +694,7 @@ end
Now if we run our tests, we should see it pass:
```bash
-$ bin/rake test test/controllers/articles_controller_test.rb test_should_create_article
+$ bin/rails test test/controllers/articles_controller_test.rb test_should_create_article
Run options: -n test_should_create_article --seed 18981
# Running:
@@ -852,7 +842,7 @@ end
I've added this file here `test/controllers/articles_routes_test.rb` and if we run the test we should see:
```bash
-$ bin/rake test test/controllers/articles_routes_test.rb
+$ bin/rails test test/controllers/articles_routes_test.rb
# Running:
diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md
index 05c46a9e76..0aa2152d56 100644
--- a/guides/source/upgrading_ruby_on_rails.md
+++ b/guides/source/upgrading_ruby_on_rails.md
@@ -20,7 +20,7 @@ The best way to be sure that your application still works after upgrading is to
Rails generally stays close to the latest released Ruby version when it's released:
-* Rails 5 requires Ruby 2.2.1 or newer.
+* Rails 5 requires Ruby 2.2.2 or newer.
* Rails 4 prefers Ruby 2.0 and requires 1.9.3 or newer.
* Rails 3.2.x is the last branch to support Ruby 1.8.7.
* Rails 3 and above require Ruby 1.8.7 or higher. Support for all of the previous Ruby versions has been dropped officially. You should upgrade as early as possible.
@@ -75,6 +75,23 @@ warning by adding the following configuration to your `config/application.rb`:
See [#17227](https://github.com/rails/rails/pull/17227) for more details.
+### ActiveJob jobs now inherent from ApplicationJob by default
+
+In Rails 4.2 an ActiveJob inherits from `ActiveJob::Base`. In Rails 5.0 this
+behavior has changed to now inherit from `ApplicationJob`.
+
+When upgrading from Rails 4.2 to Rails 5.0 you need to create an
+`application_job.rb` file in `app/jobs/` and add the following content:
+
+```
+class ApplicationJob < ActiveJob::Base
+end
+```
+
+Then make sure that all your job classes inherit from it.
+
+See [#19034](https://github.com/rails/rails/pull/19034) for more details.
+
Upgrading from Rails 4.1 to Rails 4.2
-------------------------------------
@@ -281,7 +298,7 @@ end
The migration DSL has been expanded to support foreign key definitions. If
you've been using the Foreigner gem, you might want to consider removing it.
Note that the foreign key support of Rails is a subset of Foreigner. This means
-that not every Foreigner definition can be fully replaced by it's Rails
+that not every Foreigner definition can be fully replaced by its Rails
migration DSL counterpart.
The migration procedure is as follows:
diff --git a/rails.gemspec b/rails.gemspec
index 23404da9be..52112680b2 100644
--- a/rails.gemspec
+++ b/rails.gemspec
@@ -7,7 +7,7 @@ Gem::Specification.new do |s|
s.summary = 'Full-stack web application framework.'
s.description = 'Ruby on Rails is a full-stack web framework optimized for programmer happiness and sustainable productivity. It encourages beautiful code by favoring convention over configuration.'
- s.required_ruby_version = '>= 2.2.1'
+ s.required_ruby_version = '>= 2.2.2'
s.required_rubygems_version = '>= 1.8.11'
s.license = 'MIT'
diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md
index f4c57f46f5..43eee9f442 100644
--- a/railties/CHANGELOG.md
+++ b/railties/CHANGELOG.md
@@ -1,4 +1,20 @@
-* Respect `pluralize_table_names` when generate fixture file.
+* Remove sqlite support from `rails dbconsole`.
+
+ *Andrew White*
+
+* Rename `railties/bin` to `railties/exe` to match the new Bundler executables
+ convention.
+
+ *Islam Wazery*
+
+* Print `bundle install` output in `rails new` as soon as it's available.
+
+ Running `rails new` will now print the output of `bundle install` as
+ it is available, instead of waiting until all gems finish installing.
+
+ *Max Holder*
+
+* Respect `pluralize_table_names` when generating fixture file.
Fixes #19519.
@@ -11,7 +27,7 @@
*arthurnn*
-* Add `rake initializers`
+* Add `rake initializers`.
This task prints out all defined initializers in the order they are invoked
by Rails. This is helpful for debugging issues related to the initialization
@@ -26,7 +42,7 @@
*Hyonjee Joo*
-* Add `config/initializers/active_record_belongs_to_required_by_default.rb`
+* Add `config/initializers/active_record_belongs_to_required_by_default.rb`.
Newly generated Rails apps have a new initializer called
`active_record_belongs_to_required_by_default.rb` which sets the value of
@@ -45,7 +61,7 @@
'No such middleware' errors when `insert_before` or `insert_after` are added
after the `delete` operation for the middleware being deleted.
- Fixes: #16433.
+ Fixes #16433.
*Guo Xiang Tan*
@@ -57,7 +73,7 @@
*Xavier Noria*
-* Force generated routes to be inserted into routes.rb
+* Force generated routes to be inserted into `config/routes.rb`.
*Andrew White*
@@ -71,11 +87,12 @@
*Melanie Gilman*
-* Add the `method_source` gem to the default Gemfile for apps
+* Add the `method_source` gem to the default Gemfile for apps.
*Sean Griffin*
-* Drop old test locations from `rake stats`
+* Drop old test locations from `rake stats`:
+
- test/functional
- test/unit
@@ -106,7 +123,7 @@
*Andrew Kozlov*
-* Add `config/initializers/callback_terminator.rb`
+* Add `config/initializers/callback_terminator.rb`.
Newly generated Rails apps have a new initializer called
`callback_terminator.rb` which sets the value of the configuration option
diff --git a/railties/bin/rails b/railties/exe/rails
index 82c17cabce..82c17cabce 100755
--- a/railties/bin/rails
+++ b/railties/exe/rails
diff --git a/railties/lib/rails/app_rails_loader.rb b/railties/lib/rails/app_rails_loader.rb
index 39d8007333..9a7c6c5f2d 100644
--- a/railties/lib/rails/app_rails_loader.rb
+++ b/railties/lib/rails/app_rails_loader.rb
@@ -1,4 +1,5 @@
require 'pathname'
+require 'rails/version'
module Rails
module AppRailsLoader
@@ -9,7 +10,7 @@ module Rails
BUNDLER_WARNING = <<EOS
Looks like your app's ./bin/rails is a stub that was generated by Bundler.
-In Rails 4, your app's bin/ directory contains executables that are versioned
+In Rails #{Rails::VERSION::MAJOR}, your app's bin/ directory contains executables that are versioned
like any other source code, rather than stubs that are generated on demand.
Here's how to upgrade:
diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb
index e9683d4a95..a65f8f2ad9 100644
--- a/railties/lib/rails/application.rb
+++ b/railties/lib/rails/application.rb
@@ -1,4 +1,5 @@
require 'fileutils'
+require 'yaml'
require 'active_support/core_ext/hash/keys'
require 'active_support/core_ext/object/blank'
require 'active_support/key_generator'
@@ -228,7 +229,6 @@ module Rails
yaml = Pathname.new("#{paths["config"].existent.first}/#{name}.yml")
if yaml.exist?
- require "yaml"
require "erb"
(YAML.load(ERB.new(yaml.read).result) || {})[Rails.env] || {}
else
@@ -511,7 +511,7 @@ module Rails
"Read the upgrade documentation to learn more about this new config option."
if secrets.secret_token.blank?
- raise "Missing `secret_token` and `secret_key_base` for '#{Rails.env}' environment, set these values in `config/secrets.yml`"
+ raise "Missing `secret_key_base` for '#{Rails.env}' environment, set this value in `config/secrets.yml`"
end
end
end
diff --git a/railties/lib/rails/code_statistics.rb b/railties/lib/rails/code_statistics.rb
index 583d005d46..fd352dc9b7 100644
--- a/railties/lib/rails/code_statistics.rb
+++ b/railties/lib/rails/code_statistics.rb
@@ -41,11 +41,9 @@ class CodeStatistics #:nodoc:
if File.directory?(path) && (/^\./ !~ file_name)
stats.add(calculate_directory_statistics(path, pattern))
+ elsif file_name =~ pattern
+ stats.add_by_file_path(path)
end
-
- next unless file_name =~ pattern
-
- stats.add_by_file_path(path)
end
stats
diff --git a/railties/lib/rails/commands/commands_tasks.rb b/railties/lib/rails/commands/commands_tasks.rb
index d8d4080c3e..685d55eea8 100644
--- a/railties/lib/rails/commands/commands_tasks.rb
+++ b/railties/lib/rails/commands/commands_tasks.rb
@@ -151,6 +151,17 @@ EOT
puts HELP_MESSAGE
end
+ # Output an error message stating that the attempted command is not a valid rails command.
+ # Run the attempted command as a rake command with the --dry-run flag. If successful, suggest
+ # to the user that they possibly meant to run the given rails command as a rake command.
+ # Append the help message.
+ #
+ # Example:
+ # $ rails db:migrate
+ # Error: Command 'db:migrate' not recognized
+ # Did you mean: `$ rake db:migrate` ?
+ # (Help message output)
+ #
def write_error_message(command)
puts "Error: Command '#{command}' not recognized"
if %x{rake #{command} --dry-run 2>&1 } && $?.success?
diff --git a/railties/lib/rails/commands/dbconsole.rb b/railties/lib/rails/commands/dbconsole.rb
index 5175e31f14..3b22b582cf 100644
--- a/railties/lib/rails/commands/dbconsole.rb
+++ b/railties/lib/rails/commands/dbconsole.rb
@@ -50,9 +50,6 @@ module Rails
ENV['PGPASSWORD'] = config["password"].to_s if config["password"] && options['include_password']
find_cmd_and_exec('psql', config["database"])
- when "sqlite"
- find_cmd_and_exec('sqlite', config["database"])
-
when "sqlite3"
args = []
@@ -89,7 +86,7 @@ module Rails
find_cmd_and_exec("sqsh", *args)
else
- abort "Unknown command-line client for #{config['database']}. Submit a Rails patch to add support!"
+ abort "Unknown command-line client for #{config['database']}."
end
end
diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb
index 341291f08b..a7da92168d 100644
--- a/railties/lib/rails/generators.rb
+++ b/railties/lib/rails/generators.rb
@@ -267,10 +267,13 @@ module Rails
d = (0..m).to_a
x = nil
- str1.each_char.each_with_index do |char1,i|
+ # avoid duplicating an enumerable object in the loop
+ str2_codepoint_enumerable = str2.each_codepoint
+
+ str1.each_codepoint.with_index do |char1, i|
e = i+1
- str2.each_char.each_with_index do |char2,j|
+ str2_codepoint_enumerable.with_index do |char2, j|
cost = (char1 == char2) ? 0 : 1
x = [
d[j+1] + 1, # insertion
diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb
index 813f8b21fd..119a7cb829 100644
--- a/railties/lib/rails/generators/app_base.rb
+++ b/railties/lib/rails/generators/app_base.rb
@@ -315,10 +315,6 @@ module Rails
# its own vendored Thor, which could be a different version. Running both
# things in the same process is a recipe for a night with paracetamol.
#
- # We use backticks and #print here instead of vanilla #system because it
- # is easier to silence stdout in the existing test suite this way. The
- # end-user gets the bundler commands called anyway, so no big deal.
- #
# We unset temporary bundler variables to load proper bundler and Gemfile.
#
# Thanks to James Tucker for the Gem tricks involved in this call.
@@ -326,8 +322,12 @@ module Rails
require 'bundler'
Bundler.with_clean_env do
- output = `"#{Gem.ruby}" "#{_bundle_command}" #{command}`
- print output unless options[:quiet]
+ full_command = %Q["#{Gem.ruby}" "#{_bundle_command}" #{command}]
+ if options[:quiet]
+ system(full_command, out: File::NULL)
+ else
+ system(full_command)
+ end
end
end
@@ -336,7 +336,7 @@ module Rails
end
def spring_install?
- !options[:skip_spring] && Process.respond_to?(:fork) && !RUBY_PLATFORM.include?("cygwin")
+ !options[:skip_spring] && !options.dev? && Process.respond_to?(:fork) && !RUBY_PLATFORM.include?("cygwin")
end
def run_bundle
diff --git a/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb b/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb
index d9713b0238..d99b27cb2d 100644
--- a/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb
+++ b/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb
@@ -17,6 +17,7 @@
<%%= f.label :password %><br>
<%%= f.password_field :password %>
</div>
+
<div class="field">
<%%= f.label :password_confirmation %><br>
<%%= f.password_field :password_confirmation %>
@@ -25,6 +26,7 @@
<%%= f.<%= attribute.field_type %> :<%= attribute.column_name %> %>
<% end -%>
</div>
+
<% end -%>
<div class="actions">
<%%= f.submit %>
diff --git a/railties/lib/rails/generators/rails/app/templates/app/jobs/application_job.rb b/railties/lib/rails/generators/rails/app/templates/app/jobs/application_job.rb
new file mode 100644
index 0000000000..a009ace51c
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/app/jobs/application_job.rb
@@ -0,0 +1,2 @@
+class ApplicationJob < ActiveJob::Base
+end
diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/callback_terminator.rb b/railties/lib/rails/generators/rails/app/templates/config/initializers/callback_terminator.rb
index e63022da91..a70a1b9cde 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/initializers/callback_terminator.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/callback_terminator.rb
@@ -1,4 +1,4 @@
# Be sure to restart your server when you modify this file.
# Do not halt callback chains when a callback returns false.
-Rails.application.config.active_support.halt_callback_chains_on_return_false = false
+ActiveSupport.halt_callback_chains_on_return_false = false
diff --git a/railties/lib/rails/generators/rails/controller/controller_generator.rb b/railties/lib/rails/generators/rails/controller/controller_generator.rb
index df615c88b5..0a4c509a31 100644
--- a/railties/lib/rails/generators/rails/controller/controller_generator.rb
+++ b/railties/lib/rails/generators/rails/controller/controller_generator.rb
@@ -13,12 +13,14 @@ module Rails
def add_routes
unless options[:skip_routes]
actions.reverse_each do |action|
- route generate_routing_code(action)
+ # route prepends two spaces onto the front of the string that is passed, this corrects that.
+ route generate_routing_code(action)[2..-1]
end
end
end
- hook_for :template_engine, :test_framework, :helper, :assets
+ hook_for :template_engine, :test_framework
+ hook_for :helper, :assets, hide: true
private
@@ -36,12 +38,12 @@ module Rails
# namespace :foo do
# namespace :bar do
namespace_ladder = regular_class_path.each_with_index.map do |ns, i|
- indent("namespace :#{ns} do\n", i * 2)
+ indent(" namespace :#{ns} do\n", i * 2)
end.join
# Create route
# get 'baz/index'
- route = indent(%{get '#{file_name}/#{action}'\n}, depth * 2)
+ route = indent(%{ get '#{file_name}/#{action}'\n}, depth * 2)
# Create `end` ladder
# end
diff --git a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb
index 68c3829515..fe19fa38d7 100644
--- a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb
+++ b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb
@@ -8,7 +8,7 @@ module Rails
# generator.
#
# This allows you to override entire operations, like the creation of the
- # Gemfile, README, or JavaScript files, without needing to know exactly
+ # Gemfile, \README, or JavaScript files, without needing to know exactly
# what those operations do so you can create another template action.
class PluginBuilder
def rakefile
diff --git a/railties/lib/rails/generators/rails/scaffold/templates/scaffold.css b/railties/lib/rails/generators/rails/scaffold/templates/scaffold.css
index 69af1e8307..b7818883d1 100644
--- a/railties/lib/rails/generators/rails/scaffold/templates/scaffold.css
+++ b/railties/lib/rails/generators/rails/scaffold/templates/scaffold.css
@@ -1,8 +1,11 @@
-body { background-color: #fff; color: #333; }
+body {
+ background-color: #fff;
+ color: #333;
+}
body, p, ol, ul, td {
font-family: verdana, arial, helvetica, sans-serif;
- font-size: 13px;
+ font-size: 13px;
line-height: 18px;
margin: 33px;
}
@@ -13,9 +16,18 @@ pre {
font-size: 11px;
}
-a { color: #000; }
-a:visited { color: #666; }
-a:hover { color: #fff; background-color:#000; }
+a {
+ color: #000;
+}
+
+a:visited {
+ color: #666;
+}
+
+a:hover {
+ color: #fff;
+ background-color: #000;
+}
th {
padding-bottom: 5px;
@@ -27,7 +39,8 @@ td {
padding-right: 5px;
}
-div.field, div.actions {
+div.field,
+div.actions {
margin-bottom: 10px;
}
@@ -56,7 +69,7 @@ div.field, div.actions {
padding: 5px 5px 5px 15px;
font-size: 12px;
margin: -7px;
- margin-bottom: 0px;
+ margin-bottom: 0;
background-color: #c00;
color: #fff;
}
diff --git a/railties/lib/rails/rack/logger.rb b/railties/lib/rails/rack/logger.rb
index 9962e6d943..7aaa353b91 100644
--- a/railties/lib/rails/rack/logger.rb
+++ b/railties/lib/rails/rack/logger.rb
@@ -7,6 +7,9 @@ require 'rack/body_proxy'
module Rails
module Rack
# Sets log tags, logs the request, calls the app, and flushes the logs.
+ #
+ # Log tags (+taggers+) can be an Array containing: methods that the <tt>request</tt> object responds to, a Proc
+ # that accepts an instance of the <tt>request</tt> object, or something that responds to <tt>to_s</tt>.
class Logger < ActiveSupport::LogSubscriber
def initialize(app, taggers = nil)
@app = app
diff --git a/railties/lib/rails/ruby_version_check.rb b/railties/lib/rails/ruby_version_check.rb
index 9131c51e91..67a19d8a94 100644
--- a/railties/lib/rails/ruby_version_check.rb
+++ b/railties/lib/rails/ruby_version_check.rb
@@ -1,13 +1,13 @@
-if RUBY_VERSION < '2.2.1' && RUBY_ENGINE == 'ruby'
+if RUBY_VERSION < '2.2.2' && RUBY_ENGINE == 'ruby'
desc = defined?(RUBY_DESCRIPTION) ? RUBY_DESCRIPTION : "ruby #{RUBY_VERSION} (#{RUBY_RELEASE_DATE})"
abort <<-end_message
- Rails 5 requires to run on Ruby 2.2.1 or newer.
+ Rails 5 requires Ruby 2.2.2 or newer.
You're running
#{desc}
- Please upgrade to Ruby 2.2.1 or newer to continue.
+ Please upgrade to Ruby 2.2.2 or newer to continue.
end_message
end
diff --git a/railties/lib/rails/templates/rails/welcome/index.html.erb b/railties/lib/rails/templates/rails/welcome/index.html.erb
index 6726c23fc9..acf04af416 100644
--- a/railties/lib/rails/templates/rails/welcome/index.html.erb
+++ b/railties/lib/rails/templates/rails/welcome/index.html.erb
@@ -18,7 +18,9 @@
color: #000;
}
- a {color: #03c}
+ a {
+ color: #03c;
+ }
a:hover {
background-color: #03c;
@@ -64,7 +66,10 @@
height: 64px;
}
- #header h1, #header h2 {margin: 0}
+ #header h1,
+ #header h2 {
+ margin: 0;
+ }
#header h2 {
color: #888;
@@ -104,7 +109,9 @@
color: #555;
}
- #about-content td.value {color: #000}
+ #about-content td.value {
+ color: #000;
+ }
#about-content ul {
padding: 0;
diff --git a/railties/railties.gemspec b/railties/railties.gemspec
index 001882fdc6..afe1603448 100644
--- a/railties/railties.gemspec
+++ b/railties/railties.gemspec
@@ -7,7 +7,7 @@ Gem::Specification.new do |s|
s.summary = 'Tools for creating, working with, and running Rails applications.'
s.description = 'Rails internals: application bootup, plugins, generators, and rake tasks.'
- s.required_ruby_version = '>= 2.2.1'
+ s.required_ruby_version = '>= 2.2.2'
s.license = 'MIT'
@@ -15,10 +15,10 @@ Gem::Specification.new do |s|
s.email = 'david@loudthinking.com'
s.homepage = 'http://www.rubyonrails.org'
- s.files = Dir['CHANGELOG.md', 'README.rdoc', 'RDOC_MAIN.rdoc', 'bin/**/*', 'lib/**/{*,.[a-z]*}']
+ s.files = Dir['CHANGELOG.md', 'README.rdoc', 'RDOC_MAIN.rdoc', 'exe/**/*', 'lib/**/{*,.[a-z]*}']
s.require_path = 'lib'
- s.bindir = 'bin'
+ s.bindir = 'exe'
s.executables = ['rails']
s.rdoc_options << '--exclude' << '.'
diff --git a/railties/test/application/asset_debugging_test.rb b/railties/test/application/asset_debugging_test.rb
index 9a571fac3a..acd387256c 100644
--- a/railties/test/application/asset_debugging_test.rb
+++ b/railties/test/application/asset_debugging_test.rb
@@ -57,8 +57,8 @@ module ApplicationTests
class ::PostsController < ActionController::Base ; end
get '/posts?debug_assets=true'
- assert_match(/<script src="\/assets\/application-([0-z]+)\.js\?body=1"><\/script>/, last_response.body)
- assert_match(/<script src="\/assets\/xmlhr-([0-z]+)\.js\?body=1"><\/script>/, last_response.body)
+ assert_match(/<script src="\/assets\/application(\.self)?-([0-z]+)\.js\?body=1"><\/script>/, last_response.body)
+ assert_match(/<script src="\/assets\/xmlhr(\.self)?-([0-z]+)\.js\?body=1"><\/script>/, last_response.body)
end
end
end
diff --git a/railties/test/application/assets_test.rb b/railties/test/application/assets_test.rb
index 0a2f283cce..1e2a9ba040 100644
--- a/railties/test/application/assets_test.rb
+++ b/railties/test/application/assets_test.rb
@@ -191,6 +191,7 @@ module ApplicationTests
test "asset pipeline should use a Sprockets::Index when config.assets.digest is true" do
add_to_config "config.action_controller.perform_caching = false"
+ add_to_env_config "production", "config.assets.compile = true"
ENV["RAILS_ENV"] = "production"
require "#{app_path}/config/environment"
@@ -204,7 +205,7 @@ module ApplicationTests
app_file "app/assets/javascripts/application.js", "alert();"
precompile!
- manifest = Dir["#{app_path}/public/assets/manifest-*.json"].first
+ manifest = Dir["#{app_path}/public/assets/.sprockets-manifest-*.json"].first
assets = ActiveSupport::JSON.decode(File.read(manifest))
assert_match(/application-([0-z]+)\.js/, assets["assets"]["application.js"])
@@ -217,7 +218,7 @@ module ApplicationTests
precompile!
- manifest = Dir["#{app_path}/public/x/manifest-*.json"].first
+ manifest = Dir["#{app_path}/public/x/.sprockets-manifest-*.json"].first
assets = ActiveSupport::JSON.decode(File.read(manifest))
assert_match(/application-([0-z]+)\.js/, assets["assets"]["application.js"])
end
@@ -229,7 +230,7 @@ module ApplicationTests
ENV["RAILS_ENV"] = "production"
precompile!
- manifest = Dir["#{app_path}/public/assets/manifest-*.json"].first
+ manifest = Dir["#{app_path}/public/assets/.sprockets-manifest-*.json"].first
assets = ActiveSupport::JSON.decode(File.read(manifest))
asset_path = assets["assets"]["application.js"]
@@ -261,7 +262,7 @@ module ApplicationTests
ENV["RAILS_ENV"] = "production"
precompile!
- manifest = Dir["#{app_path}/public/assets/manifest-*.json"].first
+ manifest = Dir["#{app_path}/public/assets/.sprockets-manifest-*.json"].first
assets = ActiveSupport::JSON.decode(File.read(manifest))
asset_path = assets["assets"]["application.css"]
@@ -291,7 +292,7 @@ module ApplicationTests
precompile!
- manifest = Dir["#{app_path}/public/assets/manifest-*.json"].first
+ manifest = Dir["#{app_path}/public/assets/.sprockets-manifest-*.json"].first
assets = ActiveSupport::JSON.decode(File.read(manifest))
assert asset_path = assets["assets"].find { |(k, _)| k && k =~ /.png/ }[1]
@@ -437,9 +438,9 @@ module ApplicationTests
class ::PostsController < ActionController::Base; end
get '/posts', {}, {'HTTPS'=>'off'}
- assert_match('src="http://example.com/assets/application.js', last_response.body)
+ assert_match('src="http://example.com/assets/application.self.js', last_response.body)
get '/posts', {}, {'HTTPS'=>'on'}
- assert_match('src="https://example.com/assets/application.js', last_response.body)
+ assert_match('src="https://example.com/assets/application.self.js', last_response.body)
end
test "asset urls should be protocol-relative if no request is in scope" do
@@ -464,17 +465,6 @@ module ApplicationTests
assert_match "src='/sub/uri/assets/rails.png'", File.read(Dir["#{app_path}/public/assets/app-*.js"].first)
end
- test "assets:cache:clean should clean cache" do
- ENV["RAILS_ENV"] = "production"
- precompile!
-
- quietly do
- Dir.chdir(app_path){ `bundle exec rake assets:clobber` }
- end
-
- assert !File.exist?("#{app_path}/tmp/cache/assets")
- end
-
private
def app_with_assets_in_view
diff --git a/railties/test/application/rake/dbs_test.rb b/railties/test/application/rake/dbs_test.rb
index c414732f92..5cc9790b28 100644
--- a/railties/test/application/rake/dbs_test.rb
+++ b/railties/test/application/rake/dbs_test.rb
@@ -181,6 +181,34 @@ module ApplicationTests
end
end
+ test "db:schema:load with inflections" do
+ Dir.chdir(app_path) do
+ app_file 'config/initializers/inflection.rb', <<-RUBY
+ ActiveSupport::Inflector.inflections do |inflect|
+ inflect.irregular 'goose', 'geese'
+ end
+ RUBY
+ app_file 'config/initializers/primary_key_table_name.rb', <<-RUBY
+ ActiveRecord::Base.primary_key_prefix_type = :table_name
+ RUBY
+ app_file 'db/schema.rb', <<-RUBY
+ ActiveRecord::Schema.define(version: 20140423102712) do
+ create_table("goose".pluralize) do |t|
+ t.string :name
+ end
+ end
+ RUBY
+
+ `bin/rake db:schema:load`
+
+ tables = `bin/rails runner 'p ActiveRecord::Base.connection.tables'`.strip
+ assert_match(/"geese"/, tables)
+
+ columns = `bin/rails runner 'p ActiveRecord::Base.connection.columns("geese").map(&:name)'`.strip
+ assert_equal columns, '["gooseid", "name"]'
+ end
+ end
+
def db_test_load_structure
Dir.chdir(app_path) do
`rails generate model book title:string;
diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb
index 2bff21dae5..0648b11813 100644
--- a/railties/test/application/rake_test.rb
+++ b/railties/test/application/rake_test.rb
@@ -99,7 +99,7 @@ module ApplicationTests
end
def test_code_statistics_sanity
- assert_match "Code LOC: 5 Test LOC: 0 Code to Test Ratio: 1:0.0",
+ assert_match "Code LOC: 7 Test LOC: 0 Code to Test Ratio: 1:0.0",
Dir.chdir(app_path){ `rake stats` }
end
diff --git a/railties/test/code_statistics_test.rb b/railties/test/code_statistics_test.rb
new file mode 100644
index 0000000000..1b1ff80bc1
--- /dev/null
+++ b/railties/test/code_statistics_test.rb
@@ -0,0 +1,20 @@
+require 'abstract_unit'
+require 'rails/code_statistics'
+
+class CodeStatisticsTest < ActiveSupport::TestCase
+ def setup
+ @tmp_path = File.expand_path(File.join(File.dirname(__FILE__), 'fixtures', 'tmp'))
+ @dir_js = File.expand_path(File.join(File.dirname(__FILE__), 'fixtures', 'tmp', 'lib.js'))
+ FileUtils.mkdir_p(@dir_js)
+ end
+
+ def teardown
+ FileUtils.rm_rf(@tmp_path)
+ end
+
+ test 'ignores directories that happen to have source files extensions' do
+ assert_nothing_raised do
+ @code_statistics = CodeStatistics.new(['tmp dir', @tmp_path])
+ end
+ end
+end
diff --git a/railties/test/commands/dbconsole_test.rb b/railties/test/commands/dbconsole_test.rb
index a3cd1eb0ed..2e8dd99f36 100644
--- a/railties/test/commands/dbconsole_test.rb
+++ b/railties/test/commands/dbconsole_test.rb
@@ -158,12 +158,6 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase
assert_equal 'q1w2e3', ENV['PGPASSWORD']
end
- def test_sqlite
- start(adapter: 'sqlite', database: 'db')
- assert !aborted
- assert_equal ['sqlite', 'db'], dbconsole.find_cmd_and_exec_args
- end
-
def test_sqlite3
start(adapter: 'sqlite3', database: 'db.sqlite3')
assert !aborted
diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb
index 00a7932267..2bfa05a0b8 100644
--- a/railties/test/generators/app_generator_test.rb
+++ b/railties/test/generators/app_generator_test.rb
@@ -18,6 +18,7 @@ DEFAULT_APP_FILES = %w(
app/mailers
app/models
app/models/concerns
+ app/jobs
app/views/layouts
bin/bundle
bin/rails
@@ -67,6 +68,11 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file("app/assets/javascripts/application.js")
end
+ def test_application_job_file_present
+ run_generator
+ assert_file("app/jobs/application_job.rb")
+ end
+
def test_invalid_application_name_raises_an_error
content = capture(:stderr){ run_generator [File.join(destination_root, "43-things")] }
assert_equal "Invalid application name 43-things. Please give a name which does not start with numbers.\n", content
@@ -554,6 +560,14 @@ class AppGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_spring_with_dev_option
+ run_generator [destination_root, "--dev"]
+
+ assert_file "Gemfile" do |content|
+ assert_no_match(/spring/, content)
+ end
+ end
+
def test_generator_if_skip_turbolinks_is_given
run_generator [destination_root, "--skip-turbolinks"]
diff --git a/railties/test/generators/controller_generator_test.rb b/railties/test/generators/controller_generator_test.rb
index a7d56dd352..1351151afb 100644
--- a/railties/test/generators/controller_generator_test.rb
+++ b/railties/test/generators/controller_generator_test.rb
@@ -96,6 +96,8 @@ class ControllerGeneratorTest < Rails::Generators::TestCase
def test_namespaced_routes_are_created_in_routes
run_generator ["admin/dashboard", "index"]
- assert_file "config/routes.rb", /namespace :admin do\n\s+get 'dashboard\/index'\n/
+ assert_file "config/routes.rb" do |route|
+ assert_match(/^ namespace :admin do\n get 'dashboard\/index'\n end$/, route)
+ end
end
end
diff --git a/railties/test/generators/job_generator_test.rb b/railties/test/generators/job_generator_test.rb
index a9e0cea94f..7fd8f2062f 100644
--- a/railties/test/generators/job_generator_test.rb
+++ b/railties/test/generators/job_generator_test.rb
@@ -7,14 +7,14 @@ class JobGeneratorTest < Rails::Generators::TestCase
def test_job_skeleton_is_created
run_generator ["refresh_counters"]
assert_file "app/jobs/refresh_counters_job.rb" do |job|
- assert_match(/class RefreshCountersJob < ActiveJob::Base/, job)
+ assert_match(/class RefreshCountersJob < ApplicationJob/, job)
end
end
def test_job_queue_param
run_generator ["refresh_counters", "--queue", "important"]
assert_file "app/jobs/refresh_counters_job.rb" do |job|
- assert_match(/class RefreshCountersJob < ActiveJob::Base/, job)
+ assert_match(/class RefreshCountersJob < ApplicationJob/, job)
assert_match(/queue_as :important/, job)
end
end
@@ -22,7 +22,7 @@ class JobGeneratorTest < Rails::Generators::TestCase
def test_job_namespace
run_generator ["admin/refresh_counters", "--queue", "admin"]
assert_file "app/jobs/admin/refresh_counters_job.rb" do |job|
- assert_match(/class Admin::RefreshCountersJob < ActiveJob::Base/, job)
+ assert_match(/class Admin::RefreshCountersJob < ApplicationJob/, job)
assert_match(/queue_as :admin/, job)
end
end
diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb
index 127e059bf1..fdcfb30090 100644
--- a/railties/test/generators_test.rb
+++ b/railties/test/generators_test.rb
@@ -34,6 +34,12 @@ class GeneratorsTest < Rails::Generators::TestCase
assert_match "Maybe you meant 'migration'", output
end
+ def test_generator_multiple_suggestions
+ name = :tas
+ output = capture(:stdout){ Rails::Generators.invoke name }
+ assert_match "Maybe you meant 'task', 'job' or 'assets'", output
+ end
+
def test_help_when_a_generator_with_required_arguments_is_invoked_without_arguments
output = capture(:stdout){ Rails::Generators.invoke :model, [] }
assert_match(/Description:/, output)
diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb
index 63209559d7..4509797da1 100644
--- a/railties/test/isolation/abstract_unit.rb
+++ b/railties/test/isolation/abstract_unit.rb
@@ -322,7 +322,7 @@ Module.new do
environment = File.expand_path('../../../../load_paths', __FILE__)
require_environment = "-r #{environment}"
- `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/railties/bin/rails new #{app_template_path} --skip-gemfile --no-rc`
+ `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/railties/exe/rails new #{app_template_path} --skip-gemfile --no-rc`
File.open("#{app_template_path}/config/boot.rb", 'w') do |f|
f.puts "require '#{environment}'"
f.puts "require 'rails/all'"
diff --git a/railties/test/path_generation_test.rb b/railties/test/path_generation_test.rb
index e3dfcdfb7d..d22374a1ff 100644
--- a/railties/test/path_generation_test.rb
+++ b/railties/test/path_generation_test.rb
@@ -4,18 +4,16 @@ require 'active_support/core_ext/object/json'
require 'rails'
require 'rails/application'
-ROUTING = ActionDispatch::Routing
-
class PathGenerationTest < ActiveSupport::TestCase
attr_reader :app
- class TestSet < ROUTING::RouteSet
+ class TestSet < ActionDispatch::Routing::RouteSet
def initialize(block)
@block = block
super()
end
- class Dispatcher < ROUTING::RouteSet::Dispatcher
+ class Dispatcher < ActionDispatch::Routing::RouteSet::Dispatcher
def initialize(defaults, set, block)
super(defaults)
@block = block
diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb
index 6185742cc1..79bd7a8241 100644
--- a/railties/test/railties/engine_test.rb
+++ b/railties/test/railties/engine_test.rb
@@ -1155,10 +1155,10 @@ YAML
assert_equal "App's bar partial", last_response.body.strip
get("/assets/foo.js")
- assert_equal "// Bukkit's foo js\n;", last_response.body.strip
+ assert_equal "// Bukkit's foo js", last_response.body.strip
get("/assets/bar.js")
- assert_equal "// App's bar js\n;", last_response.body.strip
+ assert_equal "// App's bar js", last_response.body.strip
# ensure that railties are not added twice
railties = Rails.application.send(:ordered_railties).map(&:class)
diff --git a/railties/test/railties/generators_test.rb b/railties/test/railties/generators_test.rb
index 7348d70c56..423ece277e 100644
--- a/railties/test/railties/generators_test.rb
+++ b/railties/test/railties/generators_test.rb
@@ -30,7 +30,7 @@ module RailtiesTests
if File.exist?("#{environment}.rb")
require_environment = "-r #{environment}"
end
- `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/railties/bin/rails #{cmd}`
+ `#{Gem.ruby} #{require_environment} #{RAILS_FRAMEWORK_ROOT}/railties/exe/rails #{cmd}`
end
def build_engine(is_mountable=false)