aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.travis.yml2
-rw-r--r--RELEASING_RAILS.rdoc3
-rw-r--r--actionmailer/lib/action_mailer/base.rb8
-rw-r--r--actionmailer/test/base_test.rb20
-rw-r--r--actionmailer/test/fixtures/base_test/after_action_mailer/welcome.html.erb (renamed from actionmailer/test/fixtures/base_test/after_filter_mailer/welcome.html.erb)0
-rw-r--r--actionmailer/test/fixtures/base_test/before_action_mailer/welcome.html.erb (renamed from actionmailer/test/fixtures/base_test/before_filter_mailer/welcome.html.erb)0
-rw-r--r--actionpack/CHANGELOG.md39
-rw-r--r--actionpack/lib/abstract_controller/callbacks.rb150
-rw-r--r--actionpack/lib/action_controller/metal/conditional_get.rb2
-rw-r--r--actionpack/lib/action_controller/metal/force_ssl.rb4
-rw-r--r--actionpack/lib/action_controller/metal/http_authentication.rb10
-rw-r--r--actionpack/lib/action_controller/metal/instrumentation.rb2
-rw-r--r--actionpack/lib/action_controller/metal/request_forgery_protection.rb12
-rw-r--r--actionpack/lib/action_controller/metal/strong_parameters.rb4
-rw-r--r--actionpack/lib/action_dispatch.rb1
-rw-r--r--actionpack/lib/action_dispatch/http/filter_redirect.rb37
-rw-r--r--actionpack/lib/action_dispatch/http/mime_negotiation.rb4
-rw-r--r--actionpack/lib/action_dispatch/http/response.rb1
-rw-r--r--actionpack/lib/action_dispatch/routing/mapper.rb32
-rw-r--r--actionpack/lib/action_view/helpers/cache_helper.rb14
-rw-r--r--actionpack/test/abstract/callbacks_test.rb92
-rw-r--r--actionpack/test/controller/default_url_options_with_before_action_test.rb (renamed from actionpack/test/controller/default_url_options_with_filter_test.rb)10
-rw-r--r--actionpack/test/controller/flash_test.rb6
-rw-r--r--actionpack/test/controller/http_basic_authentication_test.rb6
-rw-r--r--actionpack/test/controller/http_digest_authentication_test.rb4
-rw-r--r--actionpack/test/controller/http_token_authentication_test.rb6
-rw-r--r--actionpack/test/controller/log_subscriber_test.rb88
-rw-r--r--actionpack/test/controller/mime_responds_test.rb2
-rw-r--r--actionpack/test/controller/new_base/base_test.rb2
-rw-r--r--actionpack/test/controller/new_base/render_context_test.rb2
-rw-r--r--actionpack/test/controller/render_test.rb6
-rw-r--r--actionpack/test/controller/rescue_test.rb4
-rw-r--r--actionpack/test/controller/show_exceptions_test.rb2
-rw-r--r--actionpack/test/controller/view_paths_test.rb2
-rw-r--r--activemodel/lib/active_model/errors.rb6
-rw-r--r--activemodel/lib/active_model/serialization.rb2
-rw-r--r--activemodel/lib/active_model/validator.rb4
-rw-r--r--activerecord/CHANGELOG.md74
-rw-r--r--activerecord/lib/active_record/associations/collection_proxy.rb6
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb16
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb8
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb5
-rw-r--r--activerecord/lib/active_record/migration.rb24
-rw-r--r--activerecord/lib/active_record/persistence.rb2
-rw-r--r--activerecord/lib/active_record/relation/query_methods.rb84
-rw-r--r--activerecord/lib/active_record/schema.rb40
-rw-r--r--activerecord/lib/active_record/schema_dumper.rb21
-rw-r--r--activerecord/lib/active_record/schema_migration.rb39
-rw-r--r--activerecord/lib/active_record/scoping/named.rb4
-rw-r--r--activerecord/test/cases/ar_schema_test.rb51
-rw-r--r--activerecord/test/cases/associations/has_many_associations_test.rb6
-rw-r--r--activerecord/test/cases/migration/logger_test.rb2
-rw-r--r--activerecord/test/cases/migration/table_and_index_test.rb24
-rw-r--r--activerecord/test/cases/migration_test.rb11
-rw-r--r--activerecord/test/cases/migrator_test.rb9
-rw-r--r--activerecord/test/cases/persistence_test.rb16
-rw-r--r--activerecord/test/cases/relation/where_chain_test.rb75
-rw-r--r--activerecord/test/cases/relation/where_test.rb6
-rw-r--r--activerecord/test/cases/schema_dumper_test.rb17
-rw-r--r--activerecord/test/cases/schema_migration_test.rb54
-rw-r--r--activerecord/test/migrations/always_safe/1001_always_safe.rb5
-rw-r--r--activerecord/test/migrations/always_safe/1002_still_safe.rb5
-rw-r--r--activesupport/CHANGELOG.md6
-rw-r--r--activesupport/lib/active_support.rb1
-rw-r--r--activesupport/lib/active_support/basic_object.rb16
-rw-r--r--activesupport/lib/active_support/cache.rb2
-rw-r--r--activesupport/lib/active_support/callbacks.rb4
-rw-r--r--activesupport/lib/active_support/configurable.rb6
-rw-r--r--activesupport/lib/active_support/core_ext/array/conversions.rb6
-rw-r--r--activesupport/lib/active_support/core_ext/class/attribute.rb3
-rw-r--r--activesupport/lib/active_support/core_ext/class/subclasses.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/hash/indifferent_access.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/hash/keys.rb10
-rw-r--r--activesupport/lib/active_support/core_ext/object/deep_dup.rb2
-rw-r--r--activesupport/lib/active_support/dependencies.rb6
-rw-r--r--activesupport/lib/active_support/duration.rb4
-rw-r--r--activesupport/lib/active_support/file_update_checker.rb2
-rw-r--r--activesupport/lib/active_support/inflector/inflections.rb8
-rw-r--r--activesupport/lib/active_support/message_encryptor.rb4
-rw-r--r--activesupport/lib/active_support/message_verifier.rb2
-rw-r--r--activesupport/lib/active_support/multibyte.rb2
-rw-r--r--activesupport/lib/active_support/proxy_object.rb13
-rw-r--r--activesupport/lib/active_support/tagged_logging.rb2
-rw-r--r--activesupport/lib/active_support/test_case.rb2
-rw-r--r--activesupport/lib/active_support/values/time_zone.rb2
-rw-r--r--activesupport/test/core_ext/duration_test.rb4
-rw-r--r--activesupport/test/dependencies_test.rb10
-rw-r--r--guides/rails_guides/generator.rb2
-rw-r--r--guides/source/_welcome.html.erb2
-rw-r--r--guides/source/action_controller_overview.md47
-rw-r--r--guides/source/action_mailer_basics.md8
-rw-r--r--guides/source/action_view_overview.md2
-rw-r--r--guides/source/active_model_basics.md88
-rw-r--r--guides/source/active_record_basics.md42
-rw-r--r--guides/source/active_record_callbacks.md2
-rw-r--r--guides/source/active_record_querying.md14
-rw-r--r--guides/source/active_record_validations.md42
-rw-r--r--guides/source/caching_with_rails.md2
-rw-r--r--guides/source/i18n.md8
-rw-r--r--guides/source/security.md2
-rw-r--r--railties/CHANGELOG.md4
-rw-r--r--railties/lib/rails.rb24
-rw-r--r--railties/lib/rails/application.rb2
-rw-r--r--railties/lib/rails/application/configuration.rb3
-rw-r--r--railties/lib/rails/commands.rb2
-rw-r--r--railties/lib/rails/commands/console.rb2
-rw-r--r--railties/lib/rails/commands/runner.rb2
-rw-r--r--railties/lib/rails/commands/server.rb2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt4
-rw-r--r--railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb2
-rw-r--r--railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb12
-rw-r--r--railties/lib/rails/generators/test_case.rb2
-rw-r--r--railties/test/abstract_unit.rb1
-rw-r--r--railties/test/application/rake/dbs_test.rb30
-rw-r--r--railties/test/application/runner_test.rb18
-rw-r--r--railties/test/commands/console_test.rb23
-rw-r--r--railties/test/commands/server_test.rb16
-rw-r--r--railties/test/env_helpers.rb26
-rw-r--r--railties/test/generators/actions_test.rb31
-rw-r--r--railties/test/generators/scaffold_controller_generator_test.rb14
-rw-r--r--railties/test/generators/scaffold_generator_test.rb28
121 files changed, 1275 insertions, 548 deletions
diff --git a/.travis.yml b/.travis.yml
index 930fc8f583..18b0100c62 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -22,7 +22,7 @@ notifications:
on_success: change
on_failure: always
rooms:
- - secure: "qDX+Bw/tsg0ogYX0y/kTz5d326BL4JfjZQ66my2VdmRNwHyvv+mrONJ627Kt\n/U6HPA2FtSIMhtYWezi6qtGOKqZ3rns9B3gGGuaLgoCKLtCK2xzdR+OmNaNp\nXpuwGod2uABnpaDGDRYhsJ7X/efct1rk/C//S6s2b6rWKHNQd8k="
+ - secure: "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI="
bundler_args: --path vendor/bundle
matrix:
allow_failures:
diff --git a/RELEASING_RAILS.rdoc b/RELEASING_RAILS.rdoc
index af1def223a..9af79f73e2 100644
--- a/RELEASING_RAILS.rdoc
+++ b/RELEASING_RAILS.rdoc
@@ -164,6 +164,9 @@ Today, do this stuff in this order:
* Update RAILS_VERSION to remove the rc
* Build and test the gem
* Release the gems
+* If releasing a new stable version:
+ - Trigger stable docs generation (see below)
+ - Update the version in the home page
* Email security lists
* Email general announcement lists
diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb
index 31005c9d9b..dcf13e927c 100644
--- a/actionmailer/lib/action_mailer/base.rb
+++ b/actionmailer/lib/action_mailer/base.rb
@@ -284,12 +284,12 @@ module ActionMailer
#
# = Callbacks
#
- # You can specify callbacks using before_filter and after_filter for configuring your messages.
+ # You can specify callbacks using before_action and after_action for configuring your messages.
# This may be useful, for example, when you want to add default inline attachments for all
# messages sent out by a certain mailer class:
#
# class Notifier < ActionMailer::Base
- # before_filter :add_inline_attachment!
+ # before_action :add_inline_attachment!
#
# def welcome
# mail
@@ -306,8 +306,8 @@ module ActionMailer
# can define and configure callbacks in the same manner that you would use callbacks in
# classes that inherit from ActionController::Base.
#
- # Note that unless you have a specific reason to do so, you should prefer using before_filter
- # rather than after_filter in your ActionMailer classes so that headers are parsed properly.
+ # Note that unless you have a specific reason to do so, you should prefer using before_action
+ # rather than after_action in your ActionMailer classes so that headers are parsed properly.
#
# = Configuration options
#
diff --git a/actionmailer/test/base_test.rb b/actionmailer/test/base_test.rb
index 3c21886502..4a608a9ad4 100644
--- a/actionmailer/test/base_test.rb
+++ b/actionmailer/test/base_test.rb
@@ -584,9 +584,9 @@ class BaseTest < ActiveSupport::TestCase
assert_equal("Thanks for signing up this afternoon", mail.subject)
end
- test "modifying the mail message with a before_filter" do
- class BeforeFilterMailer < ActionMailer::Base
- before_filter :add_special_header!
+ test "modifying the mail message with a before_action" do
+ class BeforeActionMailer < ActionMailer::Base
+ before_action :add_special_header!
def welcome ; mail ; end
@@ -596,12 +596,12 @@ class BaseTest < ActiveSupport::TestCase
end
end
- assert_equal('Wow, so special', BeforeFilterMailer.welcome['X-Special-Header'].to_s)
+ assert_equal('Wow, so special', BeforeActionMailer.welcome['X-Special-Header'].to_s)
end
- test "modifying the mail message with an after_filter" do
- class AfterFilterMailer < ActionMailer::Base
- after_filter :add_special_header!
+ test "modifying the mail message with an after_action" do
+ class AfterActionMailer < ActionMailer::Base
+ after_action :add_special_header!
def welcome ; mail ; end
@@ -611,12 +611,12 @@ class BaseTest < ActiveSupport::TestCase
end
end
- assert_equal('Testing', AfterFilterMailer.welcome['X-Special-Header'].to_s)
+ assert_equal('Testing', AfterActionMailer.welcome['X-Special-Header'].to_s)
end
- test "adding an inline attachment using a before_filter" do
+ test "adding an inline attachment using a before_action" do
class DefaultInlineAttachmentMailer < ActionMailer::Base
- before_filter :add_inline_attachment!
+ before_action :add_inline_attachment!
def welcome ; mail ; end
diff --git a/actionmailer/test/fixtures/base_test/after_filter_mailer/welcome.html.erb b/actionmailer/test/fixtures/base_test/after_action_mailer/welcome.html.erb
index e69de29bb2..e69de29bb2 100644
--- a/actionmailer/test/fixtures/base_test/after_filter_mailer/welcome.html.erb
+++ b/actionmailer/test/fixtures/base_test/after_action_mailer/welcome.html.erb
diff --git a/actionmailer/test/fixtures/base_test/before_filter_mailer/welcome.html.erb b/actionmailer/test/fixtures/base_test/before_action_mailer/welcome.html.erb
index e69de29bb2..e69de29bb2 100644
--- a/actionmailer/test/fixtures/base_test/before_filter_mailer/welcome.html.erb
+++ b/actionmailer/test/fixtures/base_test/before_action_mailer/welcome.html.erb
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md
index 43fd727500..9db30c8cf7 100644
--- a/actionpack/CHANGELOG.md
+++ b/actionpack/CHANGELOG.md
@@ -1,4 +1,43 @@
## Rails 4.0.0 (unreleased) ##
+
+* Rename all action callbacks from *_filter to *_action to avoid the misconception that these
+ callbacks are only suited for transforming or halting the response. With the new style,
+ it's more inviting to use them as they were intended, like setting shared ivars for views.
+
+ Example:
+
+ class PeopleController < ActionController::Base
+ before_action :set_person, except: [ :index, :new, :create ]
+ before_action :ensure_permission, only: [ :edit, :update ]
+
+ ...
+
+ private
+ def set_person
+ @person = current_account.people.find(params[:id])
+ end
+
+ def ensure_permission
+ current_person.can_change?(@person)
+ end
+ end
+
+ The old *_filter methods still work with no deprecation notice.
+
+ *DHH*
+
+* Add :if / :unless conditions to fragment cache:
+
+ <%= cache @model, if: some_condition(@model) do %>
+
+ *Stephen Ausman + Fabrizio Regini*
+
+* Add filter capability to ActionController logs for redirect locations:
+
+ config.filter_redirect << 'http://please.hide.it/'
+
+ *Fabrizio Regini*
+
* Fixed a bug that ignores constraints on a glob route. This was caused because the constraint
regular expression is overwritten when the `routes.rb` file is processed. Fixes #7924
diff --git a/actionpack/lib/abstract_controller/callbacks.rb b/actionpack/lib/abstract_controller/callbacks.rb
index 02ac111392..599fff81c2 100644
--- a/actionpack/lib/abstract_controller/callbacks.rb
+++ b/actionpack/lib/abstract_controller/callbacks.rb
@@ -40,19 +40,22 @@ module AbstractController
end
end
- # Skip before, after, and around filters matching any of the names
+ # Skip before, after, and around action callbacks matching any of the names
+ # Aliased as skip_filter.
#
# ==== Parameters
# * <tt>names</tt> - A list of valid names that could be used for
# callbacks. Note that skipping uses Ruby equality, so it's
# impossible to skip a callback defined using an anonymous proc
# using #skip_filter
- def skip_filter(*names)
- skip_before_filter(*names)
- skip_after_filter(*names)
- skip_around_filter(*names)
+ def skip_action_callback(*names)
+ skip_before_action(*names)
+ skip_after_action(*names)
+ skip_around_action(*names)
end
+ alias_method :skip_filter, :skip_action_callback
+
# Take callback names and an optional callback proc, normalize them,
# then call the block with each callback. This allows us to abstract
# the normalization across several methods that use it.
@@ -75,119 +78,138 @@ module AbstractController
end
##
- # :method: before_filter
+ # :method: before_action
#
- # :call-seq: before_filter(names, block)
+ # :call-seq: before_action(names, block)
#
- # Append a before filter. See _insert_callbacks for parameter details.
+ # Append a callback before actions. See _insert_callbacks for parameter details.
+ # Aliased as before_filter.
##
- # :method: prepend_before_filter
+ # :method: prepend_before_action
#
- # :call-seq: prepend_before_filter(names, block)
+ # :call-seq: prepend_before_action(names, block)
#
- # Prepend a before filter. See _insert_callbacks for parameter details.
+ # Prepend a callback before actions. See _insert_callbacks for parameter details.
+ # Aliased as prepend_before_filter.
##
- # :method: skip_before_filter
+ # :method: skip_before_action
#
- # :call-seq: skip_before_filter(names)
+ # :call-seq: skip_before_action(names)
#
- # Skip a before filter. See _insert_callbacks for parameter details.
+ # Skip a callback before actions. See _insert_callbacks for parameter details.
+ # Aliased as skip_before_filter.
##
- # :method: append_before_filter
+ # :method: append_before_action
#
- # :call-seq: append_before_filter(names, block)
+ # :call-seq: append_before_action(names, block)
#
- # Append a before filter. See _insert_callbacks for parameter details.
+ # Append a callback before actions. See _insert_callbacks for parameter details.
+ # Aliased as append_before_filter.
##
- # :method: after_filter
+ # :method: after_action
#
- # :call-seq: after_filter(names, block)
+ # :call-seq: after_action(names, block)
#
- # Append an after filter. See _insert_callbacks for parameter details.
+ # Append a callback after actions. See _insert_callbacks for parameter details.
+ # Aliased as after_filter.
##
- # :method: prepend_after_filter
+ # :method: prepend_after_action
#
- # :call-seq: prepend_after_filter(names, block)
+ # :call-seq: prepend_after_action(names, block)
#
- # Prepend an after filter. See _insert_callbacks for parameter details.
+ # Prepend a callback after actions. See _insert_callbacks for parameter details.
+ # Aliased as prepend_after_filter.
##
- # :method: skip_after_filter
+ # :method: skip_after_action
#
- # :call-seq: skip_after_filter(names)
+ # :call-seq: skip_after_action(names)
#
- # Skip an after filter. See _insert_callbacks for parameter details.
+ # Skip a callback after actions. See _insert_callbacks for parameter details.
+ # Aliased as skip_after_filter.
##
- # :method: append_after_filter
+ # :method: append_after_action
#
- # :call-seq: append_after_filter(names, block)
+ # :call-seq: append_after_action(names, block)
#
- # Append an after filter. See _insert_callbacks for parameter details.
+ # Append a callback after actions. See _insert_callbacks for parameter details.
+ # Aliased as append_after_filter.
##
- # :method: around_filter
+ # :method: around_action
#
- # :call-seq: around_filter(names, block)
+ # :call-seq: around_action(names, block)
#
- # Append an around filter. See _insert_callbacks for parameter details.
+ # Append a callback around actions. See _insert_callbacks for parameter details.
+ # Aliased as around_filter.
##
- # :method: prepend_around_filter
+ # :method: prepend_around_action
#
- # :call-seq: prepend_around_filter(names, block)
+ # :call-seq: prepend_around_action(names, block)
#
- # Prepend an around filter. See _insert_callbacks for parameter details.
+ # Prepend a callback around actions. See _insert_callbacks for parameter details.
+ # Aliased as prepend_around_filter.
##
- # :method: skip_around_filter
+ # :method: skip_around_action
#
- # :call-seq: skip_around_filter(names)
+ # :call-seq: skip_around_action(names)
#
- # Skip an around filter. See _insert_callbacks for parameter details.
+ # Skip a callback around actions. See _insert_callbacks for parameter details.
+ # Aliased as skip_around_filter.
##
- # :method: append_around_filter
+ # :method: append_around_action
#
- # :call-seq: append_around_filter(names, block)
+ # :call-seq: append_around_action(names, block)
#
- # Append an around filter. See _insert_callbacks for parameter details.
+ # Append a callback around actions. See _insert_callbacks for parameter details.
+ # Aliased as append_around_filter.
- # set up before_filter, prepend_before_filter, skip_before_filter, etc.
+ # set up before_action, prepend_before_action, skip_before_action, etc.
# for each of before, after, and around.
- [:before, :after, :around].each do |filter|
+ [:before, :after, :around].each do |callback|
class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
- # Append a before, after or around filter. See _insert_callbacks
+ # Append a before, after or around callback. See _insert_callbacks
# for details on the allowed parameters.
- def #{filter}_filter(*names, &blk) # def before_filter(*names, &blk)
- _insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options|
- set_callback(:process_action, :#{filter}, name, options) # set_callback(:process_action, :before, name, options)
- end # end
- end # end
+ def #{callback}_action(*names, &blk) # def before_action(*names, &blk)
+ _insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options|
+ set_callback(:process_action, :#{callback}, name, options) # set_callback(:process_action, :before, name, options)
+ end # end
+ end # end
+
+ alias_method :#{callback}_filter, :#{callback}_action
- # Prepend a before, after or around filter. See _insert_callbacks
+ # Prepend a before, after or around callback. See _insert_callbacks
# for details on the allowed parameters.
- def prepend_#{filter}_filter(*names, &blk) # def prepend_before_filter(*names, &blk)
- _insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options|
- set_callback(:process_action, :#{filter}, name, options.merge(:prepend => true)) # set_callback(:process_action, :before, name, options.merge(:prepend => true))
- end # end
- end # end
+ def prepend_#{callback}_action(*names, &blk) # def prepend_before_action(*names, &blk)
+ _insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options|
+ set_callback(:process_action, :#{callback}, name, options.merge(:prepend => true)) # set_callback(:process_action, :before, name, options.merge(:prepend => true))
+ end # end
+ end # end
+
+ alias_method :prepend_#{callback}_filter, :prepend_#{callback}_action
- # Skip a before, after or around filter. See _insert_callbacks
+ # Skip a before, after or around callback. See _insert_callbacks
# for details on the allowed parameters.
- def skip_#{filter}_filter(*names) # def skip_before_filter(*names)
- _insert_callbacks(names) do |name, options| # _insert_callbacks(names) do |name, options|
- skip_callback(:process_action, :#{filter}, name, options) # skip_callback(:process_action, :before, name, options)
- end # end
- end # end
-
- # *_filter is the same as append_*_filter
- alias_method :append_#{filter}_filter, :#{filter}_filter # alias_method :append_before_filter, :before_filter
+ def skip_#{callback}_action(*names) # def skip_before_action(*names)
+ _insert_callbacks(names) do |name, options| # _insert_callbacks(names) do |name, options|
+ skip_callback(:process_action, :#{callback}, name, options) # skip_callback(:process_action, :before, name, options)
+ end # end
+ end # end
+
+ alias_method :skip_#{callback}_filter, :skip_#{callback}_action
+
+ # *_action is the same as append_*_action
+ alias_method :append_#{callback}_action, :#{callback}_action # alias_method :append_before_action, :before_action
+ alias_method :append_#{callback}_filter, :#{callback}_action # alias_method :append_before_filter, :before_action
RUBY_EVAL
end
end
diff --git a/actionpack/lib/action_controller/metal/conditional_get.rb b/actionpack/lib/action_controller/metal/conditional_get.rb
index 426adfe675..3f9b382a11 100644
--- a/actionpack/lib/action_controller/metal/conditional_get.rb
+++ b/actionpack/lib/action_controller/metal/conditional_get.rb
@@ -42,7 +42,7 @@ module ActionController
# * <tt>:public</tt> By default the Cache-Control header is private, set this to
# +true+ if you want your application to be cachable by other devices (proxy caches).
#
- # === Example:
+ # === Example:
#
# def show
# @article = Article.find(params[:id])
diff --git a/actionpack/lib/action_controller/metal/force_ssl.rb b/actionpack/lib/action_controller/metal/force_ssl.rb
index c38d8ccef3..f1e8714a86 100644
--- a/actionpack/lib/action_controller/metal/force_ssl.rb
+++ b/actionpack/lib/action_controller/metal/force_ssl.rb
@@ -32,14 +32,14 @@ module ActionController
# ==== Options
# * <tt>host</tt> - Redirect to a different host name
# * <tt>only</tt> - The callback should be run only for this action
- # * <tt>except</tt> - The callback should be run for all actions except this action
+ # * <tt>except</tt> - The callback should be run for all actions except this action
# * <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.
def force_ssl(options = {})
host = options.delete(:host)
- before_filter(options) do
+ before_action(options) do
force_ssl_redirect(host)
end
end
diff --git a/actionpack/lib/action_controller/metal/http_authentication.rb b/actionpack/lib/action_controller/metal/http_authentication.rb
index d3b5bafee1..283f6413ec 100644
--- a/actionpack/lib/action_controller/metal/http_authentication.rb
+++ b/actionpack/lib/action_controller/metal/http_authentication.rb
@@ -25,7 +25,7 @@ module ActionController
# the regular HTML interface is protected by a session approach:
#
# class ApplicationController < ActionController::Base
- # before_filter :set_account, :authenticate
+ # before_action :set_account, :authenticate
#
# protected
# def set_account
@@ -68,7 +68,7 @@ module ActionController
module ClassMethods
def http_basic_authenticate_with(options = {})
- before_filter(options.except(:name, :password, :realm)) do
+ before_action(options.except(:name, :password, :realm)) do
authenticate_or_request_with_http_basic(options[:realm] || "Application") do |name, password|
name == options[:name] && password == options[:password]
end
@@ -124,7 +124,7 @@ module ActionController
# USERS = {"dhh" => "secret", #plain text password
# "dap" => Digest::MD5.hexdigest(["dap",REALM,"secret"].join(":"))} #ha1 digest password
#
- # before_filter :authenticate, except: [:index]
+ # before_action :authenticate, except: [:index]
#
# def index
# render text: "Everyone can see me!"
@@ -317,7 +317,7 @@ module ActionController
# class PostsController < ApplicationController
# TOKEN = "secret"
#
- # before_filter :authenticate, except: [ :index ]
+ # before_action :authenticate, except: [ :index ]
#
# def index
# render text: "Everyone can see me!"
@@ -340,7 +340,7 @@ module ActionController
# the regular HTML interface is protected by a session approach:
#
# class ApplicationController < ActionController::Base
- # before_filter :set_account, :authenticate
+ # before_action :set_account, :authenticate
#
# protected
# def set_account
diff --git a/actionpack/lib/action_controller/metal/instrumentation.rb b/actionpack/lib/action_controller/metal/instrumentation.rb
index ca4ae532ca..d3aa8f90c5 100644
--- a/actionpack/lib/action_controller/metal/instrumentation.rb
+++ b/actionpack/lib/action_controller/metal/instrumentation.rb
@@ -60,7 +60,7 @@ module ActionController
ActiveSupport::Notifications.instrument("redirect_to.action_controller") do |payload|
result = super
payload[:status] = response.status
- payload[:location] = response.location
+ payload[:location] = response.filtered_location
result
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 265ce5d6f3..c5db0cb0d4 100644
--- a/actionpack/lib/action_controller/metal/request_forgery_protection.rb
+++ b/actionpack/lib/action_controller/metal/request_forgery_protection.rb
@@ -19,7 +19,7 @@ module ActionController #:nodoc:
#
# class ApplicationController < ActionController::Base
# protect_from_forgery
- # skip_before_filter :verify_authenticity_token, if: :json_request?
+ # skip_before_action :verify_authenticity_token, if: :json_request?
#
# protected
#
@@ -66,15 +66,15 @@ module ActionController #:nodoc:
#
# You can disable csrf protection on controller-by-controller basis:
#
- # skip_before_filter :verify_authenticity_token
+ # skip_before_action :verify_authenticity_token
#
# It can also be disabled for specific controller actions:
#
- # skip_before_filter :verify_authenticity_token, except: [:create]
+ # skip_before_action :verify_authenticity_token, except: [:create]
#
# Valid Options:
#
- # * <tt>:only/:except</tt> - Passed to the <tt>before_filter</tt> call. Set which actions are verified.
+ # * <tt>:only/:except</tt> - Passed to the <tt>before_action</tt> call. Set which actions are verified.
# * <tt>:with</tt> - Set the method to handle unverified request.
#
# Valid unverified request handling methods are:
@@ -84,7 +84,7 @@ module ActionController #:nodoc:
def protect_from_forgery(options = {})
include protection_method_module(options[:with] || :null_session)
self.request_forgery_protection_token ||= :authenticity_token
- prepend_before_filter :verify_authenticity_token, options
+ prepend_before_action :verify_authenticity_token, options
end
private
@@ -152,7 +152,7 @@ module ActionController #:nodoc:
end
protected
- # The actual before_filter that is used. Modify this to change how you handle unverified requests.
+ # The actual before_action that is used. Modify this to change how you handle unverified requests.
def verify_authenticity_token
unless verified_request?
logger.warn "Can't verify CSRF token authenticity" if logger
diff --git a/actionpack/lib/action_controller/metal/strong_parameters.rb b/actionpack/lib/action_controller/metal/strong_parameters.rb
index 386075bd30..25e72adbe0 100644
--- a/actionpack/lib/action_controller/metal/strong_parameters.rb
+++ b/actionpack/lib/action_controller/metal/strong_parameters.rb
@@ -163,7 +163,7 @@ module ActionController
# }
# })
#
- # permitted = params.permit(person: [ :name, { pets: :name } ])
+ # permitted = params.permit(person: [ :name, { pets: :name } ])
# permitted.permitted? # => true
# permitted[:person][:name] # => "Francesco"
# permitted[:person][:age] # => nil
@@ -228,7 +228,7 @@ module ActionController
# Returns a parameter for the given +key+. If not found,
# returns +nil+.
#
- # params = ActionController::Parameters.new(person: { name: 'Francesco' })
+ # params = ActionController::Parameters.new(person: { name: 'Francesco' })
# params[:person] # => {"name"=>"Francesco"}
# params[:none] # => nil
def [](key)
diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb
index 1d716a3248..d002babee3 100644
--- a/actionpack/lib/action_dispatch.rb
+++ b/actionpack/lib/action_dispatch.rb
@@ -75,6 +75,7 @@ module ActionDispatch
autoload :Parameters
autoload :ParameterFilter
autoload :FilterParameters
+ autoload :FilterRedirect
autoload :Upload
autoload :UploadedFile, 'action_dispatch/http/upload'
autoload :URL
diff --git a/actionpack/lib/action_dispatch/http/filter_redirect.rb b/actionpack/lib/action_dispatch/http/filter_redirect.rb
new file mode 100644
index 0000000000..900ce1c646
--- /dev/null
+++ b/actionpack/lib/action_dispatch/http/filter_redirect.rb
@@ -0,0 +1,37 @@
+module ActionDispatch
+ module Http
+ module FilterRedirect
+
+ FILTERED = '[FILTERED]'.freeze # :nodoc:
+
+ def filtered_location
+ if !location_filter.empty? && location_filter_match?
+ FILTERED
+ else
+ location
+ end
+ end
+
+ private
+
+ def location_filter
+ if request.present?
+ request.env['action_dispatch.redirect_filter'] || []
+ else
+ []
+ end
+ end
+
+ def location_filter_match?
+ location_filter.any? do |filter|
+ if String === filter
+ location.include?(filter)
+ elsif Regexp === filter
+ location.match(filter)
+ end
+ end
+ end
+
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/http/mime_negotiation.rb b/actionpack/lib/action_dispatch/http/mime_negotiation.rb
index 0f98e84788..57660e93c4 100644
--- a/actionpack/lib/action_dispatch/http/mime_negotiation.rb
+++ b/actionpack/lib/action_dispatch/http/mime_negotiation.rb
@@ -68,7 +68,7 @@ module ActionDispatch
# that are not controlled by the extension.
#
# class ApplicationController < ActionController::Base
- # before_filter :adjust_format_for_iphone
+ # before_action :adjust_format_for_iphone
#
# private
# def adjust_format_for_iphone
@@ -87,7 +87,7 @@ module ActionDispatch
# to the :html format.
#
# class ApplicationController < ActionController::Base
- # before_filter :adjust_format_for_iphone_with_html_fallback
+ # before_action :adjust_format_for_iphone_with_html_fallback
#
# private
# def adjust_format_for_iphone_with_html_fallback
diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb
index 11b7534ea4..0f808ac9cf 100644
--- a/actionpack/lib/action_dispatch/http/response.rb
+++ b/actionpack/lib/action_dispatch/http/response.rb
@@ -61,6 +61,7 @@ module ActionDispatch # :nodoc:
cattr_accessor(:default_headers)
include Rack::Response::Helpers
+ include ActionDispatch::Http::FilterRedirect
include ActionDispatch::Http::Cache::Response
include MonitorMixin
diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb
index 55e4561e8e..3c99932e72 100644
--- a/actionpack/lib/action_dispatch/routing/mapper.rb
+++ b/actionpack/lib/action_dispatch/routing/mapper.rb
@@ -1048,15 +1048,7 @@ module ActionDispatch
get :new
end if parent_resource.actions.include?(:new)
- member do
- get :edit if parent_resource.actions.include?(:edit)
- get :show if parent_resource.actions.include?(:show)
- if parent_resource.actions.include?(:update)
- patch :update
- put :update
- end
- delete :destroy if parent_resource.actions.include?(:destroy)
- end
+ set_member_mappings_for_resource
end
self
@@ -1215,15 +1207,7 @@ module ActionDispatch
get :new
end if parent_resource.actions.include?(:new)
- member do
- get :edit if parent_resource.actions.include?(:edit)
- get :show if parent_resource.actions.include?(:show)
- if parent_resource.actions.include?(:update)
- patch :update
- put :update
- end
- delete :destroy if parent_resource.actions.include?(:destroy)
- end
+ set_member_mappings_for_resource
end
self
@@ -1574,6 +1558,18 @@ module ActionDispatch
end
end
end
+
+ def set_member_mappings_for_resource
+ member do
+ get :edit if parent_resource.actions.include?(:edit)
+ get :show if parent_resource.actions.include?(:show)
+ if parent_resource.actions.include?(:update)
+ patch :update
+ put :update
+ end
+ delete :destroy if parent_resource.actions.include?(:destroy)
+ end
+ end
end
# Routing Concerns allow you to declare common routes that can be reused
diff --git a/actionpack/lib/action_view/helpers/cache_helper.rb b/actionpack/lib/action_view/helpers/cache_helper.rb
index db920ae7a4..8693f4f0e4 100644
--- a/actionpack/lib/action_view/helpers/cache_helper.rb
+++ b/actionpack/lib/action_view/helpers/cache_helper.rb
@@ -110,8 +110,15 @@ module ActionView
# <%= some_helper_method(person) %>
#
# Now all you'll have to do is change that timestamp when the helper method changes.
+ #
+ # ==== Conditional caching
+ #
+ # You can pass :if and :unless options, to conditionally perform or skip the cache.
+ #
+ # <%= cache @model, if: some_condition(@model) do %>
+ #
def cache(name = {}, options = nil, &block)
- if controller.perform_caching
+ if controller.perform_caching && conditions_match?(options)
safe_concat(fragment_for(cache_fragment_name(name, options), options, &block))
else
yield
@@ -136,6 +143,11 @@ module ActionView
end
private
+
+ def conditions_match?(options)
+ !(options && (!options.fetch(:if, true) || options.fetch(:unless, false)))
+ end
+
def fragment_name_with_digest(name) #:nodoc:
if @virtual_path
[
diff --git a/actionpack/test/abstract/callbacks_test.rb b/actionpack/test/abstract/callbacks_test.rb
index 5d1a703c55..1090af3060 100644
--- a/actionpack/test/abstract/callbacks_test.rb
+++ b/actionpack/test/abstract/callbacks_test.rb
@@ -28,9 +28,9 @@ module AbstractController
end
class Callback2 < ControllerWithCallbacks
- before_filter :first
- after_filter :second
- around_filter :aroundz
+ before_action :first
+ after_action :second
+ around_action :aroundz
def first
@text = "Hello world"
@@ -53,7 +53,7 @@ module AbstractController
end
class Callback2Overwrite < Callback2
- before_filter :first, :except => :index
+ before_action :first, except: :index
end
class TestCallbacks2 < ActiveSupport::TestCase
@@ -61,22 +61,22 @@ module AbstractController
@controller = Callback2.new
end
- test "before_filter works" do
+ test "before_action works" do
@controller.process(:index)
assert_equal "Hello world", @controller.response_body
end
- test "after_filter works" do
+ test "after_action works" do
@controller.process(:index)
assert_equal "Goodbye", @controller.instance_variable_get("@second")
end
- test "around_filter works" do
+ test "around_action works" do
@controller.process(:index)
assert_equal "FIRSTSECOND", @controller.instance_variable_get("@aroundz")
end
- test "before_filter with overwritten condition" do
+ test "before_action with overwritten condition" do
@controller = Callback2Overwrite.new
@controller.process(:index)
assert_equal "", @controller.response_body
@@ -84,11 +84,11 @@ module AbstractController
end
class Callback3 < ControllerWithCallbacks
- before_filter do |c|
+ before_action do |c|
c.instance_variable_set("@text", "Hello world")
end
- after_filter do |c|
+ after_action do |c|
c.instance_variable_set("@second", "Goodbye")
end
@@ -102,20 +102,20 @@ module AbstractController
@controller = Callback3.new
end
- test "before_filter works with procs" do
+ test "before_action works with procs" do
@controller.process(:index)
assert_equal "Hello world", @controller.response_body
end
- test "after_filter works with procs" do
+ test "after_action works with procs" do
@controller.process(:index)
assert_equal "Goodbye", @controller.instance_variable_get("@second")
end
end
class CallbacksWithConditions < ControllerWithCallbacks
- before_filter :list, :only => :index
- before_filter :authenticate, :except => :index
+ before_action :list, :only => :index
+ before_action :authenticate, :except => :index
def index
self.response_body = @list.join(", ")
@@ -141,25 +141,25 @@ module AbstractController
@controller = CallbacksWithConditions.new
end
- test "when :only is specified, a before filter is triggered on that action" do
+ test "when :only is specified, a before action is triggered on that action" do
@controller.process(:index)
assert_equal "Hello, World", @controller.response_body
end
- test "when :only is specified, a before filter is not triggered on other actions" do
+ test "when :only is specified, a before action is not triggered on other actions" do
@controller.process(:sekrit_data)
assert_equal "true", @controller.response_body
end
- test "when :except is specified, an after filter is not triggered on that action" do
+ test "when :except is specified, an after action is not triggered on that action" do
@controller.process(:index)
assert !@controller.instance_variable_defined?("@authenticated")
end
end
class CallbacksWithArrayConditions < ControllerWithCallbacks
- before_filter :list, :only => [:index, :listy]
- before_filter :authenticate, :except => [:index, :listy]
+ before_action :list, only: [:index, :listy]
+ before_action :authenticate, except: [:index, :listy]
def index
self.response_body = @list.join(", ")
@@ -185,24 +185,24 @@ module AbstractController
@controller = CallbacksWithArrayConditions.new
end
- test "when :only is specified with an array, a before filter is triggered on that action" do
+ test "when :only is specified with an array, a before action is triggered on that action" do
@controller.process(:index)
assert_equal "Hello, World", @controller.response_body
end
- test "when :only is specified with an array, a before filter is not triggered on other actions" do
+ test "when :only is specified with an array, a before action is not triggered on other actions" do
@controller.process(:sekrit_data)
assert_equal "true", @controller.response_body
end
- test "when :except is specified with an array, an after filter is not triggered on that action" do
+ test "when :except is specified with an array, an after action is not triggered on that action" do
@controller.process(:index)
assert !@controller.instance_variable_defined?("@authenticated")
end
end
class ChangedConditions < Callback2
- before_filter :first, :only => :index
+ before_action :first, :only => :index
def not_index
@text ||= nil
@@ -227,7 +227,7 @@ module AbstractController
end
class SetsResponseBody < ControllerWithCallbacks
- before_filter :set_body
+ before_action :set_body
def index
self.response_body = "Fail"
@@ -266,6 +266,50 @@ module AbstractController
end
end
+ class AliasedCallbacks < ControllerWithCallbacks
+ before_filter :first
+ after_filter :second
+ around_filter :aroundz
+
+ def first
+ @text = "Hello world"
+ end
+
+ def second
+ @second = "Goodbye"
+ end
+
+ def aroundz
+ @aroundz = "FIRST"
+ yield
+ @aroundz << "SECOND"
+ end
+ def index
+ @text ||= nil
+ self.response_body = @text.to_s
+ end
+ end
+
+ class TestAliasedCallbacks < ActiveSupport::TestCase
+ def setup
+ @controller = AliasedCallbacks.new
+ end
+
+ test "before_filter works" do
+ @controller.process(:index)
+ assert_equal "Hello world", @controller.response_body
+ end
+
+ test "after_filter works" do
+ @controller.process(:index)
+ assert_equal "Goodbye", @controller.instance_variable_get("@second")
+ end
+
+ test "around_filter works" do
+ @controller.process(:index)
+ assert_equal "FIRSTSECOND", @controller.instance_variable_get("@aroundz")
+ end
+ end
end
end
diff --git a/actionpack/test/controller/default_url_options_with_filter_test.rb b/actionpack/test/controller/default_url_options_with_before_action_test.rb
index 9a9ab17fee..656fd0431e 100644
--- a/actionpack/test/controller/default_url_options_with_filter_test.rb
+++ b/actionpack/test/controller/default_url_options_with_before_action_test.rb
@@ -1,10 +1,10 @@
require 'abstract_unit'
-class ControllerWithBeforeFilterAndDefaultUrlOptions < ActionController::Base
+class ControllerWithBeforeActionAndDefaultUrlOptions < ActionController::Base
- before_filter { I18n.locale = params[:locale] }
- after_filter { I18n.locale = "en" }
+ before_action { I18n.locale = params[:locale] }
+ after_action { I18n.locale = "en" }
def target
render :text => "final response"
@@ -19,11 +19,11 @@ class ControllerWithBeforeFilterAndDefaultUrlOptions < ActionController::Base
end
end
-class ControllerWithBeforeFilterAndDefaultUrlOptionsTest < ActionController::TestCase
+class ControllerWithBeforeActionAndDefaultUrlOptionsTest < ActionController::TestCase
# This test has its roots in issue #1872
test "should redirect with correct locale :de" do
get :redirect, :locale => "de"
- assert_redirected_to "/controller_with_before_filter_and_default_url_options/target?locale=de"
+ assert_redirected_to "/controller_with_before_action_and_default_url_options/target?locale=de"
end
end
diff --git a/actionpack/test/controller/flash_test.rb b/actionpack/test/controller/flash_test.rb
index 6414ba3994..9d4356f546 100644
--- a/actionpack/test/controller/flash_test.rb
+++ b/actionpack/test/controller/flash_test.rb
@@ -53,8 +53,8 @@ class FlashTest < ActionController::TestCase
render :inline => "hello"
end
- # methods for test_sweep_after_halted_filter_chain
- before_filter :halt_and_redir, :only => "filter_halting_action"
+ # methods for test_sweep_after_halted_action_chain
+ before_action :halt_and_redir, only: 'filter_halting_action'
def std_action
@flash_copy = {}.update(flash)
@@ -159,7 +159,7 @@ class FlashTest < ActionController::TestCase
assert_nil session["flash"]
end
- def test_sweep_after_halted_filter_chain
+ def test_sweep_after_halted_action_chain
get :std_action
assert_nil assigns["flash_copy"]["foo"]
get :filter_halting_action
diff --git a/actionpack/test/controller/http_basic_authentication_test.rb b/actionpack/test/controller/http_basic_authentication_test.rb
index 2dcfda02a7..90548d4294 100644
--- a/actionpack/test/controller/http_basic_authentication_test.rb
+++ b/actionpack/test/controller/http_basic_authentication_test.rb
@@ -2,9 +2,9 @@ require 'abstract_unit'
class HttpBasicAuthenticationTest < ActionController::TestCase
class DummyController < ActionController::Base
- before_filter :authenticate, :only => :index
- before_filter :authenticate_with_request, :only => :display
- before_filter :authenticate_long_credentials, :only => :show
+ before_action :authenticate, only: :index
+ before_action :authenticate_with_request, only: :display
+ before_action :authenticate_long_credentials, only: :show
http_basic_authenticate_with :name => "David", :password => "Goliath", :only => :search
diff --git a/actionpack/test/controller/http_digest_authentication_test.rb b/actionpack/test/controller/http_digest_authentication_test.rb
index c4a94264c3..537de7a2dd 100644
--- a/actionpack/test/controller/http_digest_authentication_test.rb
+++ b/actionpack/test/controller/http_digest_authentication_test.rb
@@ -4,8 +4,8 @@ require 'active_support/key_generator'
class HttpDigestAuthenticationTest < ActionController::TestCase
class DummyDigestController < ActionController::Base
- before_filter :authenticate, :only => :index
- before_filter :authenticate_with_request, :only => :display
+ before_action :authenticate, only: :index
+ before_action :authenticate_with_request, only: :display
USERS = { 'lifo' => 'world', 'pretty' => 'please',
'dhh' => ::Digest::MD5::hexdigest(["dhh","SuperSecret","secret"].join(":"))}
diff --git a/actionpack/test/controller/http_token_authentication_test.rb b/actionpack/test/controller/http_token_authentication_test.rb
index ad4e743be8..8a409d6ed2 100644
--- a/actionpack/test/controller/http_token_authentication_test.rb
+++ b/actionpack/test/controller/http_token_authentication_test.rb
@@ -2,9 +2,9 @@ require 'abstract_unit'
class HttpTokenAuthenticationTest < ActionController::TestCase
class DummyController < ActionController::Base
- before_filter :authenticate, :only => :index
- before_filter :authenticate_with_request, :only => :display
- before_filter :authenticate_long_credentials, :only => :show
+ before_action :authenticate, only: :index
+ before_action :authenticate_with_request, only: :display
+ before_action :authenticate_long_credentials, only: :show
def index
render :text => "Hello Secret"
diff --git a/actionpack/test/controller/log_subscriber_test.rb b/actionpack/test/controller/log_subscriber_test.rb
index 9efb6ab95f..929545fc10 100644
--- a/actionpack/test/controller/log_subscriber_test.rb
+++ b/actionpack/test/controller/log_subscriber_test.rb
@@ -13,7 +13,7 @@ module Another
head :status => 406
end
- before_filter :redirector, :only => :never_executed
+ before_action :redirector, only: :never_executed
def never_executed
end
@@ -26,6 +26,10 @@ module Another
redirect_to "http://foo.bar/"
end
+ def filterable_redirector
+ redirect_to "http://secret.foo.bar/"
+ end
+
def data_sender
send_data "cool data", :filename => "file.txt"
end
@@ -42,6 +46,22 @@ module Another
render :inline => "<%= cache('foo%bar'){ 'Contains % sign in key' } %>"
end
+ def with_fragment_cache_and_if_true_condition
+ render :inline => "<%= cache('foo', :if => true) { 'bar' } %>"
+ end
+
+ def with_fragment_cache_and_if_false_condition
+ render :inline => "<%= cache('foo', :if => false) { 'bar' } %>"
+ end
+
+ def with_fragment_cache_and_unless_false_condition
+ render :inline => "<%= cache('foo', :unless => false) { 'bar' } %>"
+ end
+
+ def with_fragment_cache_and_unless_true_condition
+ render :inline => "<%= cache('foo', :unless => true) { 'bar' } %>"
+ end
+
def with_exception
raise Exception
end
@@ -152,6 +172,24 @@ class ACLogSubscriberTest < ActionController::TestCase
assert_equal "Redirected to http://foo.bar/", logs[1]
end
+ def test_filter_redirect_url_by_string
+ @request.env['action_dispatch.redirect_filter'] = ['secret']
+ get :filterable_redirector
+ wait
+
+ assert_equal 3, logs.size
+ assert_equal "Redirected to [FILTERED]", logs[1]
+ end
+
+ def test_filter_redirect_url_by_regexp
+ @request.env['action_dispatch.redirect_filter'] = [/secret\.foo.+/]
+ get :filterable_redirector
+ wait
+
+ assert_equal 3, logs.size
+ assert_equal "Redirected to [FILTERED]", logs[1]
+ end
+
def test_send_data
get :data_sender
wait
@@ -181,6 +219,54 @@ class ACLogSubscriberTest < ActionController::TestCase
@controller.config.perform_caching = true
end
+ def test_with_fragment_cache_and_if_true
+ @controller.config.perform_caching = true
+ get :with_fragment_cache_and_if_true_condition
+ wait
+
+ assert_equal 4, logs.size
+ assert_match(/Read fragment views\/foo/, logs[1])
+ assert_match(/Write fragment views\/foo/, logs[2])
+ ensure
+ @controller.config.perform_caching = true
+ end
+
+ def test_with_fragment_cache_and_if_false
+ @controller.config.perform_caching = true
+ get :with_fragment_cache_and_if_false_condition
+ wait
+
+ assert_equal 2, logs.size
+ assert_no_match(/Read fragment views\/foo/, logs[1])
+ assert_no_match(/Write fragment views\/foo/, logs[2])
+ ensure
+ @controller.config.perform_caching = true
+ end
+
+ def test_with_fragment_cache_and_unless_true
+ @controller.config.perform_caching = true
+ get :with_fragment_cache_and_unless_true_condition
+ wait
+
+ assert_equal 2, logs.size
+ assert_no_match(/Read fragment views\/foo/, logs[1])
+ assert_no_match(/Write fragment views\/foo/, logs[2])
+ ensure
+ @controller.config.perform_caching = true
+ end
+
+ def test_with_fragment_cache_and_unless_false
+ @controller.config.perform_caching = true
+ get :with_fragment_cache_and_unless_false_condition
+ wait
+
+ assert_equal 4, logs.size
+ assert_match(/Read fragment views\/foo/, logs[1])
+ assert_match(/Write fragment views\/foo/, logs[2])
+ ensure
+ @controller.config.perform_caching = true
+ end
+
def test_with_fragment_cache_and_percent_in_key
@controller.config.perform_caching = true
get :with_fragment_cache_and_percent_in_key
diff --git a/actionpack/test/controller/mime_responds_test.rb b/actionpack/test/controller/mime_responds_test.rb
index d183b0be17..ed013e2185 100644
--- a/actionpack/test/controller/mime_responds_test.rb
+++ b/actionpack/test/controller/mime_responds_test.rb
@@ -1139,7 +1139,7 @@ end
# For testing layouts which are set automatically
class PostController < AbstractPostController
- around_filter :with_iphone
+ around_action :with_iphone
def index
respond_to(:html, :iphone, :js)
diff --git a/actionpack/test/controller/new_base/base_test.rb b/actionpack/test/controller/new_base/base_test.rb
index ed244513a5..964f22eb03 100644
--- a/actionpack/test/controller/new_base/base_test.rb
+++ b/actionpack/test/controller/new_base/base_test.rb
@@ -3,7 +3,7 @@ require 'abstract_unit'
# Tests the controller dispatching happy path
module Dispatching
class SimpleController < ActionController::Base
- before_filter :authenticate
+ before_action :authenticate
def index
render :text => "success"
diff --git a/actionpack/test/controller/new_base/render_context_test.rb b/actionpack/test/controller/new_base/render_context_test.rb
index f41b14d5d6..177a1c088d 100644
--- a/actionpack/test/controller/new_base/render_context_test.rb
+++ b/actionpack/test/controller/new_base/render_context_test.rb
@@ -14,7 +14,7 @@ module RenderContext
include ActionView::Context
# 2) Call _prepare_context that will do the required initialization
- before_filter :_prepare_context
+ before_action :_prepare_context
def hello_world
@value = "Hello"
diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb
index 859ed1466b..7640bc12a2 100644
--- a/actionpack/test/controller/render_test.rb
+++ b/actionpack/test/controller/render_test.rb
@@ -37,7 +37,7 @@ end
class TestController < ActionController::Base
protect_from_forgery
- before_filter :set_variable_for_layout
+ before_action :set_variable_for_layout
class LabellingFormBuilder < ActionView::Helpers::FormBuilder
end
@@ -137,7 +137,7 @@ class TestController < ActionController::Base
def conditional_hello_with_bangs
render :action => 'hello_world'
end
- before_filter :handle_last_modified_and_etags, :only=>:conditional_hello_with_bangs
+ before_action :handle_last_modified_and_etags, :only=>:conditional_hello_with_bangs
def handle_last_modified_and_etags
fresh_when(:last_modified => Time.now.utc.beginning_of_day, :etag => [ :foo, 123 ])
@@ -710,7 +710,7 @@ class TestController < ActionController::Base
render :action => "calling_partial_with_layout", :layout => "layouts/partial_with_layout"
end
- before_filter :only => :render_with_filters do
+ before_action only: :render_with_filters do
request.format = :xml
end
diff --git a/actionpack/test/controller/rescue_test.rb b/actionpack/test/controller/rescue_test.rb
index 48e2d6491e..4898b0c57f 100644
--- a/actionpack/test/controller/rescue_test.rb
+++ b/actionpack/test/controller/rescue_test.rb
@@ -68,9 +68,9 @@ class RescueController < ActionController::Base
render :text => 'io error'
end
- before_filter(:only => :before_filter_raises) { raise 'umm nice' }
+ before_action(only: :before_action_raises) { raise 'umm nice' }
- def before_filter_raises
+ def before_action_raises
end
def raises
diff --git a/actionpack/test/controller/show_exceptions_test.rb b/actionpack/test/controller/show_exceptions_test.rb
index 718d06ef38..888791b874 100644
--- a/actionpack/test/controller/show_exceptions_test.rb
+++ b/actionpack/test/controller/show_exceptions_test.rb
@@ -5,7 +5,7 @@ module ShowExceptions
use ActionDispatch::ShowExceptions, ActionDispatch::PublicExceptions.new("#{FIXTURE_LOAD_PATH}/public")
use ActionDispatch::DebugExceptions
- before_filter :only => :another_boom do
+ before_action only: :another_boom do
request.env["action_dispatch.show_detailed_exceptions"] = true
end
diff --git a/actionpack/test/controller/view_paths_test.rb b/actionpack/test/controller/view_paths_test.rb
index 40f6dc6f0f..c6e7a523b9 100644
--- a/actionpack/test/controller/view_paths_test.rb
+++ b/actionpack/test/controller/view_paths_test.rb
@@ -4,7 +4,7 @@ class ViewLoadPathsTest < ActionController::TestCase
class TestController < ActionController::Base
def self.controller_path() "test" end
- before_filter :add_view_path, :only => :hello_world_at_request_time
+ before_action :add_view_path, only: :hello_world_at_request_time
def hello_world() end
def hello_world_at_request_time() render(:action => 'hello_world') end
diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb
index c82d4f012c..963e52bff3 100644
--- a/activemodel/lib/active_model/errors.rb
+++ b/activemodel/lib/active_model/errors.rb
@@ -122,7 +122,7 @@ module ActiveModel
# Delete messages for +key+. Returns the deleted messages.
#
# person.errors.get(:name) # => ["can not be nil"]
- # person.errors.delete(:name) # => ["can not be nil"]
+ # person.errors.delete(:name) # => ["can not be nil"]
# person.errors.get(:name) # => nil
def delete(key)
messages.delete(key)
@@ -213,7 +213,7 @@ module ActiveModel
# 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 can not be nil"]
+ # person.errors.full_messages # => ["name can not be nil"]
# person.errors.empty? # => false
def empty?
all? { |k, v| v && v.empty? && !v.is_a?(String) }
@@ -246,7 +246,7 @@ module ActiveModel
to_hash(options && options[:full_messages])
end
- # Returns a Hash of attributes with their error messages. If +full_messages+
+ # Returns a Hash of attributes with their error messages. If +full_messages+
# is +true+, it will contain full messages (see +full_message+).
#
# person.to_hash # => {:name=>["can not be nil"]}
diff --git a/activemodel/lib/active_model/serialization.rb b/activemodel/lib/active_model/serialization.rb
index dfd68a90fd..fdb06aebb9 100644
--- a/activemodel/lib/active_model/serialization.rb
+++ b/activemodel/lib/active_model/serialization.rb
@@ -90,7 +90,7 @@ module ActiveModel
# person.name = 'bob'
# person.age = 22
# person.serializable_hash # => {"name"=>"bob", "age"=>22}
- # person.serializable_hash(only: :name) # => {"name"=>"bob"}
+ # person.serializable_hash(only: :name) # => {"name"=>"bob"}
# person.serializable_hash(except: :name) # => {"age"=>22}
# person.serializable_hash(methods: :capitalized_name)
# # => {"name"=>"bob", "age"=>22, "capitalized_name"=>"Bob"}
diff --git a/activemodel/lib/active_model/validator.rb b/activemodel/lib/active_model/validator.rb
index 629b157fed..ff3dfa01c8 100644
--- a/activemodel/lib/active_model/validator.rb
+++ b/activemodel/lib/active_model/validator.rb
@@ -109,8 +109,8 @@ module ActiveModel
# Return the kind for this validator.
#
- # PresenceValidator.new.kind # => :presence
- # UniquenessValidator.new.kind # => :uniqueness 
+ # PresenceValidator.new.kind # => :presence
+ # UniquenessValidator.new.kind # => :uniqueness
def kind
self.class.kind
end
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md
index aaaf27a211..0a2e7a127c 100644
--- a/activerecord/CHANGELOG.md
+++ b/activerecord/CHANGELOG.md
@@ -1,5 +1,65 @@
## Rails 4.0.0 (unreleased) ##
+* Allow `Relation#where` with no arguments to be chained with new `not` query method.
+
+ Example:
+
+ Developer.where.not(name: 'Aaron')
+
+ *Akira Matsuda*
+
+* Unscope `update_column(s)` query to ignore default scope.
+
+ When applying `default_scope` to a class with a where clause, using
+ `update_column(s)` could generate a query that would not properly update
+ the record due to the where clause from the `default_scope` being applied
+ to the update query.
+
+ class User < ActiveRecord::Base
+ default_scope where(active: true)
+ end
+
+ user = User.first
+ user.active = false
+ user.save!
+
+ user.update_column(:active, true) # => false
+
+ In this situation we want to skip the default_scope clause and just
+ update the record based on the primary key. With this change:
+
+ user.update_column(:active, true) # => true
+
+ Fixes #8436.
+
+ *Carlos Antonio da Silva*
+
+* SQLite adapter no longer corrupts binary data if the data contains `%00`.
+
+ *Chris Feist*
+
+* Add migration history to `schema.rb` dump. Loading `schema.rb` with full migration
+ history restores the exact list of migrations that created that schema (including names
+ and fingerprints). This avoids possible mistakes caused by assuming all migrations with
+ a lower version have been run when loading `schema.rb`. Old `schema.rb` files without
+ migration history but with the `:version` setting still work as before.
+
+ *Josh Susser*
+
+* Add metadata columns to `schema_migrations` table. New columns are:
+
+ * `migrated_at`: timestamp
+ * `fingerprint`: md5 hash of migration source
+ * `name`: filename minus version and extension
+
+ *Josh Susser*
+
+* Fix performance problem with `primary_key` method in PostgreSQL adapter when having many schemas.
+ Uses `pg_constraint` table instead of `pg_depend` table which has many records in general.
+ Fix #8414
+
+ *kennyj*
+
* Do not instantiate intermediate Active Record objects when eager loading.
These records caused `after_find` to run more than expected.
Fix #3313
@@ -7,8 +67,8 @@
*Yves Senn*
* Add STI support to init and building associations.
- Allows you to do BaseClass.new(:type => "SubClass") as well as
- parent.children.build(:type => "SubClass") or parent.build_child
+ Allows you to do `BaseClass.new(:type => "SubClass")` as well as
+ `parent.children.build(:type => "SubClass")` or `parent.build_child`
to initialize an STI subclass. Ensures that the class name is a
valid class and that it is in the ancestors of the super class
that the association is expecting.
@@ -782,7 +842,7 @@
end
person.pets.delete("1") # => [#<Pet id: 1>]
- person.pets.delete(2, 3) # => [#<Pet id: 2>, #<Pet id: 3>]
+ person.pets.delete(2, 3) # => [#<Pet id: 2>, #<Pet id: 3>]
*Francesco Rodriguez*
@@ -1053,11 +1113,11 @@
Note that you do not need to explicitly specify references in the
following cases, as they can be automatically inferred:
- Post.where(comments: { name: 'foo' })
- Post.where('comments.name' => 'foo')
- Post.order('comments.name')
+ Post.includes(:comments).where(comments: { name: 'foo' })
+ Post.includes(:comments).where('comments.name' => 'foo')
+ Post.includes(:comments).order('comments.name')
- You also do not need to worry about this unless you are doing eager
+ You do not need to worry about this unless you are doing eager
loading. Basically, don't worry unless you see a deprecation warning
or (in future releases) an SQL error due to a missing JOIN.
diff --git a/activerecord/lib/active_record/associations/collection_proxy.rb b/activerecord/lib/active_record/associations/collection_proxy.rb
index 7f9628499c..7c43e37cf2 100644
--- a/activerecord/lib/active_record/associations/collection_proxy.rb
+++ b/activerecord/lib/active_record/associations/collection_proxy.rb
@@ -101,7 +101,7 @@ module ActiveRecord
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
- # person.pets.select(:name) { |pet| pet.name =~ /oo/ }
+ # person.pets.select(:name) { |pet| pet.name =~ /oo/ }
# # => [
# # #<Pet id: 2, name: "Spook">,
# # #<Pet id: 3, name: "Choo-Choo">
@@ -824,7 +824,7 @@ module ActiveRecord
#
# person.pets # => [#<Pet id: 20, name: "Snoop">]
#
- # person.pets.include?(Pet.find(20)) # => true
+ # person.pets.include?(Pet.find(20)) # => true
# person.pets.include?(Pet.find(21)) # => false
def include?(record)
@association.include?(record)
@@ -971,7 +971,7 @@ module ActiveRecord
# person.pets.reload # fetches pets from the database
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
#
- # person.pets(true)  # fetches pets from the database
+ # person.pets(true) # fetches pets from the database
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
def reload
proxy_association.reload
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 7ec6abbc45..73012834c9 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
@@ -190,16 +190,16 @@ module ActiveRecord
#
# What can be written like this with the regular calls to column:
#
- # create_table "products", force: true do |t|
- # t.column "shop_id", :integer
- # t.column "creator_id", :integer
- # t.column "name", :string, default: "Untitled"
- # t.column "value", :string, default: "Untitled"
- # t.column "created_at", :datetime
- # t.column "updated_at", :datetime
+ # create_table :products do |t|
+ # t.column :shop_id, :integer
+ # t.column :creator_id, :integer
+ # t.column :name, :string, default: "Untitled"
+ # t.column :value, :string, default: "Untitled"
+ # t.column :created_at, :datetime
+ # t.column :updated_at, :datetime
# end
#
- # Can also be written as follows using the short-hand:
+ # can also be written as follows using the short-hand:
#
# create_table :products do |t|
# t.integer :shop_id, :creator_id
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 f1e42dfbbe..1586e84a25 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
@@ -490,8 +490,8 @@ module ActiveRecord
sm_table = ActiveRecord::Migrator.schema_migrations_table_name
ActiveRecord::SchemaMigration.order('version').map { |sm|
- "INSERT INTO #{sm_table} (version) VALUES ('#{sm.version}');"
- }.join "\n\n"
+ "INSERT INTO #{sm_table} (version, migrated_at, fingerprint, name) VALUES ('#{sm.version}',CURRENT_TIMESTAMP,'#{sm.fingerprint}','#{sm.name}');"
+ }.join("\n\n")
end
# Should not be called normally, but this operation is non-destructive.
@@ -512,7 +512,7 @@ module ActiveRecord
end
unless migrated.include?(version)
- execute "INSERT INTO #{sm_table} (version) VALUES ('#{version}')"
+ ActiveRecord::SchemaMigration.create!(:version => version, :migrated_at => Time.now)
end
inserted = Set.new
@@ -520,7 +520,7 @@ module ActiveRecord
if inserted.include?(v)
raise "Duplicate migration #{v}. Please renumber your migrations to resolve the conflict."
elsif v < version
- execute "INSERT INTO #{sm_table} (version) VALUES ('#{v}')"
+ ActiveRecord::SchemaMigration.create!(:version => v, :migrated_at => Time.now)
inserted << v
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
index 9f7086cd07..18bf14d1fb 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
@@ -305,12 +305,11 @@ module ActiveRecord
# Returns just a table's primary key
def primary_key(table)
row = exec_query(<<-end_sql, 'SCHEMA').rows.first
- SELECT DISTINCT(attr.attname)
+ SELECT attr.attname
FROM pg_attribute attr
- INNER JOIN pg_depend dep ON attr.attrelid = dep.refobjid AND attr.attnum = dep.refobjsubid
INNER JOIN pg_constraint cons ON attr.attrelid = cons.conrelid AND attr.attnum = cons.conkey[1]
WHERE cons.contype = 'p'
- AND dep.refobjid = '#{quote_table_name(table)}'::regclass
+ AND cons.conrelid = '#{quote_table_name(table)}'::regclass
end_sql
row && row.first
diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb
index 22347fcaef..4ce276d4bf 100644
--- a/activerecord/lib/active_record/migration.rb
+++ b/activerecord/lib/active_record/migration.rb
@@ -1,5 +1,6 @@
require "active_support/core_ext/class/attribute_accessors"
require 'set'
+require 'digest/md5'
module ActiveRecord
# Exception that can be raised to stop migrations from going backwards.
@@ -554,6 +555,10 @@ module ActiveRecord
delegate :migrate, :announce, :write, :to => :migration
+ def fingerprint
+ @fingerprint ||= Digest::MD5.hexdigest(File.read(filename))
+ end
+
private
def migration
@@ -724,7 +729,7 @@ module ActiveRecord
raise UnknownMigrationVersionError.new(@target_version) if target.nil?
unless (up? && migrated.include?(target.version.to_i)) || (down? && !migrated.include?(target.version.to_i))
target.migrate(@direction)
- record_version_state_after_migrating(target.version)
+ record_version_state_after_migrating(target)
end
end
@@ -747,7 +752,7 @@ module ActiveRecord
begin
ddl_transaction do
migration.migrate(@direction)
- record_version_state_after_migrating(migration.version)
+ record_version_state_after_migrating(migration)
end
rescue => e
canceled_msg = Base.connection.supports_ddl_transactions? ? "this and " : ""
@@ -805,13 +810,18 @@ module ActiveRecord
raise DuplicateMigrationVersionError.new(version) if version
end
- def record_version_state_after_migrating(version)
+ def record_version_state_after_migrating(target)
if down?
- migrated.delete(version)
- ActiveRecord::SchemaMigration.where(:version => version.to_s).delete_all
+ migrated.delete(target.version)
+ ActiveRecord::SchemaMigration.where(:version => target.version.to_s).delete_all
else
- migrated << version
- ActiveRecord::SchemaMigration.create!(:version => version.to_s)
+ migrated << target.version
+ ActiveRecord::SchemaMigration.create!(
+ :version => target.version.to_s,
+ :migrated_at => Time.now,
+ :fingerprint => target.fingerprint,
+ :name => File.basename(target.filename,'.rb').gsub(/^\d+_/,'')
+ )
end
end
diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb
index 94c109e72b..4d1a9c94b7 100644
--- a/activerecord/lib/active_record/persistence.rb
+++ b/activerecord/lib/active_record/persistence.rb
@@ -259,7 +259,7 @@ module ActiveRecord
verify_readonly_attribute(key.to_s)
end
- updated_count = self.class.where(self.class.primary_key => id).update_all(attributes)
+ updated_count = self.class.unscoped.where(self.class.primary_key => id).update_all(attributes)
attributes.each do |k, v|
raw_write_attribute(k, v)
diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb
index a480ddec9e..46c0d6206f 100644
--- a/activerecord/lib/active_record/relation/query_methods.rb
+++ b/activerecord/lib/active_record/relation/query_methods.rb
@@ -4,6 +4,51 @@ module ActiveRecord
module QueryMethods
extend ActiveSupport::Concern
+ # WhereChain objects act as placeholder for queries in which #where does not have any parameter.
+ # In this case, #where must be chained with either #not, #like, or #not_like to return a new relation.
+ class WhereChain
+ def initialize(scope)
+ @scope = scope
+ end
+
+ # Returns a new relation expressing WHERE + NOT condition
+ # according to the conditions in the arguments.
+ #
+ # #not accepts conditions in one of these formats: String, Array, Hash.
+ # See #where for more details on each format.
+ #
+ # User.where.not("name = 'Jon'")
+ # # SELECT * FROM users WHERE NOT (name = 'Jon')
+ #
+ # User.where.not(["name = ?", "Jon"])
+ # # SELECT * FROM users WHERE NOT (name = 'Jon')
+ #
+ # User.where.not(name: "Jon")
+ # # SELECT * FROM users WHERE name != 'Jon'
+ #
+ # User.where.not(name: nil)
+ # # SELECT * FROM users WHERE name IS NOT NULL
+ #
+ # User.where.not(name: %w(Ko1 Nobu))
+ # # SELECT * FROM users WHERE name NOT IN ('Ko1', 'Nobu')
+ def not(opts, *rest)
+ where_value = @scope.send(:build_where, opts, rest).map do |rel|
+ case rel
+ when Arel::Nodes::In
+ Arel::Nodes::NotIn.new(rel.left, rel.right)
+ when Arel::Nodes::Equality
+ Arel::Nodes::NotEqual.new(rel.left, rel.right)
+ when String
+ Arel::Nodes::Not.new(Arel::Nodes::SqlLiteral.new(rel))
+ else
+ Arel::Nodes::Not.new(rel)
+ end
+ end
+ @scope.where_values += where_value
+ @scope
+ end
+ end
+
Relation::MULTI_VALUE_METHODS.each do |name|
class_eval <<-CODE, __FILE__, __LINE__ + 1
def #{name}_values # def select_values
@@ -370,18 +415,41 @@ module ActiveRecord
# User.joins(:posts).where({ "posts.published" => true })
# User.joins(:posts).where({ posts: { published: true } })
#
- # === empty condition
+ # === no argument
+ #
+ # If no argument is passed, #where returns a new instance of WhereChain, that
+ # can be chained with #not to return a new relation that negates the where clause.
+ #
+ # User.where.not(name: "Jon")
+ # # SELECT * FROM users WHERE name != 'Jon'
+ #
+ # See WhereChain for more details on #not.
#
- # If the condition returns true for blank?, then where is a no-op and returns the current relation.
- def where(opts, *rest)
- opts.blank? ? self : spawn.where!(opts, *rest)
+ # === blank condition
+ #
+ # If the condition is any blank-ish object, then #where is a no-op and returns
+ # the current relation.
+ def where(opts = :chain, *rest)
+ if opts == :chain
+ WhereChain.new(spawn)
+ elsif opts.blank?
+ self
+ else
+ spawn.where!(opts, *rest)
+ end
end
- def where!(opts, *rest) # :nodoc:
- references!(PredicateBuilder.references(opts)) if Hash === opts
+ # #where! is identical to #where, except that instead of returning a new relation, it adds
+ # the condition to the existing relation.
+ def where!(opts = :chain, *rest) # :nodoc:
+ if opts == :chain
+ WhereChain.new(self)
+ else
+ references!(PredicateBuilder.references(opts)) if Hash === opts
- self.where_values += build_where(opts, rest)
- self
+ self.where_values += build_where(opts, rest)
+ self
+ end
end
# Allows to specify a HAVING clause. Note that you can't use HAVING
diff --git a/activerecord/lib/active_record/schema.rb b/activerecord/lib/active_record/schema.rb
index 3259dbbd80..44b7eb424b 100644
--- a/activerecord/lib/active_record/schema.rb
+++ b/activerecord/lib/active_record/schema.rb
@@ -39,27 +39,45 @@ module ActiveRecord
end
def define(info, &block) # :nodoc:
+ @using_deprecated_version_setting = info[:version].present?
+ SchemaMigration.drop_table
+ initialize_schema_migrations_table
+
instance_eval(&block)
- unless info[:version].blank?
- initialize_schema_migrations_table
- assume_migrated_upto_version(info[:version], migrations_paths)
- end
+ # handle files from pre-4.0 that used :version option instead of dumping migration table
+ assume_migrated_upto_version(info[:version], migrations_paths) if @using_deprecated_version_setting
end
# Eval the given block. All methods available to the current connection
# adapter are available within the block, so you can easily use the
# database definition DSL to build up your schema (+create_table+,
# +add_index+, etc.).
- #
- # The +info+ hash is optional, and if given is used to define metadata
- # about the current schema (currently, only the schema's version):
- #
- # ActiveRecord::Schema.define(version: 20380119000001) do
- # ...
- # end
def self.define(info={}, &block)
new.define(info, &block)
end
+
+ # Create schema migration history. Include migration statements in a block to this method.
+ #
+ # migrations do
+ # migration 20121128235959, "44f1397e3b92442ca7488a029068a5ad", "add_horn_color_to_unicorns"
+ # migration 20121129235959, "4a1eb3965d94406b00002b370854eae8", "add_magic_power_to_unicorns"
+ # end
+ def migrations
+ raise(ArgumentError, "Can't set migrations while using :version option") if @using_deprecated_version_setting
+ yield
+ end
+
+ # Add a migration to the ActiveRecord::SchemaMigration table.
+ #
+ # The +version+ argument is an integer.
+ # The +fingerprint+ and +name+ arguments are required but may be empty strings.
+ # The migration's +migrated_at+ attribute is set to the current time,
+ # instead of being set explicitly as an argument to the method.
+ #
+ # migration 20121129235959, "4a1eb3965d94406b00002b370854eae8", "add_magic_power_to_unicorns"
+ def migration(version, fingerprint, name)
+ SchemaMigration.create!(version: version, migrated_at: Time.now, fingerprint: fingerprint, name: name)
+ end
end
end
diff --git a/activerecord/lib/active_record/schema_dumper.rb b/activerecord/lib/active_record/schema_dumper.rb
index 36bde44e7c..194a77ca16 100644
--- a/activerecord/lib/active_record/schema_dumper.rb
+++ b/activerecord/lib/active_record/schema_dumper.rb
@@ -24,6 +24,7 @@ module ActiveRecord
def dump(stream)
header(stream)
+ migrations(stream)
tables(stream)
trailer(stream)
stream
@@ -38,13 +39,11 @@ module ActiveRecord
end
def header(stream)
- define_params = @version ? "version: #{@version}" : ""
-
if stream.respond_to?(:external_encoding) && stream.external_encoding
stream.puts "# encoding: #{stream.external_encoding.name}"
end
- stream.puts <<HEADER
+ header_text = <<HEADER_RUBY
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
@@ -57,15 +56,27 @@ module ActiveRecord
#
# It's strongly recommended that you check this file into your version control system.
-ActiveRecord::Schema.define(#{define_params}) do
+ActiveRecord::Schema.define do
-HEADER
+HEADER_RUBY
+ stream.puts header_text
end
def trailer(stream)
stream.puts "end"
end
+ def migrations(stream)
+ all_migrations = ActiveRecord::SchemaMigration.all.to_a
+ if all_migrations.any?
+ stream.puts(" migrations do")
+ all_migrations.each do |migration|
+ stream.puts(migration.schema_line(" "))
+ end
+ stream.puts(" end\n\n")
+ end
+ end
+
def tables(stream)
@connection.tables.sort.each do |tbl|
next if ['schema_migrations', ignore_tables].flatten.any? do |ignored|
diff --git a/activerecord/lib/active_record/schema_migration.rb b/activerecord/lib/active_record/schema_migration.rb
index 9830abe7d8..6c3cd5b6ba 100644
--- a/activerecord/lib/active_record/schema_migration.rb
+++ b/activerecord/lib/active_record/schema_migration.rb
@@ -14,17 +14,38 @@ module ActiveRecord
end
def self.create_table
- unless connection.table_exists?(table_name)
+ if connection.table_exists?(table_name)
+ cols = connection.columns(table_name).collect { |col| col.name }
+ unless cols.include?("migrated_at")
+ connection.add_column(table_name, "migrated_at", :datetime)
+ q_table_name = connection.quote_table_name(table_name)
+ q_timestamp = connection.quoted_date(Time.now)
+ connection.update("UPDATE #{q_table_name} SET migrated_at = '#{q_timestamp}' WHERE migrated_at IS NULL")
+ connection.change_column(table_name, "migrated_at", :datetime, :null => false)
+ end
+ unless cols.include?("fingerprint")
+ connection.add_column(table_name, "fingerprint", :string, :limit => 32)
+ end
+ unless cols.include?("name")
+ connection.add_column(table_name, "name", :string)
+ end
+ else
connection.create_table(table_name, :id => false) do |t|
t.column :version, :string, :null => false
+ t.column :migrated_at, :datetime, :null => false
+ t.column :fingerprint, :string, :limit => 32
+ t.column :name, :string
end
- connection.add_index table_name, :version, :unique => true, :name => index_name
+ connection.add_index(table_name, "version", :unique => true, :name => index_name)
end
+ reset_column_information
end
def self.drop_table
if connection.table_exists?(table_name)
- connection.remove_index table_name, :name => index_name
+ if connection.index_exists?(table_name, "version", :unique => true, :name => index_name)
+ connection.remove_index(table_name, :name => index_name)
+ end
connection.drop_table(table_name)
end
end
@@ -32,5 +53,17 @@ module ActiveRecord
def version
super.to_i
end
+
+ # Construct ruby source to include in schema.rb dump for this migration.
+ # Pass a string of spaces as +indent+ to allow calling code to control how deeply indented the line is.
+ # The generated line includes the migration version, fingerprint, and name. Either fingerprint or name
+ # can be an empty string.
+ #
+ # Example output:
+ #
+ # migration 20121129235959, "ee4be703f9e6e2fc0f4baddebe6eb8f7", "add_magic_power_to_unicorns"
+ def schema_line(indent)
+ %Q(#{indent}migration %s, "%s", "%s") % [version, fingerprint, name]
+ end
end
end
diff --git a/activerecord/lib/active_record/scoping/named.rb b/activerecord/lib/active_record/scoping/named.rb
index fb5f5b5be0..8b7eda6eee 100644
--- a/activerecord/lib/active_record/scoping/named.rb
+++ b/activerecord/lib/active_record/scoping/named.rb
@@ -116,7 +116,7 @@ module ActiveRecord
# Scopes can also be used while creating/building a record.
#
# class Article < ActiveRecord::Base
- # scope :published, -> { where(published: true) }
+ # scope :published, -> { where(published: true) }
# end
#
# Article.published.new.published # => true
@@ -126,7 +126,7 @@ module ActiveRecord
# on scopes. Assuming the following setup:
#
# class Article < ActiveRecord::Base
- # scope :published, -> { where(published: true) }
+ # scope :published, -> { where(published: true) }
# scope :featured, -> { where(featured: true) }
#
# def self.latest_article
diff --git a/activerecord/test/cases/ar_schema_test.rb b/activerecord/test/cases/ar_schema_test.rb
index b2eac0349b..bd47ba8741 100644
--- a/activerecord/test/cases/ar_schema_test.rb
+++ b/activerecord/test/cases/ar_schema_test.rb
@@ -46,4 +46,55 @@ if ActiveRecord::Base.connection.supports_migrations?
end
end
+ class ActiveRecordSchemaMigrationsTest < ActiveRecordSchemaTest
+ def setup
+ super
+ ActiveRecord::SchemaMigration.delete_all
+ end
+
+ def test_migration_adds_row_to_migrations_table
+ schema = ActiveRecord::Schema.new
+ schema.migration(1001, "", "")
+ schema.migration(1002, "123456789012345678901234567890ab", "add_magic_power_to_unicorns")
+
+ migrations = ActiveRecord::SchemaMigration.all.to_a
+ assert_equal 2, migrations.length
+
+ assert_equal 1001, migrations[0].version
+ assert_match %r{^2\d\d\d-}, migrations[0].migrated_at.to_s(:db)
+ assert_equal "", migrations[0].fingerprint
+ assert_equal "", migrations[0].name
+
+ assert_equal 1002, migrations[1].version
+ assert_match %r{^2\d\d\d-}, migrations[1].migrated_at.to_s(:db)
+ assert_equal "123456789012345678901234567890ab", migrations[1].fingerprint
+ assert_equal "add_magic_power_to_unicorns", migrations[1].name
+ end
+
+ def test_define_clears_schema_migrations
+ assert_nothing_raised do
+ ActiveRecord::Schema.define do
+ migrations do
+ migration(123001, "", "")
+ end
+ end
+ ActiveRecord::Schema.define do
+ migrations do
+ migration(123001, "", "")
+ end
+ end
+ end
+ end
+
+ def test_define_raises_if_both_version_and_explicit_migrations
+ assert_raise(ArgumentError) do
+ ActiveRecord::Schema.define(version: 123001) do
+ migrations do
+ migration(123001, "", "")
+ end
+ end
+ end
+ end
+ end
+
end
diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb
index d25aca760f..7e6c7d5862 100644
--- a/activerecord/test/cases/associations/has_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -298,12 +298,6 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal 2, Firm.order(:id).find{|f| f.id > 0}.clients.length
end
- def test_find_with_blank_conditions
- [[], {}, nil, ""].each do |blank|
- assert_equal 2, Firm.all.merge!(:order => "id").first.clients.where(blank).to_a.size
- end
- end
-
def test_find_many_with_merged_options
assert_equal 1, companies(:first_firm).limited_clients.size
assert_equal 1, companies(:first_firm).limited_clients.to_a.size
diff --git a/activerecord/test/cases/migration/logger_test.rb b/activerecord/test/cases/migration/logger_test.rb
index ee0c20747e..c2fdc50e52 100644
--- a/activerecord/test/cases/migration/logger_test.rb
+++ b/activerecord/test/cases/migration/logger_test.rb
@@ -10,6 +10,8 @@ module ActiveRecord
def migrate direction
# do nothing
end
+ def filename; "anon.rb"; end
+ def fingerprint; "123456789012345678901234567890ab"; end
end
def setup
diff --git a/activerecord/test/cases/migration/table_and_index_test.rb b/activerecord/test/cases/migration/table_and_index_test.rb
deleted file mode 100644
index 8fd770abd1..0000000000
--- a/activerecord/test/cases/migration/table_and_index_test.rb
+++ /dev/null
@@ -1,24 +0,0 @@
-require "cases/helper"
-
-module ActiveRecord
- class Migration
- class TableAndIndexTest < ActiveRecord::TestCase
- def test_add_schema_info_respects_prefix_and_suffix
- conn = ActiveRecord::Base.connection
-
- conn.drop_table(ActiveRecord::Migrator.schema_migrations_table_name) if conn.table_exists?(ActiveRecord::Migrator.schema_migrations_table_name)
- # Use shorter prefix and suffix as in Oracle database identifier cannot be larger than 30 characters
- ActiveRecord::Base.table_name_prefix = 'p_'
- ActiveRecord::Base.table_name_suffix = '_s'
- conn.drop_table(ActiveRecord::Migrator.schema_migrations_table_name) if conn.table_exists?(ActiveRecord::Migrator.schema_migrations_table_name)
-
- conn.initialize_schema_migrations_table
-
- assert_equal "p_unique_schema_migrations_s", conn.indexes(ActiveRecord::Migrator.schema_migrations_table_name)[0][:name]
- ensure
- ActiveRecord::Base.table_name_prefix = ""
- ActiveRecord::Base.table_name_suffix = ""
- end
- end
- end
-end
diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb
index c155f29973..3a861d887f 100644
--- a/activerecord/test/cases/migration_test.rb
+++ b/activerecord/test/cases/migration_test.rb
@@ -59,12 +59,21 @@ class MigrationTest < ActiveRecord::TestCase
def test_migrator_versions
migrations_path = MIGRATIONS_ROOT + "/valid"
ActiveRecord::Migrator.migrations_paths = migrations_path
+ m0_path = File.join(migrations_path, "1_valid_people_have_last_names.rb")
+ m0_fingerprint = Digest::MD5.hexdigest(File.read(m0_path))
ActiveRecord::Migrator.up(migrations_path)
assert_equal 3, ActiveRecord::Migrator.current_version
assert_equal 3, ActiveRecord::Migrator.last_version
assert_equal false, ActiveRecord::Migrator.needs_migration?
+ rows = connection.select_all("SELECT * FROM #{connection.quote_table_name(ActiveRecord::Migrator.schema_migrations_table_name)}")
+ assert_equal m0_fingerprint, rows[0]["fingerprint"]
+ assert_equal "valid_people_have_last_names", rows[0]["name"]
+ rows.each do |row|
+ assert_match(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/, row["migrated_at"].to_s, "missing migrated_at") # sometimes a String, sometimes a Time
+ end
+
ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid")
assert_equal 0, ActiveRecord::Migrator.current_version
assert_equal 3, ActiveRecord::Migrator.last_version
@@ -337,7 +346,7 @@ class MigrationTest < ActiveRecord::TestCase
assert_nothing_raised {
Person.connection.create_table :binary_testings do |t|
- t.column "data", :binary, :null => false
+ t.column :data, :binary, :null => false
end
}
diff --git a/activerecord/test/cases/migrator_test.rb b/activerecord/test/cases/migrator_test.rb
index 1e16addcf3..0f0384382f 100644
--- a/activerecord/test/cases/migrator_test.rb
+++ b/activerecord/test/cases/migrator_test.rb
@@ -18,6 +18,9 @@ module ActiveRecord
def up; @went_up = true; end
def down; @went_down = true; end
+ # also used in place of a MigrationProxy
+ def filename; "anon.rb"; end
+ def fingerprint; "123456789012345678901234567890ab"; end
end
def setup
@@ -102,7 +105,7 @@ module ActiveRecord
end
def test_finds_pending_migrations
- ActiveRecord::SchemaMigration.create!(:version => '1')
+ ActiveRecord::SchemaMigration.create!(:version => '1', :name => "anon", :migrated_at => Time.now)
migration_list = [ Migration.new('foo', 1), Migration.new('bar', 3) ]
migrations = ActiveRecord::Migrator.new(:up, migration_list).pending_migrations
@@ -152,7 +155,7 @@ module ActiveRecord
end
def test_current_version
- ActiveRecord::SchemaMigration.create!(:version => '1000')
+ ActiveRecord::SchemaMigration.create!(:version => '1000', :name => "anon", :migrated_at => Time.now)
assert_equal 1000, ActiveRecord::Migrator.current_version
end
@@ -320,7 +323,7 @@ module ActiveRecord
def test_only_loads_pending_migrations
# migrate up to 1
- ActiveRecord::SchemaMigration.create!(:version => '1')
+ ActiveRecord::SchemaMigration.create!(:version => '1', :name => "anon", :migrated_at => Time.now)
calls, migrator = migrator_class(3)
migrator.migrate("valid", nil)
diff --git a/activerecord/test/cases/persistence_test.rb b/activerecord/test/cases/persistence_test.rb
index 02034c87b4..9e0423ab52 100644
--- a/activerecord/test/cases/persistence_test.rb
+++ b/activerecord/test/cases/persistence_test.rb
@@ -512,6 +512,14 @@ class PersistencesTest < ActiveRecord::TestCase
assert_equal 'super_title', t.title
end
+ def test_update_column_with_default_scope
+ developer = DeveloperCalledDavid.first
+ developer.name = 'John'
+ developer.save!
+
+ assert developer.update_column(:name, 'Will'), 'did not update record due to default scope'
+ end
+
def test_update_columns
topic = Topic.find(1)
topic.update_columns({ "approved" => true, title: "Sebastian Topic" })
@@ -616,6 +624,14 @@ class PersistencesTest < ActiveRecord::TestCase
assert_equal true, topic.update_columns(title: "New title")
end
+ def test_update_columns_with_default_scope
+ developer = DeveloperCalledDavid.first
+ developer.name = 'John'
+ developer.save!
+
+ assert developer.update_columns(name: 'Will'), 'did not update record due to default scope'
+ end
+
def test_update_attributes
topic = Topic.find(1)
assert !topic.approved?
diff --git a/activerecord/test/cases/relation/where_chain_test.rb b/activerecord/test/cases/relation/where_chain_test.rb
new file mode 100644
index 0000000000..8ce44636b4
--- /dev/null
+++ b/activerecord/test/cases/relation/where_chain_test.rb
@@ -0,0 +1,75 @@
+require 'cases/helper'
+require 'models/post'
+require 'models/comment'
+
+module ActiveRecord
+ class WhereChainTest < ActiveRecord::TestCase
+ fixtures :posts
+
+ def test_not_eq
+ expected = Arel::Nodes::NotEqual.new(Post.arel_table[:title], 'hello')
+ relation = Post.where.not(title: 'hello')
+ assert_equal([expected], relation.where_values)
+ end
+
+ def test_not_null
+ expected = Arel::Nodes::NotEqual.new(Post.arel_table[:title], nil)
+ relation = Post.where.not(title: nil)
+ assert_equal([expected], relation.where_values)
+ end
+
+ def test_not_in
+ expected = Arel::Nodes::NotIn.new(Post.arel_table[:title], %w[hello goodbye])
+ relation = Post.where.not(title: %w[hello goodbye])
+ assert_equal([expected], relation.where_values)
+ end
+
+ def test_association_not_eq
+ expected = Arel::Nodes::NotEqual.new(Comment.arel_table[:title], 'hello')
+ relation = Post.joins(:comments).where.not(comments: {title: 'hello'})
+ assert_equal(expected.to_sql, relation.where_values.first.to_sql)
+ end
+
+ def test_not_eq_with_preceding_where
+ relation = Post.where(title: 'hello').where.not(title: 'world')
+
+ expected = Arel::Nodes::Equality.new(Post.arel_table[:title], 'hello')
+ assert_equal(expected, relation.where_values.first)
+
+ expected = Arel::Nodes::NotEqual.new(Post.arel_table[:title], 'world')
+ assert_equal(expected, relation.where_values.last)
+ end
+
+ def test_not_eq_with_succeeding_where
+ relation = Post.where.not(title: 'hello').where(title: 'world')
+
+ expected = Arel::Nodes::NotEqual.new(Post.arel_table[:title], 'hello')
+ assert_equal(expected, relation.where_values.first)
+
+ expected = Arel::Nodes::Equality.new(Post.arel_table[:title], 'world')
+ assert_equal(expected, relation.where_values.last)
+ end
+
+ def test_not_eq_with_string_parameter
+ expected = Arel::Nodes::Not.new("title = 'hello'")
+ relation = Post.where.not("title = 'hello'")
+ assert_equal([expected], relation.where_values)
+ end
+
+ def test_not_eq_with_array_parameter
+ expected = Arel::Nodes::Not.new("title = 'hello'")
+ relation = Post.where.not(['title = ?', 'hello'])
+ assert_equal([expected], relation.where_values)
+ end
+
+ def test_chaining_multiple
+ relation = Post.where.not(author_id: [1, 2]).where.not(title: 'ruby on rails')
+
+ expected = Arel::Nodes::NotIn.new(Post.arel_table[:author_id], [1, 2])
+ assert_equal(expected, relation.where_values[0])
+
+ expected = Arel::Nodes::NotEqual.new(Post.arel_table[:title], 'ruby on rails')
+ assert_equal(expected, relation.where_values[1])
+ end
+ end
+end
diff --git a/activerecord/test/cases/relation/where_test.rb b/activerecord/test/cases/relation/where_test.rb
index 9c0b139dbf..297e865308 100644
--- a/activerecord/test/cases/relation/where_test.rb
+++ b/activerecord/test/cases/relation/where_test.rb
@@ -85,5 +85,11 @@ module ActiveRecord
def test_where_with_empty_hash_and_no_foreign_key
assert_equal 0, Edge.where(:sink => {}).count
end
+
+ def test_where_with_blank_conditions
+ [[], {}, nil, ""].each do |blank|
+ assert_equal 4, Edge.where(blank).order("sink_id").to_a.size
+ end
+ end
end
end
diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb
index 7ff0044bd4..264846eedb 100644
--- a/activerecord/test/cases/schema_dumper_test.rb
+++ b/activerecord/test/cases/schema_dumper_test.rb
@@ -1,6 +1,5 @@
require "cases/helper"
-
class SchemaDumperTest < ActiveRecord::TestCase
def setup
super
@@ -18,11 +17,15 @@ class SchemaDumperTest < ActiveRecord::TestCase
def test_dump_schema_information_outputs_lexically_ordered_versions
versions = %w{ 20100101010101 20100201010101 20100301010101 }
versions.reverse.each do |v|
- ActiveRecord::SchemaMigration.create!(:version => v)
+ ActiveRecord::SchemaMigration.create!(
+ :version => v, :migrated_at => Time.now,
+ :fingerprint => "123456789012345678901234567890ab", :name => "anon")
end
schema_info = ActiveRecord::Base.connection.dump_schema_information
assert_match(/20100201010101.*20100301010101/m, schema_info)
+ target_line = %q{INSERT INTO schema_migrations (version, migrated_at, fingerprint, name) VALUES ('20100101010101',CURRENT_TIMESTAMP,'123456789012345678901234567890ab','anon');}
+ assert_match target_line, schema_info
end
def test_magic_comment
@@ -36,6 +39,16 @@ class SchemaDumperTest < ActiveRecord::TestCase
assert_no_match %r{create_table "schema_migrations"}, output
end
+ def test_schema_dump_includes_migrations
+ ActiveRecord::SchemaMigration.delete_all
+ ActiveRecord::Migrator.migrate(MIGRATIONS_ROOT + "/always_safe")
+
+ output = standard_dump
+ assert_match %r{migrations do}, output, "Missing migrations block"
+ assert_match %r{migration 1001, "[0-9a-f]{32}", "always_safe"}, output, "Missing migration line"
+ assert_match %r{migration 1002, "[0-9a-f]{32}", "still_safe"}, output, "Missing migration line"
+ end
+
def test_schema_dump_excludes_sqlite_sequence
output = standard_dump
assert_no_match %r{create_table "sqlite_sequence"}, output
diff --git a/activerecord/test/cases/schema_migration_test.rb b/activerecord/test/cases/schema_migration_test.rb
new file mode 100644
index 0000000000..882067a7d4
--- /dev/null
+++ b/activerecord/test/cases/schema_migration_test.rb
@@ -0,0 +1,54 @@
+require "cases/helper"
+
+class SchemaMigrationTest < ActiveRecord::TestCase
+ def sm_table_name
+ ActiveRecord::SchemaMigration.table_name
+ end
+
+ def connection
+ ActiveRecord::Base.connection
+ end
+
+ def test_add_schema_info_respects_prefix_and_suffix
+ connection.drop_table(sm_table_name) if connection.table_exists?(sm_table_name)
+ # Use shorter prefix and suffix as in Oracle database identifier cannot be larger than 30 characters
+ ActiveRecord::Base.table_name_prefix = 'p_'
+ ActiveRecord::Base.table_name_suffix = '_s'
+ connection.drop_table(sm_table_name) if connection.table_exists?(sm_table_name)
+
+ ActiveRecord::SchemaMigration.create_table
+
+ assert_equal "p_unique_schema_migrations_s", connection.indexes(sm_table_name)[0][:name]
+ ensure
+ ActiveRecord::Base.table_name_prefix = ""
+ ActiveRecord::Base.table_name_suffix = ""
+ end
+
+ def test_add_metadata_columns_to_exisiting_schema_migrations
+ # creates the old table schema from pre-Rails4.0, so we can test adding to it below
+ if connection.table_exists?(sm_table_name)
+ connection.drop_table(sm_table_name)
+ end
+ connection.create_table(sm_table_name, :id => false) do |schema_migrations_table|
+ schema_migrations_table.column("version", :string, :null => false)
+ end
+
+ connection.insert "INSERT INTO #{connection.quote_table_name(sm_table_name)} (version) VALUES (100)"
+ connection.insert "INSERT INTO #{connection.quote_table_name(sm_table_name)} (version) VALUES (200)"
+
+ ActiveRecord::SchemaMigration.create_table
+
+ rows = connection.select_all("SELECT * FROM #{connection.quote_table_name(sm_table_name)}")
+ assert rows[0].has_key?("migrated_at"), "missing column `migrated_at`"
+ assert_match(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/, rows[0]["migrated_at"].to_s) # sometimes a String, sometimes a Time
+ assert rows[0].has_key?("fingerprint"), "missing column `fingerprint`"
+ assert rows[0].has_key?("name"), "missing column `name`"
+ end
+
+ def test_schema_migrations_columns
+ ActiveRecord::SchemaMigration.create_table
+
+ columns = connection.columns(sm_table_name).collect(&:name)
+ %w[version migrated_at fingerprint name].each { |col| assert columns.include?(col), "missing column `#{col}`" }
+ end
+end
diff --git a/activerecord/test/migrations/always_safe/1001_always_safe.rb b/activerecord/test/migrations/always_safe/1001_always_safe.rb
new file mode 100644
index 0000000000..454b972507
--- /dev/null
+++ b/activerecord/test/migrations/always_safe/1001_always_safe.rb
@@ -0,0 +1,5 @@
+class AlwaysSafe < ActiveRecord::Migration
+ def change
+ # do nothing to avoid side-effect conflicts from running multiple times
+ end
+end
diff --git a/activerecord/test/migrations/always_safe/1002_still_safe.rb b/activerecord/test/migrations/always_safe/1002_still_safe.rb
new file mode 100644
index 0000000000..7398ae27a2
--- /dev/null
+++ b/activerecord/test/migrations/always_safe/1002_still_safe.rb
@@ -0,0 +1,5 @@
+class StillSafe < ActiveRecord::Migration
+ def change
+ # do nothing to avoid side-effect conflicts from running multiple times
+ end
+end
diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md
index 450669968b..f5f2aa85ef 100644
--- a/activesupport/CHANGELOG.md
+++ b/activesupport/CHANGELOG.md
@@ -1,5 +1,11 @@
## Rails 4.0.0 (unreleased) ##
+* Deprecate `ActiveSupport::BasicObject` in favor of `ActiveSupport::ProxyObject`.
+ This class is used for proxy classes. It avoids confusion with Ruby's BasicObject
+ class.
+
+ *Francesco Rodriguez*
+
* Patched Marshal#load to work with constant autoloading.
Fixes autoloading with cache stores that relay on Marshal(MemCacheStore and FileStore). [fixes #8167]
diff --git a/activesupport/lib/active_support.rb b/activesupport/lib/active_support.rb
index 4e397ea110..b602686114 100644
--- a/activesupport/lib/active_support.rb
+++ b/activesupport/lib/active_support.rb
@@ -40,6 +40,7 @@ module ActiveSupport
eager_autoload do
autoload :BacktraceCleaner
autoload :BasicObject
+ autoload :ProxyObject
autoload :Benchmarkable
autoload :Cache
autoload :Callbacks
diff --git a/activesupport/lib/active_support/basic_object.rb b/activesupport/lib/active_support/basic_object.rb
index 6ccb0cd525..242b766b58 100644
--- a/activesupport/lib/active_support/basic_object.rb
+++ b/activesupport/lib/active_support/basic_object.rb
@@ -1,13 +1,7 @@
-module ActiveSupport
- # A class with no predefined methods that behaves similarly to Builder's
- # BlankSlate. Used for proxy classes.
- class BasicObject < ::BasicObject
- undef_method :==
- undef_method :equal?
+require 'active_support/deprecation'
- # Let ActiveSupport::BasicObject at least raise exceptions.
- def raise(*args)
- ::Object.send(:raise, *args)
- end
- end
+module ActiveSupport
+ # :nodoc:
+ # Deprecated in favor of ActiveSupport::ProxyObject
+ BasicObject = Deprecation::DeprecatedConstantProxy.new('ActiveSupport::BasicObject', 'ActiveSupport::ProxyObject')
end
diff --git a/activesupport/lib/active_support/cache.rb b/activesupport/lib/active_support/cache.rb
index 9a53870b3d..fdec2de1d5 100644
--- a/activesupport/lib/active_support/cache.rb
+++ b/activesupport/lib/active_support/cache.rb
@@ -582,7 +582,7 @@ module ActiveSupport
end
# Returns the size of the cached value. This could be less than
- # <tt>value.size</tt> if the data is compressed.
+ # <tt>value.size</tt> if the data is compressed.
def size
if defined?(@s)
@s
diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb
index 8199f431f1..3a8353857e 100644
--- a/activesupport/lib/active_support/callbacks.rb
+++ b/activesupport/lib/active_support/callbacks.rb
@@ -14,7 +14,7 @@ module ActiveSupport
# Mixing in this module allows you to define the events in the object's
# lifecycle that will support callbacks (via +ClassMethods.define_callbacks+),
# set the instance methods, procs, or callback objects to be called (via
- # +ClassMethods.set_callback+), and run the installed callbacks at the
+ # +ClassMethods.set_callback+), and run the installed callbacks at the
# appropriate times (via +run_callbacks+).
#
# Three kinds of callbacks are supported: before callbacks, run before a
@@ -382,7 +382,7 @@ module ActiveSupport
# set_callback :save, :before_meth
#
# The callback can specified as a symbol naming an instance method; as a
- # proc, lambda, or block; as a string to be instance evaluated; or as an
+ # proc, lambda, or block; as a string to be instance evaluated; or as an
# object that responds to a certain method determined by the <tt>:scope</tt>
# argument to +define_callback+.
#
diff --git a/activesupport/lib/active_support/configurable.rb b/activesupport/lib/active_support/configurable.rb
index 16d2a6a290..e0d39d509f 100644
--- a/activesupport/lib/active_support/configurable.rb
+++ b/activesupport/lib/active_support/configurable.rb
@@ -38,7 +38,7 @@ module ActiveSupport
end
# Allows you to add shortcut so that you don't have to refer to attribute
- # through config. Also look at the example for config to contrast.
+ # through config. Also look at the example for config to contrast.
#
# Defines both class and instance config accessors.
#
@@ -75,7 +75,7 @@ module ActiveSupport
# end
#
# User.allowed_access = false
- #  User.allowed_access # => false
+ # User.allowed_access # => false
#
# User.new.allowed_access = true # => NoMethodError
# User.new.allowed_access # => NoMethodError
@@ -88,7 +88,7 @@ module ActiveSupport
# end
#
# User.allowed_access = false
- #  User.allowed_access # => false
+ # User.allowed_access # => false
#
# User.new.allowed_access = true # => NoMethodError
# User.new.allowed_access # => NoMethodError
diff --git a/activesupport/lib/active_support/core_ext/array/conversions.rb b/activesupport/lib/active_support/core_ext/array/conversions.rb
index ff06436bd6..64e9945ef5 100644
--- a/activesupport/lib/active_support/core_ext/array/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/array/conversions.rb
@@ -26,7 +26,7 @@ class Array
#
# [].to_sentence # => ""
# ['one'].to_sentence # => "one"
- # ['one', 'two'].to_sentence # => "one and two"
+ # ['one', 'two'].to_sentence # => "one and two"
# ['one', 'two', 'three'].to_sentence # => "one, two, and three"
#
# ['one', 'two'].to_sentence(passing: 'invalid option')
@@ -41,7 +41,7 @@ class Array
# Examples using <tt>:locale</tt> option:
#
# # Given this locale dictionary:
- # # 
+ # #
# # es:
# # support:
# # array:
@@ -53,7 +53,7 @@ class Array
# # => "uno y dos"
#
# ['uno', 'dos', 'tres'].to_sentence(locale: :es)
- # # => "uno o dos o al menos tres"
+ # # => "uno o dos o al menos tres"
def to_sentence(options = {})
options.assert_valid_keys(:words_connector, :two_words_connector, :last_word_connector, :locale)
diff --git a/activesupport/lib/active_support/core_ext/class/attribute.rb b/activesupport/lib/active_support/core_ext/class/attribute.rb
index 1c3d26ead4..1504e18839 100644
--- a/activesupport/lib/active_support/core_ext/class/attribute.rb
+++ b/activesupport/lib/active_support/core_ext/class/attribute.rb
@@ -72,6 +72,9 @@ class Class
instance_reader = options.fetch(:instance_accessor, true) && options.fetch(:instance_reader, true)
instance_writer = options.fetch(:instance_accessor, true) && options.fetch(:instance_writer, true)
+ # We use class_eval here rather than define_method because class_attribute
+ # may be used in a performance sensitive context therefore the overhead that
+ # define_method introduces may become significant.
attrs.each do |name|
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def self.#{name}() nil end
diff --git a/activesupport/lib/active_support/core_ext/class/subclasses.rb b/activesupport/lib/active_support/core_ext/class/subclasses.rb
index c2e0ebb3d4..9a2dc6e7c5 100644
--- a/activesupport/lib/active_support/core_ext/class/subclasses.rb
+++ b/activesupport/lib/active_support/core_ext/class/subclasses.rb
@@ -31,7 +31,7 @@ class Class
# class Bar < Foo; end
# class Baz < Foo; end
#
- # Foo.subclasses # => [Baz, Bar]
+ # Foo.subclasses # => [Baz, Bar]
def subclasses
subclasses, chain = [], descendants
chain.each do |k|
diff --git a/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb b/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb
index 6c7e876fca..981e8436bf 100644
--- a/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb
+++ b/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb
@@ -16,7 +16,7 @@ class Hash
# converting to an <tt>ActiveSupport::HashWithIndifferentAccess</tt> would not be
# desirable.
#
- # b = { b: 1 }
+ # b = { b: 1 }
# { a: b }.with_indifferent_access['a'] # calls b.nested_under_indifferent_access
alias nested_under_indifferent_access with_indifferent_access
end
diff --git a/activesupport/lib/active_support/core_ext/hash/keys.rb b/activesupport/lib/active_support/core_ext/hash/keys.rb
index 13081995b0..b4c451ace4 100644
--- a/activesupport/lib/active_support/core_ext/hash/keys.rb
+++ b/activesupport/lib/active_support/core_ext/hash/keys.rb
@@ -24,7 +24,7 @@ class Hash
# Return a new hash with all keys converted to strings.
#
- # hash = { name: 'Rob', age: '28' }
+ # hash = { name: 'Rob', age: '28' }
#
# hash.stringify_keys
# #=> { "name" => "Rob", "age" => "28" }
@@ -44,7 +44,7 @@ class Hash
# hash = { 'name' => 'Rob', 'age' => '28' }
#
# hash.symbolize_keys
- # #=> { name: "Rob", age: "28" }
+ # #=> { name: "Rob", age: "28" }
def symbolize_keys
transform_keys{ |key| key.to_sym rescue key }
end
@@ -102,7 +102,7 @@ class Hash
# This includes the keys from the root hash and from all
# nested hashes.
#
- # hash = { person: { name: 'Rob', age: '28' } }
+ # hash = { person: { name: 'Rob', age: '28' } }
#
# hash.deep_stringify_keys
# # => { "person" => { "name" => "Rob", "age" => "28" } }
@@ -121,10 +121,10 @@ class Hash
# they respond to +to_sym+. This includes the keys from the root hash
# and from all nested hashes.
#
- # hash = { 'person' => { 'name' => 'Rob', 'age' => '28' } }
+ # hash = { 'person' => { 'name' => 'Rob', 'age' => '28' } }
#
# hash.deep_symbolize_keys
- # # => { person: { name: "Rob", age: "28" } }
+ # # => { person: { name: "Rob", age: "28" } }
def deep_symbolize_keys
deep_transform_keys{ |key| key.to_sym rescue key }
end
diff --git a/activesupport/lib/active_support/core_ext/object/deep_dup.rb b/activesupport/lib/active_support/core_ext/object/deep_dup.rb
index f55fbc282e..1d639f3af6 100644
--- a/activesupport/lib/active_support/core_ext/object/deep_dup.rb
+++ b/activesupport/lib/active_support/core_ext/object/deep_dup.rb
@@ -32,7 +32,7 @@ end
class Hash
# Returns a deep copy of hash.
#
- # hash = { a: { b: 'b' } }
+ # hash = { a: { b: 'b' } }
# dup = hash.deep_dup
# dup[:a][:c] = 'c'
#
diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb
index b816ecae5a..efd351d741 100644
--- a/activesupport/lib/active_support/dependencies.rb
+++ b/activesupport/lib/active_support/dependencies.rb
@@ -44,7 +44,7 @@ module ActiveSupport #:nodoc:
self.autoload_once_paths = []
# An array of qualified constant names that have been loaded. Adding a name
- # to this array will cause it to be unloaded the next time Dependencies are
+ # to this array will cause it to be unloaded the next time Dependencies are
# cleared.
mattr_accessor :autoloaded_constants
self.autoloaded_constants = []
@@ -344,7 +344,7 @@ module ActiveSupport #:nodoc:
# Given +path+, a filesystem path to a ruby file, return an array of
# constant paths which would cause Dependencies to attempt to load this
- # file.
+ # file.
def loadable_constants_for_path(path, bases = autoload_paths)
path = $` if path =~ /\.rb\z/
expanded_path = File.expand_path(path)
@@ -394,7 +394,7 @@ module ActiveSupport #:nodoc:
# Attempt to autoload the provided module name by searching for a directory
# matching the expected path suffix. If found, the module is created and
# assigned to +into+'s constants with the name +const_name+. Provided that
- # the directory was loaded from a reloadable base path, it is added to the
+ # the directory was loaded from a reloadable base path, it is added to the
# set of constants that are to be unloaded.
def autoload_module!(into, const_name, qualified_name, path_suffix)
return nil unless base_path = autoloadable_module?(path_suffix)
diff --git a/activesupport/lib/active_support/duration.rb b/activesupport/lib/active_support/duration.rb
index 7e99646117..2cb1f408b6 100644
--- a/activesupport/lib/active_support/duration.rb
+++ b/activesupport/lib/active_support/duration.rb
@@ -1,4 +1,4 @@
-require 'active_support/basic_object'
+require 'active_support/proxy_object'
require 'active_support/core_ext/array/conversions'
require 'active_support/core_ext/object/acts_like'
@@ -7,7 +7,7 @@ module ActiveSupport
# Time#advance, respectively. It mainly supports the methods on Numeric.
#
# 1.month.ago # equivalent to Time.now.advance(months: -1)
- class Duration < BasicObject
+ class Duration < ProxyObject
attr_accessor :value, :parts
def initialize(value, parts) #:nodoc:
diff --git a/activesupport/lib/active_support/file_update_checker.rb b/activesupport/lib/active_support/file_update_checker.rb
index a6b9aa3503..20136dd1b0 100644
--- a/activesupport/lib/active_support/file_update_checker.rb
+++ b/activesupport/lib/active_support/file_update_checker.rb
@@ -68,7 +68,7 @@ module ActiveSupport
end
# Executes the given block and updates the latest watched files and
- # timestamp.
+ # timestamp.
def execute
@last_watched = watched
@last_update_at = updated_at(@last_watched)
diff --git a/activesupport/lib/active_support/inflector/inflections.rb b/activesupport/lib/active_support/inflector/inflections.rb
index af506d6f2e..6f259a093b 100644
--- a/activesupport/lib/active_support/inflector/inflections.rb
+++ b/activesupport/lib/active_support/inflector/inflections.rb
@@ -36,7 +36,7 @@ module ActiveSupport
end
# Private, for the test suite.
- def initialize_dup(orig) # :nodoc:
+ def initialize_dup(orig) # :nodoc:
%w(plurals singulars uncountables humans acronyms acronym_regex).each do |scope|
instance_variable_set("@#{scope}", orig.send(scope).dup)
end
@@ -44,7 +44,7 @@ module ActiveSupport
# Specifies a new acronym. An acronym must be specified as it will appear
# in a camelized string. An underscore string that contains the acronym
- # will retain the acronym when passed to +camelize+, +humanize+, or
+ # will retain the acronym when passed to +camelize+, +humanize+, or
# +titleize+. A camelized string that contains the acronym will maintain
# the acronym when titleized or humanized, and will convert the acronym
# into a non-delimited single lowercase word when passed to +underscore+.
@@ -79,7 +79,7 @@ module ActiveSupport
#
# +acronym+ may be used to specify any word that contains an acronym or
# otherwise needs to maintain a non-standard capitalization. The only
- # restriction is that the word must begin with a capital letter.
+ # restriction is that the word must begin with a capital letter.
#
# acronym 'RESTful'
# underscore 'RESTful' #=> 'restful'
@@ -97,7 +97,7 @@ module ActiveSupport
end
# Specifies a new pluralization rule and its replacement. The rule can
- # either be a string or a regular expression. The replacement should
+ # either be a string or a regular expression. The replacement should
# always be a string that may include references to the matched data from
# the rule.
def plural(rule, replacement)
diff --git a/activesupport/lib/active_support/message_encryptor.rb b/activesupport/lib/active_support/message_encryptor.rb
index 1588674afc..b7dc0689b0 100644
--- a/activesupport/lib/active_support/message_encryptor.rb
+++ b/activesupport/lib/active_support/message_encryptor.rb
@@ -33,7 +33,7 @@ module ActiveSupport
# the cipher key size. For the default 'aes-256-cbc' cipher, this is 256
# bits. If you are using a user-entered secret, you can generate a suitable
# key with <tt>OpenSSL::Digest::SHA256.new(user_secret).digest</tt> or
- # similar.
+ # similar.
#
# Options:
# * <tt>:cipher</tt> - Cipher to use. Can be any cipher returned by
@@ -50,7 +50,7 @@ module ActiveSupport
end
# Encrypt and sign a message. We need to sign the message in order to avoid
- # padding attacks. Reference: http://www.limited-entropy.com/padding-oracle-attacks.
+ # padding attacks. Reference: http://www.limited-entropy.com/padding-oracle-attacks.
def encrypt_and_sign(value)
verifier.generate(_encrypt(value))
end
diff --git a/activesupport/lib/active_support/message_verifier.rb b/activesupport/lib/active_support/message_verifier.rb
index 140b6ca08d..a87383fe99 100644
--- a/activesupport/lib/active_support/message_verifier.rb
+++ b/activesupport/lib/active_support/message_verifier.rb
@@ -6,7 +6,7 @@ module ActiveSupport
# signed to prevent tampering.
#
# This is useful for cases like remember-me tokens and auto-unsubscribe links
- # where the session store isn't suitable or available.
+ # where the session store isn't suitable or available.
#
# Remember Me:
# cookies[:remember_me] = @verifier.generate([@user.id, 2.weeks.from_now])
diff --git a/activesupport/lib/active_support/multibyte.rb b/activesupport/lib/active_support/multibyte.rb
index 1bf8e618ad..ffebd9a60b 100644
--- a/activesupport/lib/active_support/multibyte.rb
+++ b/activesupport/lib/active_support/multibyte.rb
@@ -5,7 +5,7 @@ module ActiveSupport #:nodoc:
# The proxy class returned when calling mb_chars. You can use this accessor
# to configure your own proxy class so you can support other encodings. See
- # the ActiveSupport::Multibyte::Chars implementation for an example how to
+ # the ActiveSupport::Multibyte::Chars implementation for an example how to
# do this.
#
# ActiveSupport::Multibyte.proxy_class = CharsForUTF32
diff --git a/activesupport/lib/active_support/proxy_object.rb b/activesupport/lib/active_support/proxy_object.rb
new file mode 100644
index 0000000000..a2bdf1d790
--- /dev/null
+++ b/activesupport/lib/active_support/proxy_object.rb
@@ -0,0 +1,13 @@
+module ActiveSupport
+ # A class with no predefined methods that behaves similarly to Builder's
+ # BlankSlate. Used for proxy classes.
+ class ProxyObject < ::BasicObject
+ undef_method :==
+ undef_method :equal?
+
+ # Let ActiveSupport::BasicObject at least raise exceptions.
+ def raise(*args)
+ ::Object.send(:raise, *args)
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/tagged_logging.rb b/activesupport/lib/active_support/tagged_logging.rb
index 33810442da..18bc919734 100644
--- a/activesupport/lib/active_support/tagged_logging.rb
+++ b/activesupport/lib/active_support/tagged_logging.rb
@@ -11,7 +11,7 @@ module ActiveSupport
# logger.tagged('BCX') { logger.tagged('Jason') { logger.info 'Stuff' } } # Logs "[BCX] [Jason] Stuff"
#
# This is used by the default Rails.logger as configured by Railties to make
- # it easy to stamp log lines with subdomains, request ids, and anything else
+ # it easy to stamp log lines with subdomains, request ids, and anything else
# to aid debugging of multi-user production applications.
module TaggedLogging
module Formatter # :nodoc:
diff --git a/activesupport/lib/active_support/test_case.rb b/activesupport/lib/active_support/test_case.rb
index ee7bda9f93..e4f182a3aa 100644
--- a/activesupport/lib/active_support/test_case.rb
+++ b/activesupport/lib/active_support/test_case.rb
@@ -69,7 +69,7 @@ module ActiveSupport
alias :assert_no_match :refute_match
alias :assert_not_same :refute_same
- # Fails if the block raises an exception.
+ # Fails if the block raises an exception.
#
# assert_nothing_raised do
# ...
diff --git a/activesupport/lib/active_support/values/time_zone.rb b/activesupport/lib/active_support/values/time_zone.rb
index b6fca9df91..d087955587 100644
--- a/activesupport/lib/active_support/values/time_zone.rb
+++ b/activesupport/lib/active_support/values/time_zone.rb
@@ -326,7 +326,7 @@ module ActiveSupport
end
# Available so that TimeZone instances respond like TZInfo::Timezone
- # instances.
+ # instances.
def period_for_utc(time)
tzinfo.period_for_utc(time)
end
diff --git a/activesupport/test/core_ext/duration_test.rb b/activesupport/test/core_ext/duration_test.rb
index c8312aa653..2826f51f2d 100644
--- a/activesupport/test/core_ext/duration_test.rb
+++ b/activesupport/test/core_ext/duration_test.rb
@@ -21,7 +21,7 @@ class DurationTest < ActiveSupport::TestCase
assert ActiveSupport::Duration === 1.day
assert !(ActiveSupport::Duration === 1.day.to_i)
assert !(ActiveSupport::Duration === 'foo')
- assert !(ActiveSupport::Duration === ActiveSupport::BasicObject.new)
+ assert !(ActiveSupport::Duration === ActiveSupport::ProxyObject.new)
end
def test_equals
@@ -131,7 +131,7 @@ class DurationTest < ActiveSupport::TestCase
assert_equal Time.local(2009,3,29,0,0,0) + 1.day, Time.local(2009,3,30,0,0,0)
end
end
-
+
def test_delegation_with_block_works
counter = 0
assert_nothing_raised do
diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb
index 952c82f9d8..51a7e4b2fe 100644
--- a/activesupport/test/dependencies_test.rb
+++ b/activesupport/test/dependencies_test.rb
@@ -923,8 +923,10 @@ class DependenciesTest < ActiveSupport::TestCase
def test_remove_constant_does_not_autoload_already_removed_parents_as_a_side_effect
with_autoloading_fixtures do
- ::A
- ::A::B
+ silence_warnings do
+ ::A
+ ::A::B
+ end
ActiveSupport::Dependencies.remove_constant('A')
ActiveSupport::Dependencies.remove_constant('A::B')
assert !defined?(A)
@@ -934,7 +936,9 @@ class DependenciesTest < ActiveSupport::TestCase
def test_load_once_constants_should_not_be_unloaded
with_autoloading_fixtures do
ActiveSupport::Dependencies.autoload_once_paths = ActiveSupport::Dependencies.autoload_paths
- ::A.to_s
+ silence_warnings do
+ ::A
+ end
assert defined?(A)
ActiveSupport::Dependencies.clear
assert defined?(A)
diff --git a/guides/rails_guides/generator.rb b/guides/rails_guides/generator.rb
index 3b124ef236..a53d34a279 100644
--- a/guides/rails_guides/generator.rb
+++ b/guides/rails_guides/generator.rb
@@ -84,7 +84,7 @@ module RailsGuides
@warnings = ENV['WARNINGS'] == '1'
@all = ENV['ALL'] == '1'
@kindle = ENV['KINDLE'] == '1'
- @version = ENV['RAILS_VERSION'] || `git rev-parse --short HEAD`.chomp
+ @version = ENV['RAILS_VERSION'] || 'local'
@lang = ENV['GUIDES_LANGUAGE']
end
diff --git a/guides/source/_welcome.html.erb b/guides/source/_welcome.html.erb
index 9d2e9c1d68..a50961a0c7 100644
--- a/guides/source/_welcome.html.erb
+++ b/guides/source/_welcome.html.erb
@@ -1,4 +1,4 @@
-<h2>Ruby on Rails Guides (<%= @version %>)</h2>
+<h2>Ruby on Rails Guides (<%= @edge ? @version[0, 7] : @version %>)</h2>
<% if @edge %>
<p>
diff --git a/guides/source/action_controller_overview.md b/guides/source/action_controller_overview.md
index f17f850107..46ff9027fd 100644
--- a/guides/source/action_controller_overview.md
+++ b/guides/source/action_controller_overview.md
@@ -434,7 +434,7 @@ Filters are inherited, so if you set a filter on `ApplicationController`, it wil
```ruby
class ApplicationController < ActionController::Base
- before_filter :require_login
+ before_action :require_login
private
@@ -458,11 +458,11 @@ end
The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a "before" filter renders or redirects, the action will not run. If there are additional filters scheduled to run after that filter, they are also cancelled.
-In this example the filter is added to `ApplicationController` and thus all controllers in the application inherit it. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with `skip_before_filter`:
+In this example the filter is added to `ApplicationController` and thus all controllers in the application inherit it. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with `skip_before_action`:
```ruby
class LoginsController < ApplicationController
- skip_before_filter :require_login, only: [:new, :create]
+ skip_before_action :require_login, only: [:new, :create]
end
```
@@ -480,7 +480,7 @@ For example, in a website where changes have an approval workflow an administrat
```ruby
class ChangesController < ActionController::Base
- around_filter :wrap_in_transaction, only: :show
+ around_action :wrap_in_transaction, only: :show
private
@@ -502,13 +502,13 @@ You can choose not to yield and build the response yourself, in which case the a
### Other Ways to Use Filters
-While the most common way to use filters is by creating private methods and using *_filter to add them, there are two other ways to do the same thing.
+While the most common way to use filters is by creating private methods and using *_action to add them, there are two other ways to do the same thing.
-The first is to use a block directly with the *_filter methods. The block receives the controller as an argument, and the `require_login` filter from above could be rewritten to use a block:
+The first is to use a block directly with the *_action methods. The block receives the controller as an argument, and the `require_login` filter from above could be rewritten to use a block:
```ruby
class ApplicationController < ActionController::Base
- before_filter do |controller|
+ before_action do |controller|
redirect_to new_login_url unless controller.send(:logged_in?)
end
end
@@ -520,7 +520,7 @@ The second way is to use a class (actually, any object that responds to the righ
```ruby
class ApplicationController < ActionController::Base
- before_filter LoginFilter
+ before_action LoginFilter
end
class LoginFilter
@@ -648,7 +648,7 @@ HTTP digest authentication is superior to the basic authentication as it does no
class AdminController < ApplicationController
USERS = { "lifo" => "world" }
- before_filter :authenticate
+ before_action :authenticate
private
@@ -751,15 +751,36 @@ Now the user can request to get a PDF version of a client just by adding ".pdf"
GET /clients/1.pdf
```
-Parameter Filtering
--------------------
+Log Filtering
+-------------
+
+Rails keeps a log file for each environment in the `log` folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file.
-Rails keeps a log file for each environment in the `log` folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. You can filter certain request parameters from your log files by appending them to `config.filter_parameters` in the application configuration. These parameters will be marked [FILTERED] in the log.
+### Parameters Filtering
+
+You can filter certain request parameters from your log files by appending them to `config.filter_parameters` in the application configuration. These parameters will be marked [FILTERED] in the log.
```ruby
config.filter_parameters << :password
```
+### Redirects Filtering
+
+Sometimes it's desirable to filter out from log files some sensible locations your application is redirecting to.
+You can do that by using the `config.filter_redirect` configuration option:
+
+```ruby
+config.filter_redirect << 's3.amazonaws.com'
+```
+
+You can set it to a String, a Regexp, or an array of both.
+
+```ruby
+config.filter_redirect.concat ['s3.amazonaws.com', /private_path/]
+```
+
+Matching URLs will be marked as '[FILTERED]'.
+
Rescue
------
@@ -807,7 +828,7 @@ end
class ClientsController < ApplicationController
# Check that the user has the right authorization to access clients.
- before_filter :check_authorization
+ before_action :check_authorization
# Note how the actions don't have to worry about all the auth stuff.
def edit
diff --git a/guides/source/action_mailer_basics.md b/guides/source/action_mailer_basics.md
index b2ccc2d82c..aaf04f4256 100644
--- a/guides/source/action_mailer_basics.md
+++ b/guides/source/action_mailer_basics.md
@@ -447,17 +447,17 @@ end
Action Mailer Callbacks
---------------------------
-Action Mailer allows for you to specify a `before_filter`, `after_filter` and 'around_filter'.
+Action Mailer allows for you to specify a `before_action`, `after_action` and 'around_action'.
* Filters can be specified with a block or a symbol to a method in the mailer class similar to controllers.
-* You could use a `before_filter` to prepopulate the mail object with defaults, delivery_method_options or insert default headers and attachments.
+* You could use a `before_action` to prepopulate the mail object with defaults, delivery_method_options or insert default headers and attachments.
-* You could use an `after_filter` to do similar setup as a `before_filter` but using instance variables set in your mailer action.
+* You could use an `after_action` to do similar setup as a `before_action` but using instance variables set in your mailer action.
```ruby
class UserMailer < ActionMailer::Base
- after_filter :set_delivery_options, :prevent_delivery_to_guests, :set_business_headers
+ after_action :set_delivery_options, :prevent_delivery_to_guests, :set_business_headers
def feedback_message(business, user)
@business = business
diff --git a/guides/source/action_view_overview.md b/guides/source/action_view_overview.md
index 4ea60391ba..6c2871d478 100644
--- a/guides/source/action_view_overview.md
+++ b/guides/source/action_view_overview.md
@@ -1484,7 +1484,7 @@ You can use the same technique to localize the rescue files in your public direc
Since Rails doesn't restrict the symbols that you use to set I18n.locale, you can leverage this system to display different content depending on anything you like. For example, suppose you have some "expert" users that should see different pages from "normal" users. You could add the following to `app/controllers/application.rb`:
```ruby
-before_filter :set_expert_locale
+before_action :set_expert_locale
def set_expert_locale
I18n.locale = :expert if current_user.expert?
diff --git a/guides/source/active_model_basics.md b/guides/source/active_model_basics.md
index 0c278095ab..68ac26c681 100644
--- a/guides/source/active_model_basics.md
+++ b/guides/source/active_model_basics.md
@@ -10,7 +10,7 @@ After reading this guide, you will know:
Introduction
------------
-Active Model is a library containing various modules used in developing frameworks that need to interact with the Rails Action Pack library. Active Model provides a known set of interfaces for usage in classes. Some of modules are explained below.
+Active Model is a library containing various modules used in developing frameworks that need to interact with the Rails Action Pack library. Active Model provides a known set of interfaces for usage in classes. Some of modules are explained below.
### AttributeMethods
@@ -26,23 +26,21 @@ class Person
attr_accessor :age
-private
- def reset_attribute(attribute)
- send("#{attribute}=", 0)
- end
+ private
+ def reset_attribute(attribute)
+ send("#{attribute}=", 0)
+ end
- def attribute_highest?(attribute)
- send(attribute) > 100 ? true : false
- end
-
+ def attribute_highest?(attribute)
+ send(attribute) > 100
+ end
end
person = Person.new
person.age = 110
person.age_highest? # true
person.reset_age # 0
-person.age_highest? # false
-
+person.age_highest? # false
```
### Callbacks
@@ -87,14 +85,14 @@ class Person
end
person = Person.new
-person.to_model == person #=> true
-person.to_key #=> nil
-person.to_param #=> nil
+person.to_model == person # => true
+person.to_key # => nil
+person.to_param # => nil
```
### Dirty
-An object becomes dirty when it has gone through one or more changes to its attributes and has not been saved. This gives the ability to check whether an object has been changed or not. It also has attribute based accessor methods. Let's consider a Person class with attributes first_name and last_name
+An object becomes dirty when it has gone through one or more changes to its attributes and has not been saved. This gives the ability to check whether an object has been changed or not. It also has attribute based accessor methods. Let's consider a Person class with attributes `first_name` and `last_name`:
```ruby
require 'active_model'
@@ -123,8 +121,8 @@ class Person
def save
@previously_changed = changes
+ # do save work...
end
-
end
```
@@ -132,21 +130,22 @@ end
```ruby
person = Person.new
-person.first_name = "First Name"
+person.changed? # => false
-person.first_name #=> "First Name"
-person.first_name = "First Name Changed"
+person.first_name = "First Name"
+person.first_name # => "First Name"
-person.changed? #=> true
+# returns if any attribute has changed.
+person.changed? # => true
-#returns an list of fields arry which all has been changed before saved.
-person.changed #=> ["first_name"]
+# returns a list of attributes that have changed before saving.
+person.changed # => ["first_name"]
-#returns a hash of the fields that have changed with their original values.
-person.changed_attributes #=> {"first_name" => "First Name Changed"}
+# returns a hash of the attributes that have changed with their original values.
+person.changed_attributes # => {"first_name"=>nil}
-#returns a hash of changes, with the attribute names as the keys, and the values will be an array of the old and new value for that field.
-person.changes #=> {"first_name" => ["First Name","First Name Changed"]}
+# returns a hash of changes, with the attribute names as the keys, and the values will be an array of the old and new value for that field.
+person.changes # => {"first_name"=>[nil, "First Name"]}
```
#### Attribute based accessor methods
@@ -154,28 +153,24 @@ person.changes #=> {"first_name" => ["First Name","First Name Changed"]}
Track whether the particular attribute has been changed or not.
```ruby
-#attr_name_changed?
-person.first_name #=> "First Name"
-
-#assign some other value to first_name attribute
-person.first_name = "First Name 1"
-
-person.first_name_changed? #=> true
+# attr_name_changed?
+person.first_name # => "First Name"
+person.first_name_changed? # => true
```
Track what was the previous value of the attribute.
```ruby
-#attr_name_was accessor
-person.first_name_was #=> "First Name"
+# attr_name_was accessor
+person.first_name_was # => "First Name"
```
Track both previous and current value of the changed attribute. Returns an array if changed, else returns nil.
```ruby
-#attr_name_change
-person.first_name_change #=> ["First Name", "First Name 1"]
-person.last_name_change #=> nil
+# attr_name_change
+person.first_name_change # => [nil, "First Name"]
+person.last_name_change # => nil
```
### Validations
@@ -187,20 +182,19 @@ class Person
include ActiveModel::Validations
attr_accessor :name, :email, :token
-
+
validates :name, presence: true
- validates_format_of :email, with: /\A([^\s]+)((?:[-a-z0-9]\.)[a-z]{2,})\z/i
+ validates_format_of :email, with: /\A([^\s]+)((?:[-a-z0-9]\.)[a-z]{2,})\z/i
validates! :token, presence: true
-
end
person = Person.new(token: "2b1f325")
-person.valid? #=> false
-person.name = 'vishnu'
-person.email = 'me'
-person.valid? #=> false
+person.valid? # => false
+person.name = 'vishnu'
+person.email = 'me'
+person.valid? # => false
person.email = 'me@vishnuatrai.com'
-person.valid? #=> true
+person.valid? # => true
person.token = nil
-person.valid? #=> raises ActiveModel::StrictValidationFailed
+person.valid? # => raises ActiveModel::StrictValidationFailed
```
diff --git a/guides/source/active_record_basics.md b/guides/source/active_record_basics.md
index cb64cf39f3..68c6416e89 100644
--- a/guides/source/active_record_basics.md
+++ b/guides/source/active_record_basics.md
@@ -147,15 +147,15 @@ Active Record objects can be created from a hash, a block or have their attribut
For example, given a model `User` with attributes of `name` and `occupation`, the `create` method call will create and save a new record into the database:
```ruby
- user = User.create(name: "David", occupation: "Code Artist")
+user = User.create(name: "David", occupation: "Code Artist")
```
Using the `new` method, an object can be created without being saved:
```ruby
- user = User.new
- user.name = "David"
- user.occupation = "Code Artist"
+user = User.new
+user.name = "David"
+user.occupation = "Code Artist"
```
A call to `user.save` will commit the record to the database.
@@ -163,10 +163,10 @@ A call to `user.save` will commit the record to the database.
Finally, if a block is provided, both `create` and `new` will yield the new object to that block for initialization:
```ruby
- user = User.new do |u|
- u.name = "David"
- u.occupation = "Code Artist"
- end
+user = User.new do |u|
+ u.name = "David"
+ u.occupation = "Code Artist"
+end
```
### Read
@@ -174,23 +174,23 @@ Finally, if a block is provided, both `create` and `new` will yield the new obje
Active Record provides a rich API for accessing data within a database. Below are a few examples of different data access methods provided by Active Record.
```ruby
- # return array with all records
- users = User.all
+# return array with all records
+users = User.all
```
```ruby
- # return the first record
- user = User.first
+# return the first record
+user = User.first
```
```ruby
- # return the first user named David
- david = User.find_by_name('David')
+# return the first user named David
+david = User.find_by_name('David')
```
```ruby
- # find all users named David who are Code Artists and sort by created_at in reverse chronological order
- users = User.where(name: 'David', occupation: 'Code Artist').order('created_at DESC')
+# find all users named David who are Code Artists and sort by created_at in reverse chronological order
+users = User.where(name: 'David', occupation: 'Code Artist').order('created_at DESC')
```
You can learn more about querying an Active Record model in the [Active Record Query Interface](active_record_querying.html) guide.
@@ -200,9 +200,9 @@ You can learn more about querying an Active Record model in the [Active Record Q
Once an Active Record object has been retrieved, its attributes can be modified and it can be saved to the database.
```ruby
- user = User.find_by_name('David')
- user.name = 'Dave'
- user.save
+user = User.find_by_name('David')
+user.name = 'Dave'
+user.save
```
### Delete
@@ -210,8 +210,8 @@ Once an Active Record object has been retrieved, its attributes can be modified
Likewise, once retrieved an Active Record object can be destroyed which removes it from the database.
```ruby
- user = User.find_by_name('David')
- user.destroy
+user = User.find_by_name('David')
+user.destroy
```
Validations
diff --git a/guides/source/active_record_callbacks.md b/guides/source/active_record_callbacks.md
index 550800861d..971c1cdb25 100644
--- a/guides/source/active_record_callbacks.md
+++ b/guides/source/active_record_callbacks.md
@@ -200,7 +200,7 @@ Halting Execution
As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks, and the database operation to be executed.
-The whole callback chain is wrapped in a transaction. If any <em>before</em> callback method returns exactly `false` or raises an exception, the execution chain gets halted and a ROLLBACK is issued; <em>after</em> callbacks can only accomplish that by raising an exception.
+The whole callback chain is wrapped in a transaction. If any _before_ callback method returns exactly `false` or raises an exception, the execution chain gets halted and a ROLLBACK is issued; _after_ callbacks can only accomplish that by raising an exception.
WARNING. Raising an arbitrary exception may break code that expects `save` and its friends not to fail like that. The `ActiveRecord::Rollback` exception is thought precisely to tell Active Record a rollback is going on. That one is internally captured but not reraised.
diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md
index 889e869a2a..24f98f68ca 100644
--- a/guides/source/active_record_querying.md
+++ b/guides/source/active_record_querying.md
@@ -505,6 +505,20 @@ This code will generate SQL like this:
SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5))
```
+### NOT, LIKE, and NOT LIKE Conditions
+
+`NOT`, `LIKE`, and `NOT LIKE` SQL queries can be built by `where.not`, `where.like`, and `where.not_like` respectively.
+
+```ruby
+Post.where.not(author: author)
+
+Author.where.like(name: 'Nari%')
+
+Developer.where.not_like(name: 'Tenderl%')
+```
+
+In other words, these sort of queries can be generated by calling `where` with no argument, then immediately chain with `not`, `like`, or `not_like` passing `where` conditions.
+
Ordering
--------
diff --git a/guides/source/active_record_validations.md b/guides/source/active_record_validations.md
index 6e20e74c34..2e2f0e4ea9 100644
--- a/guides/source/active_record_validations.md
+++ b/guides/source/active_record_validations.md
@@ -264,7 +264,7 @@ class Person < ActiveRecord::Base
end
```
-The default error message for this helper is "_must be accepted_".
+The default error message for this helper is _"must be accepted"_.
It can receive an `:accept` option, which determines the value that will be
considered acceptance. It defaults to "1" and can be easily changed.
@@ -293,7 +293,7 @@ This validation will work with all of the association types.
CAUTION: Don't use `validates_associated` on both ends of your associations.
They would call each other in an infinite loop.
-The default error message for `validates_associated` is "_is invalid_". Note
+The default error message for `validates_associated` is _"is invalid"_. Note
that each associated object will contain its own `errors` collection; errors do
not bubble up to the calling model.
@@ -328,7 +328,7 @@ class Person < ActiveRecord::Base
end
```
-The default error message for this helper is "_doesn't match confirmation_".
+The default error message for this helper is _"doesn't match confirmation"_.
### `exclusion`
@@ -348,7 +348,7 @@ alias called `:within` that you can use for the same purpose, if you'd like to.
This example uses the `:message` option to show how you can include the
attribute's value.
-The default error message is "_is reserved_".
+The default error message is _"is reserved"_.
### `format`
@@ -362,7 +362,7 @@ class Product < ActiveRecord::Base
end
```
-The default error message is "_is invalid_".
+The default error message is _"is invalid"_.
### `inclusion`
@@ -381,7 +381,7 @@ will be accepted. The `:in` option has an alias called `:within` that you can
use for the same purpose, if you'd like to. The previous example uses the
`:message` option to show how you can include the attribute's value.
-The default error message for this helper is "_is not included in the list_".
+The default error message for this helper is _"is not included in the list"_.
### `length`
@@ -471,24 +471,24 @@ Besides `:only_integer`, this helper also accepts the following options to add
constraints to acceptable values:
* `:greater_than` - Specifies the value must be greater than the supplied
- value. The default error message for this option is "_must be greater than
- %{count}_".
+ value. The default error message for this option is _"must be greater than
+ %{count}"_.
* `:greater_than_or_equal_to` - Specifies the value must be greater than or
equal to the supplied value. The default error message for this option is
- "_must be greater than or equal to %{count}_".
+ _"must be greater than or equal to %{count}"_.
* `:equal_to` - Specifies the value must be equal to the supplied value. The
- default error message for this option is "_must be equal to %{count}_".
+ default error message for this option is _"must be equal to %{count}"_.
* `:less_than` - Specifies the value must be less than the supplied value. The
- default error message for this option is "_must be less than %{count}_".
+ default error message for this option is _"must be less than %{count}"_.
* `:less_than_or_equal_to` - Specifies the value must be less than or equal the
- supplied value. The default error message for this option is "_must be less
- than or equal to %{count}_".
+ supplied value. The default error message for this option is _"must be less
+ than or equal to %{count}"_.
* `:odd` - Specifies the value must be an odd number if set to true. The
- default error message for this option is "_must be odd_".
+ default error message for this option is _"must be odd"_.
* `:even` - Specifies the value must be an even number if set to true. The
- default error message for this option is "_must be even_".
+ default error message for this option is _"must be even"_.
-The default error message is "_is not a number_".
+The default error message is _"is not a number"_.
### `presence`
@@ -528,7 +528,7 @@ If you validate the presence of an object associated via a `has_one` or
Since `false.blank?` is true, if you want to validate the presence of a boolean
field you should use `validates :field_name, inclusion: { in: [true, false] }`.
-The default error message is "_can't be empty_".
+The default error message is _"can't be empty"_.
### `uniqueness`
@@ -570,7 +570,7 @@ end
WARNING. Note that some databases are configured to perform case-insensitive
searches anyway.
-The default error message is "_has already been taken_".
+The default error message is _"has already been taken"_.
### `validates_with`
@@ -714,7 +714,7 @@ class Person < ActiveRecord::Base
validates :name, presence: { strict: true }
end
-Person.new.valid? #=> ActiveModel::StrictValidationFailed: Name can't be blank
+Person.new.valid? # => ActiveModel::StrictValidationFailed: Name can't be blank
```
There is also an ability to pass custom exception to `:strict` option
@@ -724,7 +724,7 @@ class Person < ActiveRecord::Base
validates :token, presence: true, uniqueness: true, strict: TokenGenerationException
end
-Person.new.valid? #=> TokenGenerationException: Token can't be blank
+Person.new.valid? # => TokenGenerationException: Token can't be blank
```
Conditional Validation
@@ -917,7 +917,7 @@ validations fail.
Because every application handles this kind of thing differently, Rails does
not include any view helpers to help you generate these messages directly.
-However, due to the rich number of methods Rails gives you to interact with
+However, due to the rich number of methods Rails gives you to interact with
validations in general, it's fairly easy to build your own. In addition, when
generating a scaffold, Rails will put some ERB into the `_form.html.erb` that
it generates that displays the full list of errors on that model.
diff --git a/guides/source/caching_with_rails.md b/guides/source/caching_with_rails.md
index e737dcab83..773102400a 100644
--- a/guides/source/caching_with_rails.md
+++ b/guides/source/caching_with_rails.md
@@ -104,7 +104,7 @@ Let's say you only wanted authenticated users to call actions on `ProductsContro
```ruby
class ProductsController < ActionController
- before_filter :authenticate
+ before_action :authenticate
caches_action :index
def index
diff --git a/guides/source/i18n.md b/guides/source/i18n.md
index 1131b7f245..399a4963d7 100644
--- a/guides/source/i18n.md
+++ b/guides/source/i18n.md
@@ -134,10 +134,10 @@ However, you would probably like to **provide support for more locales** in your
WARNING: You may be tempted to store the chosen locale in a _session_ or a <em>cookie</em>, however **do not do this**. The locale should be transparent and a part of the URL. This way you won't break people's basic assumptions about the web itself: if you send a URL to a friend, they should see the same page and content as you. A fancy word for this would be that you're being [<em>RESTful</em>](http://en.wikipedia.org/wiki/Representational_State_Transfer. Read more about the RESTful approach in [Stefan Tilkov's articles](http://www.infoq.com/articles/rest-introduction). Sometimes there are exceptions to this rule and those are discussed below.
-The _setting part_ is easy. You can set the locale in a `before_filter` in the `ApplicationController` like this:
+The _setting part_ is easy. You can set the locale in a `before_action` in the `ApplicationController` like this:
```ruby
-before_filter :set_locale
+before_action :set_locale
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
@@ -160,7 +160,7 @@ One option you have is to set the locale from the domain name where your applica
You can implement it like this in your `ApplicationController`:
```ruby
-before_filter :set_locale
+before_action :set_locale
def set_locale
I18n.locale = extract_locale_from_tld || I18n.default_locale
@@ -203,7 +203,7 @@ This solution has aforementioned advantages, however, you may not be able or may
### Setting the Locale from the URL Params
-The most usual way of setting (and passing) the locale would be to include it in URL params, as we did in the `I18n.locale = params[:locale]` _before_filter_ in the first example. We would like to have URLs like `www.example.com/books?locale=ja` or `www.example.com/ja/books` in this case.
+The most usual way of setting (and passing) the locale would be to include it in URL params, as we did in the `I18n.locale = params[:locale]` _before_action_ in the first example. We would like to have URLs like `www.example.com/books?locale=ja` or `www.example.com/ja/books` in this case.
This approach has almost the same set of advantages as setting the locale from the domain name: namely that it's RESTful and in accord with the rest of the World Wide Web. It does require a little bit more work to implement, though.
diff --git a/guides/source/security.md b/guides/source/security.md
index 6c32a8ff5b..532a1ae5cc 100644
--- a/guides/source/security.md
+++ b/guides/source/security.md
@@ -688,7 +688,7 @@ NOTE: _When sanitizing, protecting or verifying something, whitelists over black
A blacklist can be a list of bad e-mail addresses, non-public actions or bad HTML tags. This is opposed to a whitelist which lists the good e-mail addresses, public actions, good HTML tags and so on. Although sometimes it is not possible to create a whitelist (in a SPAM filter, for example), _prefer to use whitelist approaches_:
-* Use before_filter only: [...] instead of except: [...]. This way you don't forget to turn it off for newly added actions.
+* Use before_action only: [...] instead of except: [...]. This way you don't forget to turn it off for newly added actions.
* Use attr_accessible instead of attr_protected. See the mass-assignment section for details
* Allow &lt;strong&gt; instead of removing &lt;script&gt; against Cross-Site Scripting (XSS). See below for details.
* Don't try to correct user input by blacklists:
diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md
index c3da3094dc..01dd86c23e 100644
--- a/railties/CHANGELOG.md
+++ b/railties/CHANGELOG.md
@@ -1,5 +1,9 @@
## Rails 4.0.0 (unreleased) ##
+* Add ENV['RACK_ENV'] support to `rails runner/console/server`.
+
+ *kennyj*
+
* Add `db` to list of folders included by `rake notes` and `rake notes:custom`. *Antonio Cangiano*
* Engines with a dummy app include the rake tasks of dependencies in the app namespace.
diff --git a/railties/lib/rails.rb b/railties/lib/rails.rb
index 6bf2d8db20..b6a9eccdb6 100644
--- a/railties/lib/rails.rb
+++ b/railties/lib/rails.rb
@@ -24,13 +24,7 @@ module Rails
autoload :InfoController, 'rails/info_controller'
class << self
- def application
- @application ||= nil
- end
-
- def application=(application)
- @application = application
- end
+ attr_accessor :application, :cache, :logger
# The Configuration instance used to configure the Rails environment
def configuration
@@ -64,14 +58,6 @@ module Rails
application.initialized?
end
- def logger
- @logger ||= nil
- end
-
- def logger=(logger)
- @logger = logger
- end
-
def backtrace_cleaner
@backtrace_cleaner ||= begin
# Relies on Active Support, so we have to lazy load to postpone definition until AS has been loaded
@@ -95,14 +81,6 @@ module Rails
@_env = ActiveSupport::StringInquirer.new(environment)
end
- def cache
- @cache ||= nil
- end
-
- def cache=(cache)
- @cache = cache
- end
-
# Returns all rails groups for loading based on:
#
# * The Rails environment;
diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb
index ae3993fbd8..bf3a26d400 100644
--- a/railties/lib/rails/application.rb
+++ b/railties/lib/rails/application.rb
@@ -123,6 +123,7 @@ module Rails
# Currently stores:
#
# * "action_dispatch.parameter_filter" => config.filter_parameters
+ # * "action_dispatch.redirect_filter" => config.filter_redirect
# * "action_dispatch.secret_token" => config.secret_token,
# * "action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions
# * "action_dispatch.show_detailed_exceptions" => config.consider_all_requests_local
@@ -149,6 +150,7 @@ module Rails
super.merge({
"action_dispatch.parameter_filter" => config.filter_parameters,
+ "action_dispatch.redirect_filter" => config.filter_redirect,
"action_dispatch.secret_token" => config.secret_token,
"action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions,
"action_dispatch.show_detailed_exceptions" => config.consider_all_requests_local,
diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb
index 89afeaeec5..f15fc9296d 100644
--- a/railties/lib/rails/application/configuration.rb
+++ b/railties/lib/rails/application/configuration.rb
@@ -13,7 +13,7 @@ module Rails
:railties_order, :relative_url_root, :secret_key_base, :secret_token,
:serve_static_assets, :ssl_options, :static_cache_control, :session_options,
:time_zone, :reload_classes_only_on_change,
- :queue, :queue_consumer, :beginning_of_week
+ :queue, :queue_consumer, :beginning_of_week, :filter_redirect
attr_writer :log_level
attr_reader :encoding
@@ -23,6 +23,7 @@ module Rails
self.encoding = "utf-8"
@consider_all_requests_local = false
@filter_parameters = []
+ @filter_redirect = []
@helpers_paths = []
@serve_static_assets = true
@static_cache_control = nil
diff --git a/railties/lib/rails/commands.rb b/railties/lib/rails/commands.rb
index b0fae13192..3ab2a3809e 100644
--- a/railties/lib/rails/commands.rb
+++ b/railties/lib/rails/commands.rb
@@ -60,7 +60,7 @@ when 'console'
require 'rails/commands/console'
options = Rails::Console.parse_arguments(ARGV)
- # RAILS_ENV needs to be set before config/application is required
+ # RAILS_ENV needs to be set before config/application is required
ENV['RAILS_ENV'] = options[:environment] if options[:environment]
# shift ARGV so IRB doesn't freak
diff --git a/railties/lib/rails/commands/console.rb b/railties/lib/rails/commands/console.rb
index 92cee6b638..aef7600fbd 100644
--- a/railties/lib/rails/commands/console.rb
+++ b/railties/lib/rails/commands/console.rb
@@ -45,7 +45,7 @@ module Rails
end
def environment
- options[:environment] ||= ENV['RAILS_ENV'] || 'development'
+ options[:environment] ||= ENV['RAILS_ENV'] || ENV['RACK_ENV'] || 'development'
end
def environment?
diff --git a/railties/lib/rails/commands/runner.rb b/railties/lib/rails/commands/runner.rb
index 62d82cc005..6adbdc6e0b 100644
--- a/railties/lib/rails/commands/runner.rb
+++ b/railties/lib/rails/commands/runner.rb
@@ -1,7 +1,7 @@
require 'optparse'
require 'rbconfig'
-options = { environment: (ENV['RAILS_ENV'] || "development").dup }
+options = { environment: (ENV['RAILS_ENV'] || ENV['RACK_ENV'] || "development").dup }
code_or_file = nil
if ARGV.first.nil?
diff --git a/railties/lib/rails/commands/server.rb b/railties/lib/rails/commands/server.rb
index 0b897d736d..cdb29a8156 100644
--- a/railties/lib/rails/commands/server.rb
+++ b/railties/lib/rails/commands/server.rb
@@ -108,7 +108,7 @@ module Rails
super.merge({
Port: 3000,
DoNotReverseLookup: true,
- environment: (ENV['RAILS_ENV'] || "development").dup,
+ environment: (ENV['RAILS_ENV'] || ENV['RACK_ENV'] || "development").dup,
daemonize: false,
debugger: false,
pid: File.expand_path("tmp/pids/server.pid"),
diff --git a/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt b/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt
index 6645f40afa..7342bffd9d 100644
--- a/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt
+++ b/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt
@@ -13,8 +13,6 @@
<% unless options[:skip_javascript] -%>
//= require <%= options[:javascript] %>
//= require <%= options[:javascript] %>_ujs
-<% end -%>
-//= require_tree .
-<% unless options[:skip_javascript] -%>
//= require turbolinks
<% end -%>
+//= require_tree .
diff --git a/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb b/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb
index b4f466fbd8..60d202c5ef 100644
--- a/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb
+++ b/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb
@@ -2,7 +2,7 @@ require 'rails/generators/rails/resource/resource_generator'
module Rails
module Generators
- class ScaffoldGenerator < ResourceGenerator # :nodoc:
+ class ScaffoldGenerator < ResourceGenerator # :nodoc:
remove_hook_for :resource_controller
remove_class_option :actions
diff --git a/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb b/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb
index d6bce40b0c..24d97db407 100644
--- a/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb
+++ b/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb
@@ -4,6 +4,8 @@ require_dependency "<%= namespaced_file_path %>/application_controller"
<% end -%>
<% module_namespacing do -%>
class <%= controller_class_name %>Controller < ApplicationController
+ before_action :set_<%= singular_table_name %>, only: [ :show, :edit, :update, :destroy ]
+
# GET <%= route_url %>
# GET <%= route_url %>.json
def index
@@ -18,8 +20,6 @@ class <%= controller_class_name %>Controller < ApplicationController
# GET <%= route_url %>/1
# GET <%= route_url %>/1.json
def show
- @<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %>
-
respond_to do |format|
format.html # show.html.erb
format.json { render json: <%= "@#{singular_table_name}" %> }
@@ -39,7 +39,6 @@ class <%= controller_class_name %>Controller < ApplicationController
# GET <%= route_url %>/1/edit
def edit
- @<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %>
end
# POST <%= route_url %>
@@ -61,8 +60,6 @@ class <%= controller_class_name %>Controller < ApplicationController
# PATCH/PUT <%= route_url %>/1
# PATCH/PUT <%= route_url %>/1.json
def update
- @<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %>
-
respond_to do |format|
if @<%= orm_instance.update_attributes("#{singular_table_name}_params") %>
format.html { redirect_to @<%= singular_table_name %>, notice: <%= "'#{human_name} was successfully updated.'" %> }
@@ -77,7 +74,6 @@ class <%= controller_class_name %>Controller < ApplicationController
# DELETE <%= route_url %>/1
# DELETE <%= route_url %>/1.json
def destroy
- @<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %>
@<%= orm_instance.destroy %>
respond_to do |format|
@@ -87,6 +83,10 @@ class <%= controller_class_name %>Controller < ApplicationController
end
private
+ # Use callbacks to share common setup or constraints between actions.
+ def set_<%= singular_table_name %>
+ @<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %>
+ end
# Use this method to whitelist the permissible parameters. Example: params.require(:person).permit(:name, :age)
# Also, you can specialize this method with per-user checking of permissible attributes.
diff --git a/railties/lib/rails/generators/test_case.rb b/railties/lib/rails/generators/test_case.rb
index 24308dcf6c..01e0e66d89 100644
--- a/railties/lib/rails/generators/test_case.rb
+++ b/railties/lib/rails/generators/test_case.rb
@@ -163,7 +163,7 @@ module Rails
# end
# end
def assert_instance_method(method, content)
- assert content =~ /def #{method}(\(.+\))?(.*?)\n end/m, "Expected to have method #{method}"
+ assert content =~ /def #{method}(\(.+\))?(.*?)\n\s+end/m, "Expected to have method #{method}"
yield $2.strip if block_given?
end
alias :assert_method :assert_instance_method
diff --git a/railties/test/abstract_unit.rb b/railties/test/abstract_unit.rb
index 2ea1d2aff4..ecd5e03978 100644
--- a/railties/test/abstract_unit.rb
+++ b/railties/test/abstract_unit.rb
@@ -7,7 +7,6 @@ require 'minitest/autorun'
require 'fileutils'
require 'active_support'
-
require 'action_controller'
require 'rails/all'
diff --git a/railties/test/application/rake/dbs_test.rb b/railties/test/application/rake/dbs_test.rb
index 03798d572a..ccb47663d4 100644
--- a/railties/test/application/rake/dbs_test.rb
+++ b/railties/test/application/rake/dbs_test.rb
@@ -55,8 +55,8 @@ module ApplicationTests
def db_migrate_and_status
Dir.chdir(app_path) do
- `rails generate model book title:string`
- `bundle exec rake db:migrate`
+ `rails generate model book title:string;
+ bundle exec rake db:migrate`
output = `bundle exec rake db:migrate:status`
assert_match(/database:\s+\S+#{expected[:database]}/, output)
assert_match(/up\s+\d{14}\s+Create books/, output)
@@ -78,9 +78,8 @@ module ApplicationTests
def db_schema_dump
Dir.chdir(app_path) do
- `rails generate model book title:string`
- `rake db:migrate`
- `rake db:schema:dump`
+ `rails generate model book title:string;
+ rake db:migrate db:schema:dump`
schema_dump = File.read("db/schema.rb")
assert_match(/create_table \"books\"/, schema_dump)
end
@@ -97,9 +96,8 @@ module ApplicationTests
def db_fixtures_load
Dir.chdir(app_path) do
- `rails generate model book title:string`
- `bundle exec rake db:migrate`
- `bundle exec rake db:fixtures:load`
+ `rails generate model book title:string;
+ bundle exec rake db:migrate db:fixtures:load`
assert_match(/#{expected[:database]}/,
ActiveRecord::Base.connection_config[:database])
require "#{app_path}/app/models/book"
@@ -122,13 +120,11 @@ module ApplicationTests
def db_structure_dump_and_load
Dir.chdir(app_path) do
- `rails generate model book title:string`
- `bundle exec rake db:migrate`
- `bundle exec rake db:structure:dump`
+ `rails generate model book title:string;
+ bundle exec rake db:migrate db:structure:dump`
structure_dump = File.read("db/structure.sql")
assert_match(/CREATE TABLE \"books\"/, structure_dump)
- `bundle exec rake db:drop`
- `bundle exec rake db:structure:load`
+ `bundle exec rake db:drop db:structure:load`
assert_match(/#{expected[:database]}/,
ActiveRecord::Base.connection_config[:database])
require "#{app_path}/app/models/book"
@@ -152,10 +148,8 @@ module ApplicationTests
def db_test_load_structure
Dir.chdir(app_path) do
- `rails generate model book title:string`
- `bundle exec rake db:migrate`
- `bundle exec rake db:structure:dump`
- `bundle exec rake db:test:load_structure`
+ `rails generate model book title:string;
+ bundle exec rake db:migrate db:structure:dump db:test:load_structure`
ActiveRecord::Base.configurations = Rails.application.config.database_configuration
ActiveRecord::Base.establish_connection 'test'
require "#{app_path}/app/models/book"
@@ -178,4 +172,4 @@ module ApplicationTests
end
end
end
-end \ No newline at end of file
+end
diff --git a/railties/test/application/runner_test.rb b/railties/test/application/runner_test.rb
index 81ed5873a5..f65b5e2f2d 100644
--- a/railties/test/application/runner_test.rb
+++ b/railties/test/application/runner_test.rb
@@ -1,8 +1,10 @@
require 'isolation/abstract_unit'
+require 'env_helpers'
module ApplicationTests
class RunnerTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
+ include EnvHelpers
def setup
build_app
@@ -67,5 +69,21 @@ module ApplicationTests
assert_match "true", Dir.chdir(app_path) { `bundle exec rails runner "puts Rails.application.config.ran"` }
end
+
+ def test_default_environment
+ assert_match "development", Dir.chdir(app_path) { `bundle exec rails runner "puts Rails.env"` }
+ end
+
+ def test_environment_with_rails_env
+ with_rails_env "production" do
+ assert_match "production", Dir.chdir(app_path) { `bundle exec rails runner "puts Rails.env"` }
+ end
+ end
+
+ def test_environment_with_rack_env
+ with_rack_env "production" do
+ assert_match "production", Dir.chdir(app_path) { `bundle exec rails runner "puts Rails.env"` }
+ end
+ end
end
end
diff --git a/railties/test/commands/console_test.rb b/railties/test/commands/console_test.rb
index f99ea13022..9e449856f4 100644
--- a/railties/test/commands/console_test.rb
+++ b/railties/test/commands/console_test.rb
@@ -1,14 +1,14 @@
require 'abstract_unit'
+require 'env_helpers'
require 'rails/commands/console'
class Rails::ConsoleTest < ActiveSupport::TestCase
+ include EnvHelpers
+
class FakeConsole
def self.start; end
end
- def setup
- end
-
def test_sandbox_option
console = Rails::Console.new(app, parse_arguments(["--sandbox"]))
assert console.sandbox?
@@ -78,7 +78,14 @@ class Rails::ConsoleTest < ActiveSupport::TestCase
assert_match(/\sspecial-production\s/, output)
end
end
-
+
+ def test_default_environment_with_rack_env
+ with_rack_env 'production' do
+ start
+ assert_match(/\sproduction\s/, output)
+ end
+ end
+
def test_e_option
start ['-e', 'special-production']
assert_match(/\sspecial-production\s/, output)
@@ -126,12 +133,4 @@ class Rails::ConsoleTest < ActiveSupport::TestCase
def parse_arguments(args)
Rails::Console.parse_arguments(args)
end
-
- def with_rails_env(env)
- original_rails_env = ENV['RAILS_ENV']
- ENV['RAILS_ENV'] = env
- yield
- ensure
- ENV['RAILS_ENV'] = original_rails_env
- end
end
diff --git a/railties/test/commands/server_test.rb b/railties/test/commands/server_test.rb
index 4a3ea82e3d..cb57b3c0cd 100644
--- a/railties/test/commands/server_test.rb
+++ b/railties/test/commands/server_test.rb
@@ -1,7 +1,9 @@
require 'abstract_unit'
+require 'env_helpers'
require 'rails/commands/server'
class Rails::ServerTest < ActiveSupport::TestCase
+ include EnvHelpers
def test_environment_with_server_option
args = ["thin", "-e", "production"]
@@ -23,4 +25,18 @@ class Rails::ServerTest < ActiveSupport::TestCase
assert_nil options[:environment]
assert_equal 'thin', options[:server]
end
+
+ def test_environment_with_rails_env
+ with_rails_env 'production' do
+ server = Rails::Server.new
+ assert_equal 'production', server.options[:environment]
+ end
+ end
+
+ def test_environment_with_rack_env
+ with_rack_env 'production' do
+ server = Rails::Server.new
+ assert_equal 'production', server.options[:environment]
+ end
+ end
end
diff --git a/railties/test/env_helpers.rb b/railties/test/env_helpers.rb
new file mode 100644
index 0000000000..6223c85bbf
--- /dev/null
+++ b/railties/test/env_helpers.rb
@@ -0,0 +1,26 @@
+module EnvHelpers
+ private
+
+ def with_rails_env(env)
+ switch_env 'RAILS_ENV', env do
+ switch_env 'RACK_ENV', nil do
+ yield
+ end
+ end
+ end
+
+ def with_rack_env(env)
+ switch_env 'RACK_ENV', env do
+ switch_env 'RAILS_ENV', nil do
+ yield
+ end
+ end
+ end
+
+ def switch_env(key, value)
+ old, ENV[key] = ENV[key], value
+ yield
+ ensure
+ ENV[key] = old
+ end
+end
diff --git a/railties/test/generators/actions_test.rb b/railties/test/generators/actions_test.rb
index 8af92479c3..54734ed260 100644
--- a/railties/test/generators/actions_test.rb
+++ b/railties/test/generators/actions_test.rb
@@ -1,8 +1,11 @@
require 'generators/generators_test_helper'
require 'rails/generators/rails/app/app_generator'
+require 'env_helpers'
class ActionsTest < Rails::Generators::TestCase
include GeneratorsTestHelper
+ include EnvHelpers
+
tests Rails::Generators::AppGenerator
arguments [destination_root]
@@ -154,10 +157,9 @@ class ActionsTest < Rails::Generators::TestCase
def test_rake_should_run_rake_command_with_default_env
generator.expects(:run).once.with("rake log:clear RAILS_ENV=development", verbose: false)
- old_env, ENV['RAILS_ENV'] = ENV["RAILS_ENV"], nil
- action :rake, 'log:clear'
- ensure
- ENV["RAILS_ENV"] = old_env
+ with_rails_env nil do
+ action :rake, 'log:clear'
+ end
end
def test_rake_with_env_option_should_run_rake_command_in_env
@@ -167,26 +169,23 @@ class ActionsTest < Rails::Generators::TestCase
def test_rake_with_rails_env_variable_should_run_rake_command_in_env
generator.expects(:run).once.with('rake log:clear RAILS_ENV=production', verbose: false)
- old_env, ENV["RAILS_ENV"] = ENV["RAILS_ENV"], "production"
- action :rake, 'log:clear'
- ensure
- ENV["RAILS_ENV"] = old_env
+ with_rails_env "production" do
+ action :rake, 'log:clear'
+ end
end
def test_env_option_should_win_over_rails_env_variable_when_running_rake
generator.expects(:run).once.with('rake log:clear RAILS_ENV=production', verbose: false)
- old_env, ENV["RAILS_ENV"] = ENV["RAILS_ENV"], "staging"
- action :rake, 'log:clear', env: 'production'
- ensure
- ENV["RAILS_ENV"] = old_env
+ with_rails_env "staging" do
+ action :rake, 'log:clear', env: 'production'
+ end
end
def test_rake_with_sudo_option_should_run_rake_command_with_sudo
generator.expects(:run).once.with("sudo rake log:clear RAILS_ENV=development", verbose: false)
- old_env, ENV['RAILS_ENV'] = ENV["RAILS_ENV"], nil
- action :rake, 'log:clear', sudo: true
- ensure
- ENV["RAILS_ENV"] = old_env
+ with_rails_env nil do
+ action :rake, 'log:clear', sudo: true
+ end
end
def test_capify_should_run_the_capify_command
diff --git a/railties/test/generators/scaffold_controller_generator_test.rb b/railties/test/generators/scaffold_controller_generator_test.rb
index 8cacca668f..2a88dac635 100644
--- a/railties/test/generators/scaffold_controller_generator_test.rb
+++ b/railties/test/generators/scaffold_controller_generator_test.rb
@@ -20,17 +20,13 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase
assert_match(/@users = User\.all/, m)
end
- assert_instance_method :show, content do |m|
- assert_match(/@user = User\.find\(params\[:id\]\)/, m)
- end
+ assert_instance_method :show, content
assert_instance_method :new, content do |m|
assert_match(/@user = User\.new/, m)
end
- assert_instance_method :edit, content do |m|
- assert_match(/@user = User\.find\(params\[:id\]\)/, m)
- end
+ assert_instance_method :edit, content
assert_instance_method :create, content do |m|
assert_match(/@user = User\.new\(user_params\)/, m)
@@ -39,16 +35,18 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase
end
assert_instance_method :update, content do |m|
- assert_match(/@user = User\.find\(params\[:id\]\)/, m)
assert_match(/@user\.update_attributes\(user_params\)/, m)
assert_match(/@user\.errors/, m)
end
assert_instance_method :destroy, content do |m|
- assert_match(/@user = User\.find\(params\[:id\]\)/, m)
assert_match(/@user\.destroy/, m)
end
+ assert_instance_method :set_user, content do |m|
+ assert_match(/@user = User\.find\(params\[:id\]\)/, m)
+ end
+
assert_match(/def user_params/, content)
assert_match(/params\.require\(:user\)\.permit\(:name, :age\)/, content)
end
diff --git a/railties/test/generators/scaffold_generator_test.rb b/railties/test/generators/scaffold_generator_test.rb
index 54d5a9db6f..7fcc0a7409 100644
--- a/railties/test/generators/scaffold_generator_test.rb
+++ b/railties/test/generators/scaffold_generator_test.rb
@@ -30,17 +30,13 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
assert_match(/@product_lines = ProductLine\.all/, m)
end
- assert_instance_method :show, content do |m|
- assert_match(/@product_line = ProductLine\.find\(params\[:id\]\)/, m)
- end
+ assert_instance_method :show, content
assert_instance_method :new, content do |m|
assert_match(/@product_line = ProductLine\.new/, m)
end
- assert_instance_method :edit, content do |m|
- assert_match(/@product_line = ProductLine\.find\(params\[:id\]\)/, m)
- end
+ assert_instance_method :edit, content
assert_instance_method :create, content do |m|
assert_match(/@product_line = ProductLine\.new\(product_line_params\)/, m)
@@ -49,15 +45,17 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
end
assert_instance_method :update, content do |m|
- assert_match(/@product_line = ProductLine\.find\(params\[:id\]\)/, m)
assert_match(/@product_line\.update_attributes\(product_line_params\)/, m)
assert_match(/@product_line\.errors/, m)
end
assert_instance_method :destroy, content do |m|
- assert_match(/@product_line = ProductLine\.find\(params\[:id\]\)/, m)
assert_match(/@product_line\.destroy/, m)
end
+
+ assert_instance_method :set_product_line, content do |m|
+ assert_match(/@product_line = ProductLine\.find\(params\[:id\]\)/, m)
+ end
end
assert_file "test/controllers/product_lines_controller_test.rb" do |test|
@@ -149,17 +147,13 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
assert_match(/@admin_roles = Admin::Role\.all/, m)
end
- assert_instance_method :show, content do |m|
- assert_match(/@admin_role = Admin::Role\.find\(params\[:id\]\)/, m)
- end
+ assert_instance_method :show, content
assert_instance_method :new, content do |m|
assert_match(/@admin_role = Admin::Role\.new/, m)
end
- assert_instance_method :edit, content do |m|
- assert_match(/@admin_role = Admin::Role\.find\(params\[:id\]\)/, m)
- end
+ assert_instance_method :edit, content
assert_instance_method :create, content do |m|
assert_match(/@admin_role = Admin::Role\.new\(admin_role_params\)/, m)
@@ -168,15 +162,17 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
end
assert_instance_method :update, content do |m|
- assert_match(/@admin_role = Admin::Role\.find\(params\[:id\]\)/, m)
assert_match(/@admin_role\.update_attributes\(admin_role_params\)/, m)
assert_match(/@admin_role\.errors/, m)
end
assert_instance_method :destroy, content do |m|
- assert_match(/@admin_role = Admin::Role\.find\(params\[:id\]\)/, m)
assert_match(/@admin_role\.destroy/, m)
end
+
+ assert_instance_method :set_admin_role, content do |m|
+ assert_match(/@admin_role = Admin::Role\.find\(params\[:id\]\)/, m)
+ end
end
assert_file "test/controllers/admin/roles_controller_test.rb",