aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Gemfile.lock2
-rw-r--r--actionmailer/lib/action_mailer/base.rb30
-rw-r--r--actionmailer/lib/action_mailer/mail_helper.rb12
-rw-r--r--actionmailer/test/fixtures/base_mailer/email_custom_layout.text.html.erb1
-rw-r--r--actionmailer/test/fixtures/first_mailer/share.erb1
-rw-r--r--actionmailer/test/fixtures/path.with.dots/funky_path_mailer/multipart_with_template_path_with_dots.erb1
-rw-r--r--actionmailer/test/fixtures/second_mailer/share.erb1
-rw-r--r--actionmailer/test/fixtures/test_mailer/_subtemplate.text.erb1
-rw-r--r--actionmailer/test/fixtures/test_mailer/custom_templating_extension.html.haml6
-rw-r--r--actionmailer/test/fixtures/test_mailer/custom_templating_extension.text.haml6
-rw-r--r--actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.html.erb10
-rw-r--r--actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.html.erb~10
-rw-r--r--actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.ignored.erb1
-rw-r--r--actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.rhtml.bak1
-rw-r--r--actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.text.erb2
-rw-r--r--actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.yaml.erb1
-rw-r--r--actionmailer/test/fixtures/test_mailer/included_subtemplate.text.erb1
-rw-r--r--actionmailer/test/fixtures/test_mailer/multipart_alternative.html.erb1
-rw-r--r--actionmailer/test/fixtures/test_mailer/multipart_alternative.plain.erb1
-rw-r--r--actionmailer/test/fixtures/test_mailer/rxml_template.rxml2
-rw-r--r--actionmailer/test/fixtures/test_mailer/signed_up.html.erb3
-rw-r--r--actionpack/CHANGELOG.md15
-rw-r--r--actionpack/actionpack.gemspec2
-rw-r--r--actionpack/lib/abstract_controller/callbacks.rb4
-rw-r--r--actionpack/lib/action_controller/metal/strong_parameters.rb1
-rw-r--r--actionpack/lib/action_dispatch/http/response.rb8
-rw-r--r--actionpack/lib/action_dispatch/http/url.rb2
-rw-r--r--actionpack/lib/action_dispatch/journey/router.rb1
-rw-r--r--actionpack/lib/action_dispatch/middleware/session/cache_store.rb9
-rw-r--r--actionpack/lib/action_dispatch/middleware/session/cookie_store.rb10
-rw-r--r--actionpack/lib/action_dispatch/middleware/session/mem_cache_store.rb4
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/routes/_route.html.erb8
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb122
-rw-r--r--actionpack/lib/action_dispatch/routing/inspector.rb26
-rw-r--r--actionpack/lib/action_dispatch/routing/polymorphic_routes.rb18
-rw-r--r--actionpack/lib/action_dispatch/routing/url_for.rb6
-rw-r--r--actionpack/lib/action_dispatch/testing/integration.rb26
-rw-r--r--actionpack/lib/action_dispatch/testing/test_response.rb13
-rw-r--r--actionpack/test/controller/caching_test.rb58
-rw-r--r--actionpack/test/controller/filters_test.rb8
-rw-r--r--actionpack/test/controller/integration_test.rb34
-rw-r--r--actionpack/test/controller/test_case_test.rb46
-rw-r--r--actionpack/test/dispatch/response_test.rb6
-rw-r--r--actionpack/test/dispatch/routing/inspector_test.rb8
-rw-r--r--actionpack/test/dispatch/routing_test.rb17
-rw-r--r--actionpack/test/fixtures/collection_cache/index.html.erb1
-rw-r--r--actionpack/test/fixtures/customers/_commented_customer.html.erb4
-rw-r--r--actionpack/test/fixtures/customers/_customer.html.erb3
-rw-r--r--actionview/CHANGELOG.md30
-rw-r--r--actionview/lib/action_view/dependency_tracker.rb19
-rw-r--r--actionview/lib/action_view/helpers/cache_helper.rb31
-rw-r--r--actionview/lib/action_view/helpers/form_helper.rb3
-rw-r--r--actionview/lib/action_view/helpers/translation_helper.rb6
-rw-r--r--actionview/lib/action_view/railtie.rb6
-rw-r--r--actionview/lib/action_view/renderer/partial_renderer.rb8
-rw-r--r--actionview/lib/action_view/renderer/partial_renderer/collection_caching.rb70
-rw-r--r--actionview/lib/action_view/routing_url_for.rb6
-rw-r--r--actionview/lib/action_view/template.rb14
-rw-r--r--actionview/lib/action_view/template/handlers/erb.rb18
-rw-r--r--actionview/test/actionpack/controller/render_test.rb4
-rw-r--r--actionview/test/fixtures/test/_cached_customer.erb3
-rw-r--r--actionview/test/fixtures/test/_cached_customer_as.erb3
-rw-r--r--actionview/test/template/dependency_tracker_test.rb1
-rw-r--r--actionview/test/template/render_test.rb38
-rw-r--r--actionview/test/template/translation_helper_test.rb5
-rw-r--r--activejob/README.md4
-rw-r--r--activemodel/lib/active_model/errors.rb1
-rw-r--r--activerecord/CHANGELOG.md18
-rw-r--r--activerecord/lib/active_record/association_relation.rb13
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb2
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/transaction.rb11
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract_adapter.rb1
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb10
-rw-r--r--activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb9
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb4
-rw-r--r--activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb3
-rw-r--r--activerecord/lib/active_record/connection_handling.rb2
-rw-r--r--activerecord/lib/active_record/core.rb45
-rw-r--r--activerecord/lib/active_record/fixtures.rb4
-rw-r--r--activerecord/lib/active_record/persistence.rb3
-rw-r--r--activerecord/lib/active_record/railtie.rb3
-rw-r--r--activerecord/lib/active_record/relation/calculations.rb2
-rw-r--r--activerecord/lib/active_record/relation/finder_methods.rb1
-rw-r--r--activerecord/lib/active_record/transactions.rb77
-rw-r--r--activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb4
-rw-r--r--activerecord/test/cases/associations/has_many_associations_test.rb25
-rw-r--r--activerecord/test/cases/associations/has_many_through_associations_test.rb6
-rw-r--r--activerecord/test/cases/fixtures_test.rb20
-rw-r--r--activerecord/test/cases/transaction_callbacks_test.rb60
-rw-r--r--activerecord/test/schema/schema.rb1
-rw-r--r--activesupport/CHANGELOG.md10
-rw-r--r--activesupport/lib/active_support/cache.rb40
-rw-r--r--activesupport/lib/active_support/cache/mem_cache_store.rb17
-rw-r--r--activesupport/lib/active_support/core_ext/array/grouping.rb12
-rw-r--r--activesupport/lib/active_support/core_ext/enumerable.rb11
-rw-r--r--activesupport/lib/active_support/core_ext/module/anonymous.rb7
-rw-r--r--activesupport/lib/active_support/core_ext/module/delegation.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/range/conversions.rb19
-rw-r--r--activesupport/lib/active_support/core_ext/string/filters.rb7
-rw-r--r--activesupport/lib/active_support/core_ext/string/multibyte.rb7
-rw-r--r--activesupport/test/caching_test.rb9
-rw-r--r--activesupport/test/core_ext/enumerable_test.rb7
-rw-r--r--activesupport/test/core_ext/string_ext_test.rb9
-rw-r--r--guides/Rakefile2
-rw-r--r--guides/rails_guides/levenshtein.rb2
-rw-r--r--guides/source/4_0_release_notes.md4
-rw-r--r--guides/source/4_1_release_notes.md18
-rw-r--r--guides/source/active_record_validations.md4
-rw-r--r--guides/source/active_support_core_extensions.md17
-rw-r--r--guides/source/active_support_instrumentation.md4
-rw-r--r--guides/source/asset_pipeline.md21
-rw-r--r--guides/source/association_basics.md2
-rw-r--r--guides/source/caching_with_rails.md2
-rw-r--r--guides/source/command_line.md6
-rw-r--r--guides/source/debugging_rails_applications.md113
-rw-r--r--guides/source/form_helpers.md2
-rw-r--r--guides/source/getting_started.md15
-rw-r--r--guides/source/i18n.md7
-rw-r--r--guides/source/layouts_and_rendering.md36
-rw-r--r--guides/source/routing.md2
-rw-r--r--guides/source/testing.md1
-rw-r--r--railties/CHANGELOG.md14
-rw-r--r--railties/lib/rails/code_statistics.rb8
-rw-r--r--railties/lib/rails/info_controller.rb25
-rw-r--r--railties/lib/rails/paths.rb2
-rw-r--r--railties/lib/rails/tasks.rb1
-rw-r--r--railties/lib/rails/tasks/restart.rake4
-rw-r--r--railties/test/application/rake/restart_test.rb31
-rw-r--r--railties/test/rails_info_controller_test.rb25
129 files changed, 1206 insertions, 467 deletions
diff --git a/Gemfile.lock b/Gemfile.lock
index d2ed998160..4fc36bf86c 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -41,7 +41,7 @@ PATH
actionview (= 5.0.0.alpha)
activesupport (= 5.0.0.alpha)
rack (~> 1.6)
- rack-test (~> 0.6.2)
+ rack-test (~> 0.6.3)
rails-dom-testing (~> 1.0, >= 1.0.5)
rails-html-sanitizer (~> 1.0, >= 1.0.1)
actionview (5.0.0.alpha)
diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb
index 7eae76f93b..3e5125f72e 100644
--- a/actionmailer/lib/action_mailer/base.rb
+++ b/actionmailer/lib/action_mailer/base.rb
@@ -25,7 +25,7 @@ module ActionMailer
# layout 'mailer'
# end
#
- # class Notifier < ApplicationMailer
+ # class NotifierMailer < ApplicationMailer
# default from: 'no-reply@example.com',
# return_path: 'system@example.com'
#
@@ -88,7 +88,7 @@ module ActionMailer
#
# To define a template to be used with a mailing, create an <tt>.erb</tt> file with the same
# name as the method in your mailer model. For example, in the mailer defined above, the template at
- # <tt>app/views/notifier/welcome.text.erb</tt> would be used to generate the email.
+ # <tt>app/views/notifier_mailer/welcome.text.erb</tt> would be used to generate the email.
#
# Variables defined in the methods of your mailer model are accessible as instance variables in their
# corresponding view.
@@ -137,20 +137,20 @@ module ActionMailer
# Once a mailer action and template are defined, you can deliver your message or create it and save it
# for delivery later:
#
- # Notifier.welcome(User.first).deliver_now # sends the email
- # mail = Notifier.welcome(User.first) # => an ActionMailer::MessageDelivery object
+ # NotifierMailer.welcome(User.first).deliver_now # sends the email
+ # mail = NotifierMailer.welcome(User.first) # => an ActionMailer::MessageDelivery object
# mail.deliver_now # sends the email
#
# The <tt>ActionMailer::MessageDelivery</tt> class is a wrapper around a <tt>Mail::Message</tt> object. If
# you want direct access to the <tt>Mail::Message</tt> object you can call the <tt>message</tt> method on
# the <tt>ActionMailer::MessageDelivery</tt> object.
#
- # Notifier.welcome(User.first).message # => a Mail::Message object
+ # NotifierMailer.welcome(User.first).message # => a Mail::Message object
#
# Action Mailer is nicely integrated with Active Job so you can send emails in the background (example: outside
# of the request-response cycle, so the user doesn't have to wait on it):
#
- # Notifier.welcome(User.first).deliver_later # enqueue the email sending to Active Job
+ # NotifierMailer.welcome(User.first).deliver_later # enqueue the email sending to Active Job
#
# You never instantiate your mailer class. Rather, you just call the method you defined on the class itself.
#
@@ -179,7 +179,7 @@ module ActionMailer
#
# Sending attachment in emails is easy:
#
- # class Notifier < ApplicationMailer
+ # class NotifierMailer < ApplicationMailer
# def welcome(recipient)
# attachments['free_book.pdf'] = File.read('path/to/file.pdf')
# mail(to: recipient, subject: "New account information")
@@ -195,7 +195,7 @@ module ActionMailer
# If you need to send attachments with no content, you need to create an empty view for it,
# or add an empty body parameter like this:
#
- # class Notifier < ApplicationMailer
+ # class NotifierMailer < ApplicationMailer
# def welcome(recipient)
# attachments['free_book.pdf'] = File.read('path/to/file.pdf')
# mail(to: recipient, subject: "New account information", body: "")
@@ -207,7 +207,7 @@ module ActionMailer
# You can also specify that a file should be displayed inline with other HTML. This is useful
# if you want to display a corporate logo or a photo.
#
- # class Notifier < ApplicationMailer
+ # class NotifierMailer < ApplicationMailer
# def welcome(recipient)
# attachments.inline['photo.png'] = File.read('path/to/photo.png')
# mail(to: recipient, subject: "Here is what we look like")
@@ -246,7 +246,7 @@ module ActionMailer
# Action Mailer provides some intelligent defaults for your emails, these are usually specified in a
# default method inside the class definition:
#
- # class Notifier < ApplicationMailer
+ # class NotifierMailer < ApplicationMailer
# default sender: 'system@example.com'
# end
#
@@ -264,7 +264,7 @@ module ActionMailer
# As you can pass in any header, you need to either quote the header as a string, or pass it in as
# an underscored symbol, so the following will work:
#
- # class Notifier < ApplicationMailer
+ # class NotifierMailer < ApplicationMailer
# default 'Content-Transfer-Encoding' => '7bit',
# content_description: 'This is a description'
# end
@@ -272,7 +272,7 @@ module ActionMailer
# Finally, Action Mailer also supports passing <tt>Proc</tt> objects into the default hash, so you
# can define methods that evaluate as the message is being generated:
#
- # class Notifier < ApplicationMailer
+ # class NotifierMailer < ApplicationMailer
# default 'X-Special-Header' => Proc.new { my_method }
#
# private
@@ -297,7 +297,7 @@ module ActionMailer
# This may be useful, for example, when you want to add default inline attachments for all
# messages sent out by a certain mailer class:
#
- # class Notifier < ApplicationMailer
+ # class NotifierMailer < ApplicationMailer
# before_action :add_inline_attachment!
#
# def welcome
@@ -325,9 +325,9 @@ module ActionMailer
# <tt>ActionMailer::Base.preview_path</tt>. Since most emails do something interesting
# with database data, you'll need to write some scenarios to load messages with fake data:
#
- # class NotifierPreview < ActionMailer::Preview
+ # class NotifierMailerPreview < ActionMailer::Preview
# def welcome
- # Notifier.welcome(User.first)
+ # NotifierMailer.welcome(User.first)
# end
# end
#
diff --git a/actionmailer/lib/action_mailer/mail_helper.rb b/actionmailer/lib/action_mailer/mail_helper.rb
index 227192f48d..239974e7b1 100644
--- a/actionmailer/lib/action_mailer/mail_helper.rb
+++ b/actionmailer/lib/action_mailer/mail_helper.rb
@@ -4,7 +4,17 @@ module ActionMailer
# attachments list.
module MailHelper
# Take the text and format it, indented two spaces for each line, and
- # wrapped at 72 columns.
+ # wrapped at 72 columns:
+ #
+ # text = <<-TEXT
+ # This is
+ # the paragraph.
+ #
+ # * item1 * item2
+ # TEXT
+ #
+ # block_format text
+ # # => " This is the paragraph.\n\n * item1\n * item2\n"
def block_format(text)
formatted = text.split(/\n\r?\n/).collect { |paragraph|
format_paragraph(paragraph)
diff --git a/actionmailer/test/fixtures/base_mailer/email_custom_layout.text.html.erb b/actionmailer/test/fixtures/base_mailer/email_custom_layout.text.html.erb
deleted file mode 100644
index a2187308b6..0000000000
--- a/actionmailer/test/fixtures/base_mailer/email_custom_layout.text.html.erb
+++ /dev/null
@@ -1 +0,0 @@
-body_text \ No newline at end of file
diff --git a/actionmailer/test/fixtures/first_mailer/share.erb b/actionmailer/test/fixtures/first_mailer/share.erb
deleted file mode 100644
index da43638ceb..0000000000
--- a/actionmailer/test/fixtures/first_mailer/share.erb
+++ /dev/null
@@ -1 +0,0 @@
-first mail
diff --git a/actionmailer/test/fixtures/path.with.dots/funky_path_mailer/multipart_with_template_path_with_dots.erb b/actionmailer/test/fixtures/path.with.dots/funky_path_mailer/multipart_with_template_path_with_dots.erb
deleted file mode 100644
index 2d0cd5c124..0000000000
--- a/actionmailer/test/fixtures/path.with.dots/funky_path_mailer/multipart_with_template_path_with_dots.erb
+++ /dev/null
@@ -1 +0,0 @@
-Have some dots. Enjoy! \ No newline at end of file
diff --git a/actionmailer/test/fixtures/second_mailer/share.erb b/actionmailer/test/fixtures/second_mailer/share.erb
deleted file mode 100644
index 9a54010672..0000000000
--- a/actionmailer/test/fixtures/second_mailer/share.erb
+++ /dev/null
@@ -1 +0,0 @@
-second mail
diff --git a/actionmailer/test/fixtures/test_mailer/_subtemplate.text.erb b/actionmailer/test/fixtures/test_mailer/_subtemplate.text.erb
deleted file mode 100644
index 3b4ba35f20..0000000000
--- a/actionmailer/test/fixtures/test_mailer/_subtemplate.text.erb
+++ /dev/null
@@ -1 +0,0 @@
-let's go! \ No newline at end of file
diff --git a/actionmailer/test/fixtures/test_mailer/custom_templating_extension.html.haml b/actionmailer/test/fixtures/test_mailer/custom_templating_extension.html.haml
deleted file mode 100644
index 8dcf9746cc..0000000000
--- a/actionmailer/test/fixtures/test_mailer/custom_templating_extension.html.haml
+++ /dev/null
@@ -1,6 +0,0 @@
-%p Hello there,
-
-%p
- Mr.
- = @recipient
- from haml \ No newline at end of file
diff --git a/actionmailer/test/fixtures/test_mailer/custom_templating_extension.text.haml b/actionmailer/test/fixtures/test_mailer/custom_templating_extension.text.haml
deleted file mode 100644
index 8dcf9746cc..0000000000
--- a/actionmailer/test/fixtures/test_mailer/custom_templating_extension.text.haml
+++ /dev/null
@@ -1,6 +0,0 @@
-%p Hello there,
-
-%p
- Mr.
- = @recipient
- from haml \ No newline at end of file
diff --git a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.html.erb b/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.html.erb
deleted file mode 100644
index 946d99ede5..0000000000
--- a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.html.erb
+++ /dev/null
@@ -1,10 +0,0 @@
-<html>
- <body>
- HTML formatted message to <strong><%= @recipient %></strong>.
- </body>
-</html>
-<html>
- <body>
- HTML formatted message to <strong><%= @recipient %></strong>.
- </body>
-</html>
diff --git a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.html.erb~ b/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.html.erb~
deleted file mode 100644
index 946d99ede5..0000000000
--- a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.html.erb~
+++ /dev/null
@@ -1,10 +0,0 @@
-<html>
- <body>
- HTML formatted message to <strong><%= @recipient %></strong>.
- </body>
-</html>
-<html>
- <body>
- HTML formatted message to <strong><%= @recipient %></strong>.
- </body>
-</html>
diff --git a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.ignored.erb b/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.ignored.erb
deleted file mode 100644
index 6940419d47..0000000000
--- a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.ignored.erb
+++ /dev/null
@@ -1 +0,0 @@
-Ignored when searching for implicitly multipart parts.
diff --git a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.rhtml.bak b/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.rhtml.bak
deleted file mode 100644
index 6940419d47..0000000000
--- a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.rhtml.bak
+++ /dev/null
@@ -1 +0,0 @@
-Ignored when searching for implicitly multipart parts.
diff --git a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.text.erb b/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.text.erb
deleted file mode 100644
index a6c8d54cf9..0000000000
--- a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.text.erb
+++ /dev/null
@@ -1,2 +0,0 @@
-Plain text to <%= @recipient %>.
-Plain text to <%= @recipient %>.
diff --git a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.yaml.erb b/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.yaml.erb
deleted file mode 100644
index c14348c770..0000000000
--- a/actionmailer/test/fixtures/test_mailer/implicitly_multipart_example.yaml.erb
+++ /dev/null
@@ -1 +0,0 @@
-yaml to: <%= @recipient %> \ No newline at end of file
diff --git a/actionmailer/test/fixtures/test_mailer/included_subtemplate.text.erb b/actionmailer/test/fixtures/test_mailer/included_subtemplate.text.erb
deleted file mode 100644
index ae3cfa77e7..0000000000
--- a/actionmailer/test/fixtures/test_mailer/included_subtemplate.text.erb
+++ /dev/null
@@ -1 +0,0 @@
-Hey Ho, <%= render partial: "subtemplate" %> \ No newline at end of file
diff --git a/actionmailer/test/fixtures/test_mailer/multipart_alternative.html.erb b/actionmailer/test/fixtures/test_mailer/multipart_alternative.html.erb
deleted file mode 100644
index 73ea14f82f..0000000000
--- a/actionmailer/test/fixtures/test_mailer/multipart_alternative.html.erb
+++ /dev/null
@@ -1 +0,0 @@
-<strong>foo</strong> <%= @foo %> \ No newline at end of file
diff --git a/actionmailer/test/fixtures/test_mailer/multipart_alternative.plain.erb b/actionmailer/test/fixtures/test_mailer/multipart_alternative.plain.erb
deleted file mode 100644
index 779fe4c1ea..0000000000
--- a/actionmailer/test/fixtures/test_mailer/multipart_alternative.plain.erb
+++ /dev/null
@@ -1 +0,0 @@
-foo: <%= @foo %> \ No newline at end of file
diff --git a/actionmailer/test/fixtures/test_mailer/rxml_template.rxml b/actionmailer/test/fixtures/test_mailer/rxml_template.rxml
deleted file mode 100644
index d566bd8d7c..0000000000
--- a/actionmailer/test/fixtures/test_mailer/rxml_template.rxml
+++ /dev/null
@@ -1,2 +0,0 @@
-xml.instruct!
-xml.test \ No newline at end of file
diff --git a/actionmailer/test/fixtures/test_mailer/signed_up.html.erb b/actionmailer/test/fixtures/test_mailer/signed_up.html.erb
deleted file mode 100644
index 7afe1f651c..0000000000
--- a/actionmailer/test/fixtures/test_mailer/signed_up.html.erb
+++ /dev/null
@@ -1,3 +0,0 @@
-Hello there,
-
-Mr. <%= @recipient %> \ No newline at end of file
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md
index 8685cd6495..0134bf7cab 100644
--- a/actionpack/CHANGELOG.md
+++ b/actionpack/CHANGELOG.md
@@ -1,3 +1,10 @@
+* Fix regression in functional tests. Responses should have default headers
+ assigned.
+
+ See #18423.
+
+ *Jeremy Kemper*, *Yves Senn*
+
* Deprecate AbstractController#skip_action_callback in favor of individual skip_callback methods
(which can be made to raise an error if no callback was removed).
@@ -9,6 +16,14 @@
*David Ilizarov*
+* Change filter on /rails/info/routes to use an actual path regexp from rails
+ and not approximate javascript version. Oniguruma supports much more
+ extensive list of features than javascript regexp engine.
+
+ Fixes #18402.
+
+ *Ravil Bayramgalin*
+
* Non-string authenticity tokens do not raise NoMethodError when decoding
the masked token.
diff --git a/actionpack/actionpack.gemspec b/actionpack/actionpack.gemspec
index d9b23ad4a9..d907001bd6 100644
--- a/actionpack/actionpack.gemspec
+++ b/actionpack/actionpack.gemspec
@@ -22,7 +22,7 @@ Gem::Specification.new do |s|
s.add_dependency 'activesupport', version
s.add_dependency 'rack', '~> 1.6'
- s.add_dependency 'rack-test', '~> 0.6.2'
+ s.add_dependency 'rack-test', '~> 0.6.3'
s.add_dependency 'rails-html-sanitizer', '~> 1.0', '>= 1.0.1'
s.add_dependency 'rails-dom-testing', '~> 1.0', '>= 1.0.5'
s.add_dependency 'actionview', version
diff --git a/actionpack/lib/abstract_controller/callbacks.rb b/actionpack/lib/abstract_controller/callbacks.rb
index f4fd1db36c..59ffb0a19e 100644
--- a/actionpack/lib/abstract_controller/callbacks.rb
+++ b/actionpack/lib/abstract_controller/callbacks.rb
@@ -1,5 +1,3 @@
-require 'active_support/deprecation'
-
module AbstractController
module Callbacks
extend ActiveSupport::Concern
@@ -70,7 +68,7 @@ module AbstractController
end
def skip_filter(*names)
- ActiveSupport::Deprecation.warn("#{callback}_filter is deprecated and will be removed in Rails 5.1. Use #{callback}_action instead.")
+ ActiveSupport::Deprecation.warn("`skip_filter` is deprecated and will be removed in Rails 5.1. Use skip_before_action, skip_after_action or skip_around_action instead.")
skip_action_callback(*names)
end
diff --git a/actionpack/lib/action_controller/metal/strong_parameters.rb b/actionpack/lib/action_controller/metal/strong_parameters.rb
index 01bbd749c1..f19c4201ba 100644
--- a/actionpack/lib/action_controller/metal/strong_parameters.rb
+++ b/actionpack/lib/action_controller/metal/strong_parameters.rb
@@ -1,7 +1,6 @@
require 'active_support/core_ext/hash/indifferent_access'
require 'active_support/core_ext/array/wrap'
require 'active_support/core_ext/string/filters'
-require 'active_support/deprecation'
require 'active_support/rescuable'
require 'action_dispatch/http/upload'
require 'stringio'
diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb
index 4061ea71a3..a895d1ab18 100644
--- a/actionpack/lib/action_dispatch/http/response.rb
+++ b/actionpack/lib/action_dispatch/http/response.rb
@@ -113,10 +113,10 @@ module ActionDispatch # :nodoc:
# The underlying body, as a streamable object.
attr_reader :stream
- def initialize(status = 200, header = {}, body = [])
+ def initialize(status = 200, header = {}, body = [], default_headers: self.class.default_headers)
super()
- header = merge_default_headers(header, self.class.default_headers)
+ header = merge_default_headers(header, default_headers)
self.body, self.header, self.status = body, header, status
@@ -308,9 +308,7 @@ module ActionDispatch # :nodoc:
end
def merge_default_headers(original, default)
- return original unless default.respond_to?(:merge)
-
- default.merge(original)
+ default.respond_to?(:merge) ? default.merge(original) : original
end
def build_buffer(response, body)
diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb
index 001b14ec97..7da6301ac4 100644
--- a/actionpack/lib/action_dispatch/http/url.rb
+++ b/actionpack/lib/action_dispatch/http/url.rb
@@ -67,7 +67,7 @@ module ActionDispatch
end
def path_for(options)
- path = options[:script_name].to_s.chomp("/")
+ path = options[:script_name].to_s.chomp("/".freeze)
path << options[:path] if options.key?(:path)
add_trailing_slash(path) if options[:trailing_slash]
diff --git a/actionpack/lib/action_dispatch/journey/router.rb b/actionpack/lib/action_dispatch/journey/router.rb
index e9df984c86..2b036796ab 100644
--- a/actionpack/lib/action_dispatch/journey/router.rb
+++ b/actionpack/lib/action_dispatch/journey/router.rb
@@ -121,7 +121,6 @@ module ActionDispatch
end
def match_head_routes(routes, req)
- routes.delete_if { |route| route.verb == // }
head_routes = match_routes(routes, req)
if head_routes.empty?
diff --git a/actionpack/lib/action_dispatch/middleware/session/cache_store.rb b/actionpack/lib/action_dispatch/middleware/session/cache_store.rb
index 625050dc4b..857e49a682 100644
--- a/actionpack/lib/action_dispatch/middleware/session/cache_store.rb
+++ b/actionpack/lib/action_dispatch/middleware/session/cache_store.rb
@@ -2,12 +2,15 @@ require 'action_dispatch/middleware/session/abstract_store'
module ActionDispatch
module Session
- # Session store that uses an ActiveSupport::Cache::Store to store the sessions. This store is most useful
+ # A session store that uses an ActiveSupport::Cache::Store to store the sessions. This store is most useful
# if you don't store critical data in your sessions and you don't need them to live for extended periods
# of time.
+ #
+ # ==== Options
+ # * <tt>cache</tt> - The cache to use. If it is not specified, <tt>Rails.cache</tt> will be used.
+ # * <tt>expire_after</tt> - The length of time a session will be stored before automatically expiring.
+ # By default, the <tt>:expires_in</tt> option of the cache is used.
class CacheStore < AbstractStore
- # Create a new store. The cache to use can be passed in the <tt>:cache</tt> option. If it is
- # not specified, <tt>Rails.cache</tt> will be used.
def initialize(app, options = {})
@cache = options[:cache] || Rails.cache
options[:expire_after] ||= @cache.options[:expires_in]
diff --git a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb
index ed25c67ae5..d8f9614904 100644
--- a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb
+++ b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb
@@ -52,6 +52,16 @@ module ActionDispatch
# JavaScript before upgrading.
#
# Note that changing the secret key will invalidate all existing sessions!
+ #
+ # Because CookieStore extends Rack::Session::Abstract::ID, many of the
+ # options described there can be used to customize the session cookie that
+ # is generated. For example:
+ #
+ # Rails.application.config.session_store :cookie_store, expire_after: 14.days
+ #
+ # would set the session cookie to expire automatically 14 days after creation.
+ # Other useful options include <tt>:key</tt>, <tt>:secure</tt> and
+ # <tt>:httponly</tt>.
class CookieStore < Rack::Session::Abstract::ID
include Compatibility
include StaleSessionCheck
diff --git a/actionpack/lib/action_dispatch/middleware/session/mem_cache_store.rb b/actionpack/lib/action_dispatch/middleware/session/mem_cache_store.rb
index b4d6629c35..cb19786f0b 100644
--- a/actionpack/lib/action_dispatch/middleware/session/mem_cache_store.rb
+++ b/actionpack/lib/action_dispatch/middleware/session/mem_cache_store.rb
@@ -8,6 +8,10 @@ end
module ActionDispatch
module Session
+ # A session store that uses MemCache to implement storage.
+ #
+ # ==== Options
+ # * <tt>expire_after</tt> - The length of time a session will be stored before automatically expiring.
class MemCacheStore < Rack::Session::Dalli
include Compatibility
include StaleSessionCheck
diff --git a/actionpack/lib/action_dispatch/middleware/templates/routes/_route.html.erb b/actionpack/lib/action_dispatch/middleware/templates/routes/_route.html.erb
index 24e44f31ac..6e995c85c1 100644
--- a/actionpack/lib/action_dispatch/middleware/templates/routes/_route.html.erb
+++ b/actionpack/lib/action_dispatch/middleware/templates/routes/_route.html.erb
@@ -4,13 +4,13 @@
<%= route[:name] %><span class='helper'>_path</span>
<% end %>
</td>
- <td data-route-verb='<%= route[:verb] %>'>
+ <td>
<%= route[:verb] %>
</td>
- <td data-route-path='<%= route[:path] %>' data-regexp='<%= route[:regexp] %>'>
+ <td data-route-path='<%= route[:path] %>'>
<%= route[:path] %>
</td>
- <td data-route-reqs='<%= route[:reqs] %>'>
- <%= route[:reqs] %>
+ <td>
+ <%=simple_format route[:reqs] %>
</td>
</tr>
diff --git a/actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb b/actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb
index 5cee0b5932..429ea7057c 100644
--- a/actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb
+++ b/actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb
@@ -81,92 +81,87 @@
</table>
<script type='text/javascript'>
- // Iterates each element through a function
- function each(elems, func) {
- if (!elems instanceof Array) { elems = [elems]; }
- for (var i = 0, len = elems.length; i < len; i++) {
- func(elems[i]);
- }
- }
-
- // Sets innerHTML for an element
- function setContent(elem, text) {
- elem.innerHTML = text;
- }
+ // support forEarch iterator on NodeList
+ NodeList.prototype.forEach = Array.prototype.forEach;
// Enables path search functionality
function setupMatchPaths() {
- // Check if the user input (sanitized as a path) matches the regexp data attribute
- function checkExactMatch(section, elem, value) {
- var string = sanitizePath(value),
- regexp = elem.getAttribute("data-regexp");
-
- showMatch(string, regexp, section, elem);
+ // Check if there are any matched results in a section
+ function checkNoMatch(section, noMatchText) {
+ if (section.children.length <= 1) {
+ section.innerHTML += noMatchText;
+ }
}
- // Check if the route path data attribute contains the user input
- function checkFuzzyMatch(section, elem, value) {
- var string = elem.getAttribute("data-route-path"),
- regexp = value;
-
- showMatch(string, regexp, section, elem);
+ // get JSON from url and invoke callback with result
+ function getJSON(url, success) {
+ var xhr = new XMLHttpRequest();
+ xhr.open('GET', url);
+ xhr.onload = function() {
+ if (this.status == 200)
+ success(JSON.parse(this.response));
+ };
+ xhr.send();
}
- // Display the parent <tr> element in the appropriate section when there's a match
- function showMatch(string, regexp, section, elem) {
- if(string.match(RegExp(regexp))) {
- section.appendChild(elem.parentNode.cloneNode(true));
+ function delayedKeyup(input, callback) {
+ var timeout;
+ input.onkeyup = function(){
+ if (timeout) clearTimeout(timeout);
+ timeout = setTimeout(callback, 300);
}
}
- // Check if there are any matched results in a section
- function checkNoMatch(section, defaultText, noMatchText) {
- if (section.innerHTML === defaultText) {
- setContent(section, defaultText + noMatchText);
- }
- }
-
- // Ensure path always starts with a slash "/" and remove params or fragments
+ // remove params or fragments
function sanitizePath(path) {
- var path = path.charAt(0) == '/' ? path : "/" + path;
- return path.replace(/\#.*|\?.*/, '');
+ return path.replace(/[#?].*/, '');
}
- var regexpElems = document.querySelectorAll('#route_table [data-regexp]'),
- searchElem = document.querySelector('#search'),
- exactMatches = document.querySelector('#exact_matches'),
- fuzzyMatches = document.querySelector('#fuzzy_matches');
+ var pathElements = document.querySelectorAll('#route_table [data-route-path]'),
+ searchElem = document.querySelector('#search'),
+ exactSection = document.querySelector('#exact_matches'),
+ fuzzySection = document.querySelector('#fuzzy_matches');
// Remove matches when no search value is present
searchElem.onblur = function(e) {
if (searchElem.value === "") {
- setContent(exactMatches, "");
- setContent(fuzzyMatches, "");
+ exactSection.innerHTML = "";
+ fuzzySection.innerHTML = "";
}
}
// On key press perform a search for matching paths
- searchElem.onkeyup = function(e){
- var userInput = searchElem.value,
- defaultExactMatch = '<tr><th colspan="4">Paths Matching (' + escape(sanitizePath(userInput)) +'):</th></tr>',
- defaultFuzzyMatch = '<tr><th colspan="4">Paths Containing (' + escape(userInput) +'):</th></tr>',
+ delayedKeyup(searchElem, function() {
+ var path = sanitizePath(searchElem.value),
+ defaultExactMatch = '<tr><th colspan="4">Paths Matching (' + path +'):</th></tr>',
+ defaultFuzzyMatch = '<tr><th colspan="4">Paths Containing (' + path +'):</th></tr>',
noExactMatch = '<tr><th colspan="4">No Exact Matches Found</th></tr>',
noFuzzyMatch = '<tr><th colspan="4">No Fuzzy Matches Found</th></tr>';
- // Clear out results section
- setContent(exactMatches, defaultExactMatch);
- setContent(fuzzyMatches, defaultFuzzyMatch);
+ if (!path)
+ return searchElem.onblur();
- // Display exact matches and fuzzy matches
- each(regexpElems, function(elem) {
- checkExactMatch(exactMatches, elem, userInput);
- checkFuzzyMatch(fuzzyMatches, elem, userInput);
- })
+ getJSON('/rails/info/routes?path=' + path, function(matches){
+ // Clear out results section
+ exactSection.innerHTML = defaultExactMatch;
+ fuzzySection.innerHTML = defaultFuzzyMatch;
- // Display 'No Matches' message when no matches are found
- checkNoMatch(exactMatches, defaultExactMatch, noExactMatch);
- checkNoMatch(fuzzyMatches, defaultFuzzyMatch, noFuzzyMatch);
- }
+ // Display exact matches and fuzzy matches
+ pathElements.forEach(function(elem) {
+ var elemPath = elem.getAttribute('data-route-path');
+
+ if (matches['exact'].indexOf(elemPath) != -1)
+ exactSection.appendChild(elem.parentNode.cloneNode(true));
+
+ if (matches['fuzzy'].indexOf(elemPath) != -1)
+ fuzzySection.appendChild(elem.parentNode.cloneNode(true));
+ })
+
+ // Display 'No Matches' message when no matches are found
+ checkNoMatch(exactSection, noExactMatch);
+ checkNoMatch(fuzzySection, noFuzzyMatch);
+ })
+ })
}
// Enables functionality to toggle between `_path` and `_url` helper suffixes
@@ -174,19 +169,20 @@
// Sets content for each element
function setValOn(elems, val) {
- each(elems, function(elem) {
- setContent(elem, val);
+ elems.forEach(function(elem) {
+ elem.innerHTML = val;
});
}
// Sets onClick event for each element
function onClick(elems, func) {
- each(elems, function(elem) {
+ elems.forEach(function(elem) {
elem.onclick = func;
});
}
var toggleLinks = document.querySelectorAll('#route_table [data-route-helper]');
+
onClick(toggleLinks, function(){
var helperTxt = this.getAttribute("data-route-helper"),
helperElems = document.querySelectorAll('[data-route-name] span.helper');
diff --git a/actionpack/lib/action_dispatch/routing/inspector.rb b/actionpack/lib/action_dispatch/routing/inspector.rb
index df5ebb6751..c513737fc2 100644
--- a/actionpack/lib/action_dispatch/routing/inspector.rb
+++ b/actionpack/lib/action_dispatch/routing/inspector.rb
@@ -28,23 +28,6 @@ module ActionDispatch
super.to_s
end
- def regexp
- __getobj__.path.to_regexp
- end
-
- def json_regexp
- str = regexp.inspect.
- sub('\\A' , '^').
- sub('\\Z' , '$').
- sub('\\z' , '$').
- sub(/^\// , '').
- sub(/\/[a-z]*$/ , '').
- gsub(/\(\?#.+\)/ , '').
- gsub(/\(\?-\w+:/ , '(').
- gsub(/\s/ , '')
- Regexp.new(str).source
- end
-
def reqs
@reqs ||= begin
reqs = endpoint
@@ -117,11 +100,10 @@ module ActionDispatch
end.reject(&:internal?).collect do |route|
collect_engine_routes(route)
- { name: route.name,
- verb: route.verb,
- path: route.path,
- reqs: route.reqs,
- regexp: route.json_regexp }
+ { name: route.name,
+ verb: route.verb,
+ path: route.path,
+ reqs: route.reqs }
end
end
diff --git a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
index 2e116ea9cd..9934f5547a 100644
--- a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
+++ b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
@@ -247,14 +247,12 @@ module ActionDispatch
args = []
model = record.to_model
- name = if model.persisted?
- args << model
- model.model_name.singular_route_key
- else
- @key_strategy.call model.model_name
- end
-
- named_route = prefix + "#{name}_#{suffix}"
+ named_route = if model.persisted?
+ args << model
+ get_method_for_string model.model_name.singular_route_key
+ else
+ get_method_for_class model
+ end
[named_route, args]
end
@@ -309,11 +307,11 @@ module ActionDispatch
def get_method_for_class(klass)
name = @key_strategy.call klass.model_name
- prefix + "#{name}_#{suffix}"
+ get_method_for_string name
end
def get_method_for_string(str)
- prefix + "#{str}_#{suffix}"
+ "#{prefix}#{str}_#{suffix}"
end
[nil, 'new', 'edit'].each do |action|
diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb
index dca86858cc..eb554ec383 100644
--- a/actionpack/lib/action_dispatch/routing/url_for.rb
+++ b/actionpack/lib/action_dispatch/routing/url_for.rb
@@ -184,12 +184,6 @@ module ActionDispatch
def _routes_context
self
end
-
- private
-
- def _generate_paths_by_default
- true
- end
end
end
end
diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb
index 9b00616968..f7f898288b 100644
--- a/actionpack/lib/action_dispatch/testing/integration.rb
+++ b/actionpack/lib/action_dispatch/testing/integration.rb
@@ -369,7 +369,7 @@ module ActionDispatch
@request_count += 1
@request = ActionDispatch::Request.new(session.last_request.env)
response = _mock_session.last_response
- @response = ActionDispatch::TestResponse.new(response.status, response.headers, response.body)
+ @response = ActionDispatch::TestResponse.from_response(response)
@html_document = nil
@url_options = nil
@@ -388,16 +388,8 @@ module ActionDispatch
APP_SESSIONS = {}
- attr_reader :app
-
- def before_setup
- super
- @app = nil
- @integration_session = nil
- end
-
- def integration_session
- @integration_session ||= create_session(app)
+ def app
+ @app ||= nil
end
# Reset the current session. This is useful for testing multiple sessions
@@ -425,6 +417,8 @@ module ActionDispatch
%w(get post patch put head delete cookies assigns
xml_http_request xhr get_via_redirect post_via_redirect).each do |method|
define_method(method) do |*args|
+ reset! unless integration_session
+
# reset the html_document variable, except for cookies/assigns calls
unless method == 'cookies' || method == 'assigns'
@html_document = nil
@@ -456,16 +450,19 @@ module ActionDispatch
# Copy the instance variables from the current session instance into the
# test instance.
def copy_session_variables! #:nodoc:
+ return unless integration_session
@controller = @integration_session.controller
@response = @integration_session.response
@request = @integration_session.request
end
def default_url_options
+ reset! unless integration_session
integration_session.default_url_options
end
def default_url_options=(options)
+ reset! unless integration_session
integration_session.default_url_options = options
end
@@ -475,6 +472,7 @@ module ActionDispatch
# Delegate unhandled messages to the current session instance.
def method_missing(sym, *args, &block)
+ reset! unless integration_session
if integration_session.respond_to?(sym)
integration_session.__send__(sym, *args, &block).tap do
copy_session_variables!
@@ -483,6 +481,11 @@ module ActionDispatch
super
end
end
+
+ private
+ def integration_session
+ @integration_session ||= nil
+ end
end
end
@@ -659,6 +662,7 @@ module ActionDispatch
end
def url_options
+ reset! unless integration_session
integration_session.url_options
end
diff --git a/actionpack/lib/action_dispatch/testing/test_response.rb b/actionpack/lib/action_dispatch/testing/test_response.rb
index 369ea1467c..a9b88ac5fd 100644
--- a/actionpack/lib/action_dispatch/testing/test_response.rb
+++ b/actionpack/lib/action_dispatch/testing/test_response.rb
@@ -7,11 +7,7 @@ module ActionDispatch
# See Response for more information on controller response objects.
class TestResponse < Response
def self.from_response(response)
- new.tap do |resp|
- resp.status = response.status
- resp.headers = response.headers
- resp.body = response.body
- end
+ new response.status, response.headers, response.body, default_headers: nil
end
# Was the response successful?
@@ -25,12 +21,5 @@ module ActionDispatch
# Was there a server-side error?
alias_method :error?, :server_error?
-
- def merge_default_headers(original, *args)
- # Default headers are already applied, no need to merge them a second time.
- # This makes sure that default headers, removed in controller actions, will
- # not be reapplied to the test response.
- original
- end
end
end
diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb
index 4760ec1698..2d6607041d 100644
--- a/actionpack/test/controller/caching_test.rb
+++ b/actionpack/test/controller/caching_test.rb
@@ -1,5 +1,6 @@
require 'fileutils'
require 'abstract_unit'
+require 'lib/controller/fake_models'
CACHE_DIR = 'test_cache'
# Don't change '/../temp/' cavalierly or you might hose something you don't want hosed
@@ -349,3 +350,60 @@ class ViewCacheDependencyTest < ActionController::TestCase
assert_equal %w(trombone flute), HasDependenciesController.new.view_cache_dependencies
end
end
+
+class CollectionCacheController < ActionController::Base
+ def index
+ @customers = [Customer.new('david', params[:id] || 1)]
+ end
+
+ def index_ordered
+ @customers = [Customer.new('david', 1), Customer.new('david', 2), Customer.new('david', 3)]
+ render 'index'
+ end
+
+ def index_explicit_render
+ @customers = [Customer.new('david', 1)]
+ render partial: 'customers/customer', collection: @customers
+ end
+
+ def index_with_comment
+ @customers = [Customer.new('david', 1)]
+ render partial: 'customers/commented_customer', collection: @customers, as: :customer
+ end
+end
+
+class AutomaticCollectionCacheTest < ActionController::TestCase
+ def setup
+ super
+ @controller = CollectionCacheController.new
+ @controller.perform_caching = true
+ @controller.cache_store = ActiveSupport::Cache::MemoryStore.new
+ end
+
+ def test_collection_fetches_cached_views
+ get :index
+
+ ActionView::PartialRenderer.expects(:collection_with_template).never
+ get :index
+ end
+
+ def test_preserves_order_when_reading_from_cache_plus_rendering
+ get :index, params: { id: 2 }
+ get :index_ordered
+
+ assert_select ':root', "david, 1\n david, 2\n david, 3"
+ end
+
+ def test_explicit_render_call_with_options
+ get :index_explicit_render
+
+ assert_select ':root', "david, 1"
+ end
+
+ def test_caching_works_with_beginning_comment
+ get :index_with_comment
+
+ ActionView::PartialRenderer.expects(:collection_with_template).never
+ get :index_with_comment
+ end
+end
diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb
index 26b94f0db8..a1ce12a13e 100644
--- a/actionpack/test/controller/filters_test.rb
+++ b/actionpack/test/controller/filters_test.rb
@@ -1074,6 +1074,14 @@ class YieldingAroundFiltersTest < ActionController::TestCase
end
end
+ def test_deprecated_skip_filter
+ assert_deprecated do
+ Class.new(PostsController) do
+ skip_filter :clean_up
+ end
+ end
+ end
+
protected
def test_process(controller, action = "show")
@controller = controller.is_a?(Class) ? controller.new : controller
diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb
index 9ab1549e8e..438c044da2 100644
--- a/actionpack/test/controller/integration_test.rb
+++ b/actionpack/test/controller/integration_test.rb
@@ -397,9 +397,9 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
redirect_to action_url('get')
end
- def remove_default_header
- response.headers.except! 'X-Frame-Options'
- head :ok
+ def remove_header
+ response.headers.delete params[:header]
+ head :ok, 'c' => '3'
end
end
@@ -640,25 +640,27 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
end
end
- def test_removed_default_headers_on_test_response_are_not_reapplied
+ def test_respect_removal_of_default_headers_by_a_controller_action
with_test_route_set do
- begin
- header_to_remove = 'X-Frame-Options'
- original_default_headers = ActionDispatch::Response.default_headers
- ActionDispatch::Response.default_headers = {
- 'X-Content-Type-Options' => 'nosniff',
- header_to_remove => 'SAMEORIGIN',
- }
- get '/remove_default_header'
- assert_includes headers, 'X-Content-Type-Options'
- assert_not_includes headers, header_to_remove, "Should not contain removed default header"
- ensure
- ActionDispatch::Response.default_headers = original_default_headers
+ with_default_headers 'a' => '1', 'b' => '2' do
+ get '/remove_header', params: { header: 'a' }
end
end
+
+ assert_not_includes @response.headers, 'a', 'Response should not include default header removed by the controller action'
+ assert_includes @response.headers, 'b'
+ assert_includes @response.headers, 'c'
end
private
+ def with_default_headers(headers)
+ original = ActionDispatch::Response.default_headers
+ ActionDispatch::Response.default_headers = headers
+ yield
+ ensure
+ ActionDispatch::Response.default_headers = original
+ end
+
def with_test_route_set
with_routing do |set|
controller = ::IntegrationProcessTest::IntegrationController.clone
diff --git a/actionpack/test/controller/test_case_test.rb b/actionpack/test/controller/test_case_test.rb
index ca854040b7..e348749f78 100644
--- a/actionpack/test/controller/test_case_test.rb
+++ b/actionpack/test/controller/test_case_test.rb
@@ -965,6 +965,52 @@ XML
end
end
+class ResponseDefaultHeadersTest < ActionController::TestCase
+ class TestController < ActionController::Base
+ def remove_header
+ headers.delete params[:header]
+ head :ok, 'C' => '3'
+ end
+ end
+
+ setup do
+ @original = ActionDispatch::Response.default_headers
+ @defaults = { 'A' => '1', 'B' => '2' }
+ ActionDispatch::Response.default_headers = @defaults
+ end
+
+ teardown do
+ ActionDispatch::Response.default_headers = @original
+ end
+
+ def setup
+ super
+ @controller = TestController.new
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+ @request.env['PATH_INFO'] = nil
+ @routes = ActionDispatch::Routing::RouteSet.new.tap do |r|
+ r.draw do
+ get ':controller(/:action(/:id))'
+ end
+ end
+ end
+
+ test "response contains default headers" do
+ # Response headers start out with the defaults
+ assert_equal @defaults, response.headers
+
+ get :remove_header, params: { header: 'A' }
+ assert_response :ok
+
+ # After a request, the response in the test case doesn't have the
+ # defaults merged on top again.
+ assert_not_includes response.headers, 'A'
+ assert_includes response.headers, 'B'
+ assert_includes response.headers, 'C'
+ end
+end
+
module EngineControllerTests
class Engine < ::Rails::Engine
isolate_namespace EngineControllerTests
diff --git a/actionpack/test/dispatch/response_test.rb b/actionpack/test/dispatch/response_test.rb
index 5fbd19acdf..f4c0b421d6 100644
--- a/actionpack/test/dispatch/response_test.rb
+++ b/actionpack/test/dispatch/response_test.rb
@@ -172,7 +172,7 @@ class ResponseTest < ActiveSupport::TestCase
original = ActionDispatch::Response.default_charset
begin
ActionDispatch::Response.default_charset = 'utf-16'
- resp = ActionDispatch::Response.new(200, { "Content-Type" => "text/xml" })
+ resp = ActionDispatch::Response.new(200, { "Content-Type" => "text/xml" }, default_headers: nil)
assert_equal('utf-16', resp.charset)
ensure
ActionDispatch::Response.default_charset = original
@@ -254,6 +254,10 @@ class ResponseTest < ActiveSupport::TestCase
end
class ResponseIntegrationTest < ActionDispatch::IntegrationTest
+ def app
+ @app
+ end
+
test "response cache control from railsish app" do
@app = lambda { |env|
ActionDispatch::Response.new.tap { |resp|
diff --git a/actionpack/test/dispatch/routing/inspector_test.rb b/actionpack/test/dispatch/routing/inspector_test.rb
index 3d3d4b74ae..3df022c64b 100644
--- a/actionpack/test/dispatch/routing/inspector_test.rb
+++ b/actionpack/test/dispatch/routing/inspector_test.rb
@@ -26,14 +26,6 @@ module ActionDispatch
inspector.format(ActionDispatch::Routing::ConsoleFormatter.new, options[:filter]).split("\n")
end
- def test_json_regexp_converter
- @set.draw do
- get '/cart', :to => 'cart#show'
- end
- route = ActionDispatch::Routing::RouteWrapper.new(@set.routes.first)
- assert_equal "^\\/cart(?:\\.([^\\/.?]+))?$", route.json_regexp
- end
-
def test_displaying_routes_for_engines
engine = Class.new(Rails::Engine) do
def self.inspect
diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb
index deb289bd57..b4502c19d6 100644
--- a/actionpack/test/dispatch/routing_test.rb
+++ b/actionpack/test/dispatch/routing_test.rb
@@ -3489,13 +3489,20 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
def test_head_fetch_with_mount_on_root
draw do
get '/home' => 'test#index'
- mount lambda { |env| [404, {"Content-Type" => "text/html"}, ["testing"]] }, at: '/'
+ mount lambda { |env| [200, {}, [env['REQUEST_METHOD']]] }, at: '/'
end
- head '/home'
- assert_response :success
- head '/'
- assert_response :not_found
+ # TODO: HEAD request should match `get /home` rather than the
+ # lower-precedence Rack app mounted at `/`.
+ head '/home'
+ assert_response :ok
+ #assert_equal 'test#index', @response.body
+ assert_equal 'HEAD', @response.body
+
+ # But the Rack app can still respond to its own HEAD requests.
+ head '/foobar'
+ assert_response :ok
+ assert_equal 'HEAD', @response.body
end
private
diff --git a/actionpack/test/fixtures/collection_cache/index.html.erb b/actionpack/test/fixtures/collection_cache/index.html.erb
new file mode 100644
index 0000000000..521b1450df
--- /dev/null
+++ b/actionpack/test/fixtures/collection_cache/index.html.erb
@@ -0,0 +1 @@
+<%= render @customers %> \ No newline at end of file
diff --git a/actionpack/test/fixtures/customers/_commented_customer.html.erb b/actionpack/test/fixtures/customers/_commented_customer.html.erb
new file mode 100644
index 0000000000..d5f6e3b491
--- /dev/null
+++ b/actionpack/test/fixtures/customers/_commented_customer.html.erb
@@ -0,0 +1,4 @@
+<%# I'm a comment %>
+<% cache customer do %>
+ <%= customer.name %>, <%= customer.id %>
+<% end %> \ No newline at end of file
diff --git a/actionpack/test/fixtures/customers/_customer.html.erb b/actionpack/test/fixtures/customers/_customer.html.erb
new file mode 100644
index 0000000000..67e9f6d411
--- /dev/null
+++ b/actionpack/test/fixtures/customers/_customer.html.erb
@@ -0,0 +1,3 @@
+<% cache customer do %>
+ <%= customer.name %>, <%= customer.id %>
+<% end %> \ No newline at end of file
diff --git a/actionview/CHANGELOG.md b/actionview/CHANGELOG.md
index 5557285ef5..101f1263d9 100644
--- a/actionview/CHANGELOG.md
+++ b/actionview/CHANGELOG.md
@@ -1,3 +1,33 @@
+* Fixed the translation helper method to accept different default values types
+ besides String.
+
+ *Ulisses Almeida*
+
+* Collection rendering automatically caches and fetches multiple partials.
+
+ Collections rendered as:
+
+ ```ruby
+ <%= render @notifications %>
+ <%= render partial: 'notifications/notification', collection: @notifications, as: :notification %>
+ ```
+
+ will now read several partials from cache at once, if the template starts with a cache call:
+
+ ```ruby
+ # notifications/_notification.html.erb
+ <% cache notification do %>
+ <%# ... %>
+ <% end %>
+ ```
+
+ *Kasper Timm Hansen*
+
+* Fixed a dependency tracker bug that caused template dependencies not
+ count layouts as dependencies for partials.
+
+ *Juho Leinonen*
+
* Extracted `ActionView::Helpers::RecordTagHelper` to external gem
(`record_tag_helper`) and added removal notices.
diff --git a/actionview/lib/action_view/dependency_tracker.rb b/actionview/lib/action_view/dependency_tracker.rb
index e34bdd4a46..7a7e116dbb 100644
--- a/actionview/lib/action_view/dependency_tracker.rb
+++ b/actionview/lib/action_view/dependency_tracker.rb
@@ -76,6 +76,12 @@ module ActionView
(?:#{STRING}|#{VARIABLE_OR_METHOD_CHAIN}) # finally, the dependency name of interest
/xm
+ LAYOUT_DEPENDENCY = /\A
+ (?:\s*\(?\s*) # optional opening paren surrounded by spaces
+ (?:.*?#{LAYOUT_HASH_KEY}) # check if the line has layout key declaration
+ (?:#{STRING}|#{VARIABLE_OR_METHOD_CHAIN}) # finally, the dependency name of interest
+ /xm
+
def self.call(name, template)
new(name, template).dependencies
end
@@ -106,15 +112,20 @@ module ActionView
render_calls = source.split(/\brender\b/).drop(1)
render_calls.each do |arguments|
- arguments.scan(RENDER_ARGUMENTS) do
- add_dynamic_dependency(render_dependencies, Regexp.last_match[:dynamic])
- add_static_dependency(render_dependencies, Regexp.last_match[:static])
- end
+ add_dependencies(render_dependencies, arguments, LAYOUT_DEPENDENCY)
+ add_dependencies(render_dependencies, arguments, RENDER_ARGUMENTS)
end
render_dependencies.uniq
end
+ def add_dependencies(render_dependencies, arguments, pattern)
+ arguments.scan(pattern) do
+ add_dynamic_dependency(render_dependencies, Regexp.last_match[:dynamic])
+ add_static_dependency(render_dependencies, Regexp.last_match[:static])
+ end
+ end
+
def add_dynamic_dependency(dependencies, dependency)
if dependency
dependencies << "#{dependency.pluralize}/#{dependency.singularize}"
diff --git a/actionview/lib/action_view/helpers/cache_helper.rb b/actionview/lib/action_view/helpers/cache_helper.rb
index 9dadfb5ce1..0e2a5f90f4 100644
--- a/actionview/lib/action_view/helpers/cache_helper.rb
+++ b/actionview/lib/action_view/helpers/cache_helper.rb
@@ -110,6 +110,29 @@ module ActionView
# <%= some_helper_method(person) %>
#
# Now all you'll have to do is change that timestamp when the helper method changes.
+ #
+ # === Automatic Collection Caching
+ #
+ # When rendering collections such as:
+ #
+ # <%= render @notifications %>
+ # <%= render partial: 'notifications/notification', collection: @notifications %>
+ #
+ # If the notifications/_notification partial starts with a cache call like so:
+ #
+ # <% cache notification do %>
+ # <%= notification.name %>
+ # <% end %>
+ #
+ # The collection can then automatically use any cached renders for that
+ # template by reading them at once instead of one by one.
+ #
+ # See ActionView::Template::Handlers::ERB.resource_cache_call_pattern for more
+ # information on what cache calls make a template eligible for this collection caching.
+ #
+ # The automatic cache multi read can be turned off like so:
+ #
+ # <%= render @notifications, cache: false %>
def cache(name = {}, options = nil, &block)
if controller.perform_caching
safe_concat(fragment_for(cache_fragment_name(name, options), options, &block))
@@ -161,6 +184,14 @@ module ActionView
end
end
+ # Given a key (as described in ActionController::Caching::Fragments.expire_fragment),
+ # returns a key suitable for use in reading, writing, or expiring a
+ # cached fragment. All keys are prefixed with <tt>views/</tt> and uses
+ # ActiveSupport::Cache.expand_cache_key for the expansion.
+ def fragment_cache_key(key)
+ ActiveSupport::Cache.expand_cache_key(key.is_a?(Hash) ? url_for(key).split("://").last : key, :views)
+ end
+
private
def fragment_name_with_digest(name) #:nodoc:
diff --git a/actionview/lib/action_view/helpers/form_helper.rb b/actionview/lib/action_view/helpers/form_helper.rb
index b76b35bf3c..b0793d0b91 100644
--- a/actionview/lib/action_view/helpers/form_helper.rb
+++ b/actionview/lib/action_view/helpers/form_helper.rb
@@ -1246,7 +1246,7 @@ module ActionView
# Admin: <%= person_form.check_box :admin %>
# <% end %>
#
- # In the above block, the a +FormBuilder+ object is yielded as the
+ # In the above block, a +FormBuilder+ object is yielded as the
# +person_form+ variable. This allows you to generate the +text_field+
# and +check_box+ fields by specifying their eponymous methods, which
# modify the underlying template and associates the +@person+ model object
@@ -1267,6 +1267,7 @@ module ActionView
# )
# )
# end
+ # end
#
# The above code creates a new method +div_radio_button+ which wraps a div
# around the new radio button. Note that when options are passed in, you
diff --git a/actionview/lib/action_view/helpers/translation_helper.rb b/actionview/lib/action_view/helpers/translation_helper.rb
index 342361217c..24b633c5bb 100644
--- a/actionview/lib/action_view/helpers/translation_helper.rb
+++ b/actionview/lib/action_view/helpers/translation_helper.rb
@@ -37,8 +37,12 @@ module ActionView
# you know what kind of output to expect when you call translate in a template.
def translate(key, options = {})
options = options.dup
+ has_default = options.has_key?(:default)
remaining_defaults = Array(options.delete(:default))
- options[:default] = remaining_defaults.shift if remaining_defaults.first.kind_of? String
+
+ if has_default && !remaining_defaults.first.kind_of?(Symbol)
+ options[:default] = remaining_defaults.shift
+ end
# If the user has explicitly decided to NOT raise errors, pass that option to I18n.
# Otherwise, tell I18n to raise an exception, which we rescue further in this method.
diff --git a/actionview/lib/action_view/railtie.rb b/actionview/lib/action_view/railtie.rb
index ee3dce24b7..9a26cba574 100644
--- a/actionview/lib/action_view/railtie.rb
+++ b/actionview/lib/action_view/railtie.rb
@@ -36,6 +36,12 @@ module ActionView
end
end
+ initializer "action_view.collection_caching" do |app|
+ ActiveSupport.on_load(:action_controller) do
+ PartialRenderer.collection_cache = app.config.action_controller.cache_store
+ end
+ end
+
initializer "action_view.setup_action_pack" do |app|
ActiveSupport.on_load(:action_controller) do
ActionView::RoutingUrlFor.include(ActionDispatch::Routing::UrlFor)
diff --git a/actionview/lib/action_view/renderer/partial_renderer.rb b/actionview/lib/action_view/renderer/partial_renderer.rb
index 5ff15411cf..56b8ab1e2d 100644
--- a/actionview/lib/action_view/renderer/partial_renderer.rb
+++ b/actionview/lib/action_view/renderer/partial_renderer.rb
@@ -1,3 +1,4 @@
+require 'action_view/renderer/partial_renderer/collection_caching'
require 'thread_safe'
module ActionView
@@ -280,6 +281,8 @@ module ActionView
# <%- end -%>
# <% end %>
class PartialRenderer < AbstractRenderer
+ include CollectionCaching
+
PREFIXED_PARTIAL_NAMES = ThreadSafe::Cache.new do |h, k|
h[k] = ThreadSafe::Cache.new
end
@@ -321,8 +324,9 @@ module ActionView
spacer = find_template(@options[:spacer_template], @locals.keys).render(@view, @locals)
end
- result = @template ? collection_with_template : collection_without_template
- result.join(spacer).html_safe
+ cache_collection_render do
+ @template ? collection_with_template : collection_without_template
+ end.join(spacer).html_safe
end
def render_partial
diff --git a/actionview/lib/action_view/renderer/partial_renderer/collection_caching.rb b/actionview/lib/action_view/renderer/partial_renderer/collection_caching.rb
new file mode 100644
index 0000000000..b77c884e66
--- /dev/null
+++ b/actionview/lib/action_view/renderer/partial_renderer/collection_caching.rb
@@ -0,0 +1,70 @@
+require 'active_support/core_ext/object/try'
+
+module ActionView
+ module CollectionCaching # :nodoc:
+ extend ActiveSupport::Concern
+
+ included do
+ # Fallback cache store if Action View is used without Rails.
+ # Otherwise overriden in Railtie to use Rails.cache.
+ mattr_accessor(:collection_cache) { ActiveSupport::Cache::MemoryStore.new }
+ end
+
+ private
+ def cache_collection_render
+ return yield unless cache_collection?
+
+ keyed_collection = collection_by_cache_keys
+ partial_cache = collection_cache.read_multi(*keyed_collection.keys)
+
+ @collection = keyed_collection.reject { |key, _| partial_cache.key?(key) }.values
+ rendered_partials = @collection.any? ? yield.dup : []
+
+ fetch_or_cache_partial(partial_cache, order_by: keyed_collection.each_key) do
+ rendered_partials.shift
+ end
+ end
+
+ def cache_collection?
+ @options.fetch(:cache, automatic_cache_eligible?)
+ end
+
+ def automatic_cache_eligible?
+ single_template_render? && !callable_cache_key? &&
+ @template.eligible_for_collection_caching?(as: @options[:as])
+ end
+
+ def single_template_render?
+ @template # Template is only set when a collection renders one template.
+ end
+
+ def callable_cache_key?
+ @options[:cache].respond_to?(:call)
+ end
+
+ def collection_by_cache_keys
+ seed = callable_cache_key? ? @options[:cache] : ->(i) { i }
+
+ @collection.each_with_object({}) do |item, hash|
+ hash[expanded_cache_key(seed.call(item))] = item
+ end
+ end
+
+ def expanded_cache_key(key)
+ key = @view.fragment_cache_key(@view.cache_fragment_name(key))
+ key.frozen? ? key.dup : key # #read_multi & #write may require mutability, Dalli 2.6.0.
+ end
+
+ def fetch_or_cache_partial(cached_partials, order_by:)
+ cache_options = @options[:cache_options] || @locals[:cache_options] || {}
+
+ order_by.map do |key|
+ cached_partials.fetch(key) do
+ yield.tap do |rendered_partial|
+ collection_cache.write(key, rendered_partial, cache_options)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/actionview/lib/action_view/routing_url_for.rb b/actionview/lib/action_view/routing_url_for.rb
index f281333a41..0371db07dc 100644
--- a/actionview/lib/action_view/routing_url_for.rb
+++ b/actionview/lib/action_view/routing_url_for.rb
@@ -130,5 +130,11 @@ module ActionView
controller.optimize_routes_generation? : super
end
protected :optimize_routes_generation?
+
+ private
+
+ def _generate_paths_by_default
+ true
+ end
end
end
diff --git a/actionview/lib/action_view/template.rb b/actionview/lib/action_view/template.rb
index 305d9c6ee3..377ceb534a 100644
--- a/actionview/lib/action_view/template.rb
+++ b/actionview/lib/action_view/template.rb
@@ -130,6 +130,7 @@ module ActionView
@source = source
@identifier = identifier
@handler = handler
+ @cache_name = extract_resource_cache_call_name
@compiled = false
@original_encoding = nil
@locals = details[:locals] || []
@@ -165,6 +166,10 @@ module ActionView
@type ||= Types[@formats.first] if @formats.first
end
+ def eligible_for_collection_caching?(as: nil)
+ @cache_name == (as || inferred_cache_name).to_s
+ end
+
# Receives a view object and return a template similar to self by using @virtual_path.
#
# This method is useful if you have a template object but it does not contain its source
@@ -345,5 +350,14 @@ module ActionView
payload = { virtual_path: @virtual_path, identifier: @identifier }
ActiveSupport::Notifications.instrument("#{action}.action_view", payload, &block)
end
+
+ def extract_resource_cache_call_name
+ $1 if @handler.respond_to?(:resource_cache_call_pattern) &&
+ @source =~ @handler.resource_cache_call_pattern
+ end
+
+ def inferred_cache_name
+ @inferred_cache_name ||= @virtual_path.split('/').last.sub('_', '')
+ end
end
end
diff --git a/actionview/lib/action_view/template/handlers/erb.rb b/actionview/lib/action_view/template/handlers/erb.rb
index 85a100ed4c..88a8570706 100644
--- a/actionview/lib/action_view/template/handlers/erb.rb
+++ b/actionview/lib/action_view/template/handlers/erb.rb
@@ -123,6 +123,24 @@ module ActionView
).src
end
+ # Returns Regexp to extract a cached resource's name from a cache call at the
+ # first line of a template.
+ # The extracted cache name is expected in $1.
+ #
+ # <% cache notification do %> # => notification
+ #
+ # The pattern should support templates with a beginning comment:
+ #
+ # <%# Still extractable even though there's a comment %>
+ # <% cache notification do %> # => notification
+ #
+ # But fail to extract a name if a resource association is cached.
+ #
+ # <% cache notification.event do %> # => nil
+ def resource_cache_call_pattern
+ /\A(?:<%#.*%>\n?)?<% cache\(?\s*(\w+\.?)/
+ end
+
private
def valid_encoding(string, encoding)
diff --git a/actionview/test/actionpack/controller/render_test.rb b/actionview/test/actionpack/controller/render_test.rb
index fb826af044..8b47536a18 100644
--- a/actionview/test/actionpack/controller/render_test.rb
+++ b/actionview/test/actionpack/controller/render_test.rb
@@ -31,6 +31,10 @@ class Customer < Struct.new(:name, :id)
def persisted?
id.present?
end
+
+ def cache_key
+ name.to_s
+ end
end
module Quiz
diff --git a/actionview/test/fixtures/test/_cached_customer.erb b/actionview/test/fixtures/test/_cached_customer.erb
new file mode 100644
index 0000000000..52f35a3497
--- /dev/null
+++ b/actionview/test/fixtures/test/_cached_customer.erb
@@ -0,0 +1,3 @@
+<% cache cached_customer do %>
+ Hello: <%= cached_customer.name %>
+<% end %> \ No newline at end of file
diff --git a/actionview/test/fixtures/test/_cached_customer_as.erb b/actionview/test/fixtures/test/_cached_customer_as.erb
new file mode 100644
index 0000000000..fca8d19e34
--- /dev/null
+++ b/actionview/test/fixtures/test/_cached_customer_as.erb
@@ -0,0 +1,3 @@
+<% cache buyer do %>
+ <%= greeting %>: <%= customer.name %>
+<% end %> \ No newline at end of file
diff --git a/actionview/test/template/dependency_tracker_test.rb b/actionview/test/template/dependency_tracker_test.rb
index d74da4c318..672b4747ec 100644
--- a/actionview/test/template/dependency_tracker_test.rb
+++ b/actionview/test/template/dependency_tracker_test.rb
@@ -60,7 +60,6 @@ class ERBTrackerTest < Minitest::Test
end
def test_dependency_of_template_partial_with_layout
- skip # FIXME: Needs to be fixed properly, right now we can only match one dependency per line. Need multiple!
template = FakeTemplate.new("<%# render partial: 'messages/show', layout: 'messages/layout' %>", :erb)
tracker = make_tracker("multiple/_dependencies", template)
diff --git a/actionview/test/template/render_test.rb b/actionview/test/template/render_test.rb
index 94af1dc3ad..22665b6844 100644
--- a/actionview/test/template/render_test.rb
+++ b/actionview/test/template/render_test.rb
@@ -598,3 +598,41 @@ class LazyViewRenderTest < ActiveSupport::TestCase
silence_warnings { Encoding.default_external = old }
end
end
+
+class CachedCollectionViewRenderTest < CachedViewRenderTest
+ class CachedCustomer < Customer; end
+
+ teardown do
+ ActionView::PartialRenderer.collection_cache.clear
+ end
+
+ test "with custom key" do
+ customer = Customer.new("david")
+ key = ActionController::Base.new.fragment_cache_key([customer, 'key'])
+
+ ActionView::PartialRenderer.collection_cache.write(key, 'Hello')
+
+ assert_equal "Hello",
+ @view.render(partial: "test/customer", collection: [customer], cache: ->(item) { [item, 'key'] })
+ end
+
+ test "automatic caching with inferred cache name" do
+ customer = CachedCustomer.new("david")
+ key = ActionController::Base.new.fragment_cache_key(customer)
+
+ ActionView::PartialRenderer.collection_cache.write(key, 'Cached')
+
+ assert_equal "Cached",
+ @view.render(partial: "test/cached_customer", collection: [customer])
+ end
+
+ test "automatic caching with as name" do
+ customer = CachedCustomer.new("david")
+ key = ActionController::Base.new.fragment_cache_key(customer)
+
+ ActionView::PartialRenderer.collection_cache.write(key, 'Cached')
+
+ assert_equal "Cached",
+ @view.render(partial: "test/cached_customer_as", collection: [customer], as: :buyer)
+ end
+end
diff --git a/actionview/test/template/translation_helper_test.rb b/actionview/test/template/translation_helper_test.rb
index 8fde478ac9..ef4d13efa7 100644
--- a/actionview/test/template/translation_helper_test.rb
+++ b/actionview/test/template/translation_helper_test.rb
@@ -180,6 +180,11 @@ class TranslationHelperTest < ActiveSupport::TestCase
assert_equal 'A Generic String', translation
end
+ def test_translate_with_object_default
+ translation = translate(:'translations.missing', default: 123)
+ assert_equal 123, translation
+ end
+
def test_translate_with_array_of_string_defaults
translation = translate(:'translations.missing', default: ['A Generic String', 'Second generic string'])
assert_equal 'A Generic String', translation
diff --git a/activejob/README.md b/activejob/README.md
index 8c83d3669a..5170ebee6e 100644
--- a/activejob/README.md
+++ b/activejob/README.md
@@ -7,7 +7,7 @@ small units of work and run in parallel, really.
It also serves as the backend for Action Mailer's #deliver_later functionality
that makes it easy to turn any mailing into a job for running later. That's
-one of the most common jobs in a modern web application: Sending emails outside
+one of the most common jobs in a modern web application: sending emails outside
of the request-response cycle, so the user doesn't have to wait on it.
The main point is to ensure that all Rails apps will have a job infrastructure
@@ -118,7 +118,7 @@ Active Job is released under the MIT license:
## Support
-API documentation is at
+API documentation is at:
* http://api.rubyonrails.org
diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb
index 8a21332cc2..f324788979 100644
--- a/activemodel/lib/active_model/errors.rb
+++ b/activemodel/lib/active_model/errors.rb
@@ -3,7 +3,6 @@
require 'active_support/core_ext/array/conversions'
require 'active_support/core_ext/string/inflections'
require 'active_support/core_ext/object/deep_dup'
-require 'active_support/deprecation'
module ActiveModel
# == Active \Model \Errors
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md
index 6cdf9ebd9b..b5dd19988d 100644
--- a/activerecord/CHANGELOG.md
+++ b/activerecord/CHANGELOG.md
@@ -1,3 +1,21 @@
+* Dont enroll records in the transaction if they dont have commit callbacks.
+ That was causing a memory grow problem when creating a lot of records inside a transaction.
+
+ Fixes #15549.
+
+ *Will Bryant*, *Aaron Patterson*
+
+* Correctly create through records when created on a has many through
+ association when using `where`.
+
+ Fixes #19073.
+
+ *Sean Griffin*
+
+* Add `SchemaMigration.create_table` support any unicode charsets for MySQL.
+
+ *Ryuta Kamizono*
+
* PostgreSQL, no longer disables user triggers if system triggers can't be
disabled. Disabling user triggers does not fulfill what the method promises.
Rails currently requires superuser privileges for this method.
diff --git a/activerecord/lib/active_record/association_relation.rb b/activerecord/lib/active_record/association_relation.rb
index f2b44913db..ee0bb8fafe 100644
--- a/activerecord/lib/active_record/association_relation.rb
+++ b/activerecord/lib/active_record/association_relation.rb
@@ -13,6 +13,19 @@ module ActiveRecord
other == to_a
end
+ def build(*args, &block)
+ scoping { @association.build(*args, &block) }
+ end
+ alias new build
+
+ def create(*args, &block)
+ scoping { @association.create(*args, &block) }
+ end
+
+ def create!(*args, &block)
+ scoping { @association.create!(*args, &block) }
+ end
+
private
def exec_queries
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 0acc815d51..8231f44b4e 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
@@ -401,7 +401,7 @@ module ActiveRecord
# Adds a reference. Optionally adds a +type+ column, if the
# +:polymorphic+ option is provided. +references+ and +belongs_to+
- # are acceptable. The reference column will be an +integer+ by default,
+ # are interchangeable. The reference column will be an +integer+ by default,
# the +:type+ option can be used to specify a different type. A foreign
# key will be created if the +:foreign_key+ option is passed.
#
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb b/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb
index 11440e30d4..ebb4a1523f 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb
@@ -1,13 +1,10 @@
module ActiveRecord
module ConnectionAdapters
class TransactionState
- attr_reader :parent
-
VALID_STATES = Set.new([:committed, :rolledback, nil])
def initialize(state = nil)
@state = state
- @parent = nil
end
def finalized?
@@ -77,6 +74,10 @@ module ActiveRecord
@state.set_state(:committed)
end
+ def before_commit_records
+ records.uniq.each(&:before_committed!)
+ end
+
def commit_records
ite = records.uniq
while record = ite.shift
@@ -159,13 +160,15 @@ module ActiveRecord
def commit_transaction
inner_transaction = @stack.pop
- inner_transaction.commit
if current_transaction.joinable?
+ inner_transaction.commit
inner_transaction.records.each do |r|
r.add_to_transaction
end
else
+ inner_transaction.before_commit_records
+ inner_transaction.commit
inner_transaction.commit_records
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
index c307189980..ae42e8ef8d 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
@@ -478,7 +478,6 @@ module ActiveRecord
message = "#{e.class.name}: #{e.message.force_encoding sql.encoding}: #{sql}"
end
- @logger.error message if @logger
exception = translate_exception(e, message)
exception.set_backtrace e.backtrace
exception
diff --git a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
index 98009da2bd..c084431588 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
@@ -235,6 +235,16 @@ module ActiveRecord
end
end
+ MAX_INDEX_LENGTH_FOR_CHARSETS_OF_4BYTES_MAXLEN = 191
+ CHARSETS_OF_4BYTES_MAXLEN = ['utf8mb4', 'utf16', 'utf16le', 'utf32']
+ def initialize_schema_migrations_table
+ if CHARSETS_OF_4BYTES_MAXLEN.include?(charset)
+ ActiveRecord::SchemaMigration.create_table(MAX_INDEX_LENGTH_FOR_CHARSETS_OF_4BYTES_MAXLEN)
+ else
+ ActiveRecord::SchemaMigration.create_table
+ end
+ end
+
# Returns true, since this connection adapter supports migrations.
def supports_migrations?
true
diff --git a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
index fac6f81540..21631be25c 100644
--- a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
@@ -37,15 +37,6 @@ module ActiveRecord
configure_connection
end
- MAX_INDEX_LENGTH_FOR_UTF8MB4 = 191
- def initialize_schema_migrations_table
- if charset == 'utf8mb4'
- ActiveRecord::SchemaMigration.create_table(MAX_INDEX_LENGTH_FOR_UTF8MB4)
- else
- ActiveRecord::SchemaMigration.create_table
- end
- end
-
def supports_explain?
true
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 75b9d079bd..eeb141dd1e 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
@@ -514,14 +514,14 @@ module ActiveRecord
sql = case type.to_s
when 'binary'
# PostgreSQL doesn't support limits on binary (bytea) columns.
- # The hard limit is 1Gb, because of a 32-bit size field, and TOAST.
+ # The hard limit is 1GB, because of a 32-bit size field, and TOAST.
case limit
when nil, 0..0x3fffffff; super(type)
else raise(ActiveRecordError, "No binary type has byte size #{limit}.")
end
when 'text'
# PostgreSQL doesn't support limits on text columns.
- # The hard limit is 1Gb, according to section 8.3 in the manual.
+ # The hard limit is 1GB, according to section 8.3 in the manual.
case limit
when nil, 0..0x3fffffff; super(type)
else raise(ActiveRecordError, "The limit on text can be at most 1GB - 1byte.")
diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
index 400b586c95..7e184dd510 100644
--- a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
@@ -121,6 +121,7 @@ module ActiveRecord
@config = config
@visitor = Arel::Visitors::SQLite.new self
+ @quoted_column_names = {}
if self.class.type_cast_config_to_boolean(config.fetch(:prepared_statements) { true })
@prepared_statements = true
@@ -240,7 +241,7 @@ module ActiveRecord
end
def quote_column_name(name) #:nodoc:
- %Q("#{name.to_s.gsub('"', '""')}")
+ @quoted_column_names[name] ||= %Q("#{name.to_s.gsub('"', '""')}")
end
#--
diff --git a/activerecord/lib/active_record/connection_handling.rb b/activerecord/lib/active_record/connection_handling.rb
index 984af79642..24f5849e45 100644
--- a/activerecord/lib/active_record/connection_handling.rb
+++ b/activerecord/lib/active_record/connection_handling.rb
@@ -5,7 +5,7 @@ module ActiveRecord
# Establishes the connection to the database. Accepts a hash as input where
# the <tt>:adapter</tt> key must be specified with the name of a database adapter (in lower-case)
- # example for regular databases (MySQL, Postgresql, etc):
+ # example for regular databases (MySQL, PostgreSQL, etc):
#
# ActiveRecord::Base.establish_connection(
# adapter: "mysql",
diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb
index de48681746..97ce4642aa 100644
--- a/activerecord/lib/active_record/core.rb
+++ b/activerecord/lib/active_record/core.rb
@@ -483,51 +483,6 @@ module ActiveRecord
private
- def set_transaction_state(state) # :nodoc:
- @transaction_state = state
- end
-
- def has_transactional_callbacks? # :nodoc:
- !_rollback_callbacks.empty? || !_commit_callbacks.empty?
- end
-
- # Updates the attributes on this particular ActiveRecord object so that
- # if it is associated with a transaction, then the state of the AR object
- # will be updated to reflect the current state of the transaction
- #
- # The @transaction_state variable stores the states of the associated
- # transaction. This relies on the fact that a transaction can only be in
- # one rollback or commit (otherwise a list of states would be required)
- # Each AR object inside of a transaction carries that transaction's
- # TransactionState.
- #
- # This method checks to see if the ActiveRecord object's state reflects
- # the TransactionState, and rolls back or commits the ActiveRecord object
- # as appropriate.
- #
- # Since ActiveRecord objects can be inside multiple transactions, this
- # method recursively goes through the parent of the TransactionState and
- # checks if the ActiveRecord object reflects the state of the object.
- def sync_with_transaction_state
- update_attributes_from_transaction_state(@transaction_state, 0)
- end
-
- def update_attributes_from_transaction_state(transaction_state, depth)
- @reflects_state = [false] if depth == 0
-
- if transaction_state && transaction_state.finalized? && !has_transactional_callbacks?
- unless @reflects_state[depth]
- restore_transaction_record_state if transaction_state.rolledback?
- clear_transaction_record_state
- @reflects_state[depth] = true
- end
-
- if transaction_state.parent && !@reflects_state[depth+1]
- update_attributes_from_transaction_state(transaction_state.parent, depth+1)
- end
- end
- end
-
# Under Ruby 1.9, Array#flatten will call #to_ary (recursively) on each of the elements
# of the array, and then rescues from the possible NoMethodError. If those elements are
# ActiveRecord::Base's, then this triggers the various method_missing's that we have,
diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb
index 739be524da..75b0e1e08d 100644
--- a/activerecord/lib/active_record/fixtures.rb
+++ b/activerecord/lib/active_record/fixtures.rb
@@ -708,6 +708,10 @@ module ActiveRecord
def lhs_key
@association.through_reflection.foreign_key
end
+
+ def join_table
+ @association.through_reflection.table_name
+ end
end
private
diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb
index 7c076864a3..a6176dffdb 100644
--- a/activerecord/lib/active_record/persistence.rb
+++ b/activerecord/lib/active_record/persistence.rb
@@ -96,7 +96,8 @@ module ActiveRecord
# Returns true if the record is persisted, i.e. it's not a new record and it was
# not destroyed, otherwise returns false.
def persisted?
- !(new_record? || destroyed?)
+ sync_with_transaction_state
+ !(@new_record || @destroyed)
end
# Saves the model.
diff --git a/activerecord/lib/active_record/railtie.rb b/activerecord/lib/active_record/railtie.rb
index f1bdbc845c..b6de90e89d 100644
--- a/activerecord/lib/active_record/railtie.rb
+++ b/activerecord/lib/active_record/railtie.rb
@@ -58,6 +58,9 @@ module ActiveRecord
require "active_record/railties/console_sandbox" if app.sandbox?
require "active_record/base"
console = ActiveSupport::Logger.new(STDERR)
+ console.formatter = Rails.logger.formatter
+ console.level = Rails.logger.level
+
Rails.logger.extend ActiveSupport::Logger.broadcast console
end
diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb
index 4a4de86d48..7f27e7b463 100644
--- a/activerecord/lib/active_record/relation/calculations.rb
+++ b/activerecord/lib/active_record/relation/calculations.rb
@@ -222,7 +222,7 @@ module ActiveRecord
end
def execute_simple_calculation(operation, column_name, distinct) #:nodoc:
- # Postgresql doesn't like ORDER BY when there are no GROUP BY
+ # PostgreSQL doesn't like ORDER BY when there are no GROUP BY
relation = unscope(:order)
column_alias = column_name
diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb
index fb47d915ff..7bd091b66c 100644
--- a/activerecord/lib/active_record/relation/finder_methods.rb
+++ b/activerecord/lib/active_record/relation/finder_methods.rb
@@ -1,4 +1,3 @@
-require 'active_support/deprecation'
require 'active_support/core_ext/string/filters'
module ActiveRecord
diff --git a/activerecord/lib/active_record/transactions.rb b/activerecord/lib/active_record/transactions.rb
index dd405c7796..ffe7c4ae42 100644
--- a/activerecord/lib/active_record/transactions.rb
+++ b/activerecord/lib/active_record/transactions.rb
@@ -7,6 +7,10 @@ module ActiveRecord
included do
define_callbacks :commit, :rollback,
+ :before_commit,
+ :before_commit_without_transaction_enrollment,
+ :commit_without_transaction_enrollment,
+ :rollback_without_transaction_enrollment,
scope: [:kind, :name]
end
@@ -206,6 +210,11 @@ module ActiveRecord
connection.transaction(options, &block)
end
+ def before_commit(*args, &block) # :nodoc:
+ set_options_for_callbacks!(args)
+ set_callback(:before_commit, :before, *args, &block)
+ end
+
# This callback is called after a record has been created, updated, or destroyed.
#
# You can specify that the callback should only be fired by a certain action with
@@ -233,6 +242,21 @@ module ActiveRecord
set_callback(:rollback, :after, *args, &block)
end
+ def before_commit_without_transaction_enrollment(*args, &block) # :nodoc:
+ set_options_for_callbacks!(args)
+ set_callback(:before_commit_without_transaction_enrollment, :before, *args, &block)
+ end
+
+ def after_commit_without_transaction_enrollment(*args, &block) # :nodoc:
+ set_options_for_callbacks!(args)
+ set_callback(:commit_without_transaction_enrollment, :after, *args, &block)
+ end
+
+ def after_rollback_without_transaction_enrollment(*args, &block) # :nodoc:
+ set_options_for_callbacks!(args)
+ set_callback(:rollback_without_transaction_enrollment, :after, *args, &block)
+ end
+
def raise_in_transactional_callbacks
ActiveSupport::Deprecation.warn('ActiveRecord::Base.raise_in_transactional_callbacks is deprecated and will be removed without replacement.')
true
@@ -296,12 +320,20 @@ module ActiveRecord
clear_transaction_record_state
end
+ def before_committed! # :nodoc:
+ _run_before_commit_without_transaction_enrollment_callbacks
+ _run_before_commit_callbacks
+ end
+
# Call the +after_commit+ callbacks.
#
# Ensure that it is not called if the object was never persisted (failed create),
# but call it after the commit of a destroyed object.
def committed!(should_run_callbacks: true) #:nodoc:
- _run_commit_callbacks if should_run_callbacks && destroyed? || persisted?
+ if should_run_callbacks && destroyed? || persisted?
+ _run_commit_without_transaction_enrollment_callbacks
+ _run_commit_callbacks
+ end
ensure
force_clear_transaction_record_state
end
@@ -309,7 +341,10 @@ module ActiveRecord
# Call the +after_rollback+ callbacks. The +force_restore_state+ argument indicates if the record
# state should be rolled back to the beginning or just to the last savepoint.
def rolledback!(force_restore_state: false, should_run_callbacks: true) #:nodoc:
- _run_rollback_callbacks if should_run_callbacks
+ if should_run_callbacks
+ _run_rollback_without_transaction_enrollment_callbacks
+ _run_rollback_callbacks
+ end
ensure
restore_transaction_record_state(force_restore_state)
clear_transaction_record_state
@@ -407,5 +442,43 @@ module ActiveRecord
end
end
end
+
+ private
+
+ def set_transaction_state(state) # :nodoc:
+ @transaction_state = state
+ end
+
+ def has_transactional_callbacks? # :nodoc:
+ !_rollback_callbacks.empty? || !_commit_callbacks.empty? || !_before_commit_callbacks.empty?
+ end
+
+ # Updates the attributes on this particular ActiveRecord object so that
+ # if it is associated with a transaction, then the state of the AR object
+ # will be updated to reflect the current state of the transaction
+ #
+ # The @transaction_state variable stores the states of the associated
+ # transaction. This relies on the fact that a transaction can only be in
+ # one rollback or commit (otherwise a list of states would be required)
+ # Each AR object inside of a transaction carries that transaction's
+ # TransactionState.
+ #
+ # This method checks to see if the ActiveRecord object's state reflects
+ # the TransactionState, and rolls back or commits the ActiveRecord object
+ # as appropriate.
+ #
+ # Since ActiveRecord objects can be inside multiple transactions, this
+ # method recursively goes through the parent of the TransactionState and
+ # checks if the ActiveRecord object reflects the state of the object.
+ def sync_with_transaction_state
+ update_attributes_from_transaction_state(@transaction_state)
+ end
+
+ def update_attributes_from_transaction_state(transaction_state)
+ if transaction_state && transaction_state.finalized?
+ restore_transaction_record_state if transaction_state.rolledback?
+ clear_transaction_record_state
+ end
+ end
end
end
diff --git a/activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb b/activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb
index 271b570eb5..417ccf6d11 100644
--- a/activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb
+++ b/activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb
@@ -2,7 +2,7 @@ require "cases/helper"
module ActiveRecord
module ConnectionAdapters
- class Mysql2Adapter
+ class AbstractMysqlAdapter
class SchemaMigrationsTest < ActiveRecord::TestCase
def test_renaming_index_on_foreign_key
connection.add_index "engines", "car_id"
@@ -28,7 +28,7 @@ module ActiveRecord
connection.initialize_schema_migrations_table
- assert connection.column_exists?(smtn, :version, :string, limit: Mysql2Adapter::MAX_INDEX_LENGTH_FOR_UTF8MB4)
+ assert connection.column_exists?(smtn, :version, :string, limit: AbstractMysqlAdapter::MAX_INDEX_LENGTH_FOR_CHARSETS_OF_4BYTES_MAXLEN)
ensure
execute("ALTER DATABASE #{database_name} DEFAULT CHARACTER SET #{original_charset} COLLATE #{original_collation}")
end
diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb
index eebeaad7cf..897c52a49d 100644
--- a/activerecord/test/cases/associations/has_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -30,6 +30,7 @@ require 'models/college'
require 'models/student'
require 'models/pirate'
require 'models/ship'
+require 'models/ship_part'
require 'models/tyre'
require 'models/subscriber'
require 'models/subscription'
@@ -162,6 +163,30 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal college.students, Student.where(active: true, college_id: college.id)
end
+ def test_add_record_to_collection_should_change_its_updated_at
+ ship = Ship.create(name: 'dauntless')
+ part = ShipPart.create(name: 'cockpit')
+ updated_at = part.updated_at
+
+ ship.parts << part
+
+ assert_equal part.ship, ship
+ assert_not_equal part.updated_at, updated_at
+ end
+
+ def test_clear_collection_should_not_change_updated_at
+ # GH#17161: .clear calls delete_all (and returns the association),
+ # which is intended to not touch associated objects's updated_at field
+ ship = Ship.create(name: 'dauntless')
+ part = ShipPart.create(name: 'cockpit', ship_id: ship.id)
+
+ ship.parts.clear
+ part.reload
+
+ assert_equal nil, part.ship
+ assert !part.updated_at_changed?
+ end
+
def test_create_from_association_should_respect_default_scope
car = Car.create(:name => 'honda')
assert_equal 'honda', car.name
diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb
index 6729a5a9fc..5f52c65412 100644
--- a/activerecord/test/cases/associations/has_many_through_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb
@@ -595,6 +595,12 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
assert posts(:thinking).reload.people(true).collect(&:first_name).include?("Jeb")
end
+ def test_through_record_is_built_when_created_with_where
+ assert_difference("posts(:thinking).readers.count", 1) do
+ posts(:thinking).people.where(first_name: "Jeb").create
+ end
+ end
+
def test_associate_with_create_and_no_options
peeps = posts(:thinking).people.count
posts(:thinking).people.create(:first_name => 'foo')
diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb
index f41245dfd2..7ef2ebc998 100644
--- a/activerecord/test/cases/fixtures_test.rb
+++ b/activerecord/test/cases/fixtures_test.rb
@@ -273,7 +273,7 @@ class HasManyThroughFixture < ActiveSupport::TestCase
Class.new(ActiveRecord::Base) { define_singleton_method(:name) { name } }
end
- def test_has_many_through
+ def test_has_many_through_with_default_table_name
pt = make_model "ParrotTreasure"
parrot = make_model "Parrot"
treasure = make_model "Treasure"
@@ -292,6 +292,24 @@ class HasManyThroughFixture < ActiveSupport::TestCase
assert_equal load_has_and_belongs_to_many['parrots_treasures'], rows['parrots_treasures']
end
+ def test_has_many_through_with_renamed_table
+ pt = make_model "ParrotTreasure"
+ parrot = make_model "Parrot"
+ treasure = make_model "Treasure"
+
+ pt.belongs_to :parrot, :class => parrot
+ pt.belongs_to :treasure, :class => treasure
+
+ parrot.has_many :parrot_treasures, :class => pt
+ parrot.has_many :treasures, :through => :parrot_treasures
+
+ parrots = File.join FIXTURES_ROOT, 'parrots'
+
+ fs = ActiveRecord::FixtureSet.new parrot.connection, "parrots", parrot, parrots
+ rows = fs.table_rows
+ assert_equal load_has_and_belongs_to_many['parrots_treasures'], rows['parrot_treasures']
+ end
+
def load_has_and_belongs_to_many
parrot = make_model "Parrot"
parrot.has_and_belongs_to_many :treasures
diff --git a/activerecord/test/cases/transaction_callbacks_test.rb b/activerecord/test/cases/transaction_callbacks_test.rb
index f185cda263..e868022fed 100644
--- a/activerecord/test/cases/transaction_callbacks_test.rb
+++ b/activerecord/test/cases/transaction_callbacks_test.rb
@@ -400,3 +400,63 @@ class CallbacksOnMultipleActionsTest < ActiveRecord::TestCase
assert_equal [:update_and_destroy, :create_and_destroy], topic.history
end
end
+
+
+class TransactionEnrollmentCallbacksTest < ActiveRecord::TestCase
+
+ class TopicWithoutTransactionalEnrollmentCallbacks < ActiveRecord::Base
+ self.table_name = :topics
+
+ before_commit_without_transaction_enrollment { |r| r.history << :before_commit }
+ after_commit_without_transaction_enrollment { |r| r.history << :after_commit }
+ after_rollback_without_transaction_enrollment { |r| r.history << :rollback }
+
+ def history
+ @history ||= []
+ end
+ end
+
+ def setup
+ @topic = TopicWithoutTransactionalEnrollmentCallbacks.create!
+ end
+
+ def test_commit_does_not_run_transactions_callbacks_without_enrollment
+ @topic.transaction do
+ @topic.content = 'foo'
+ @topic.save!
+ end
+ assert @topic.history.empty?
+ end
+
+ def test_commit_run_transactions_callbacks_with_explicit_enrollment
+ @topic.transaction do
+ 2.times do
+ @topic.content = 'foo'
+ @topic.save!
+ end
+ @topic.class.connection.add_transaction_record(@topic)
+ end
+ assert_equal [:before_commit, :after_commit], @topic.history
+ end
+
+ def test_rollback_does_not_run_transactions_callbacks_without_enrollment
+ @topic.transaction do
+ @topic.content = 'foo'
+ @topic.save!
+ raise ActiveRecord::Rollback
+ end
+ assert @topic.history.empty?
+ end
+
+ def test_rollback_run_transactions_callbacks_with_explicit_enrollment
+ @topic.transaction do
+ 2.times do
+ @topic.content = 'foo'
+ @topic.save!
+ end
+ @topic.class.connection.add_transaction_record(@topic)
+ raise ActiveRecord::Rollback
+ end
+ assert_equal [:rollback], @topic.history
+ end
+end
diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb
index 08a16d5c9e..5e5f7a798e 100644
--- a/activerecord/test/schema/schema.rb
+++ b/activerecord/test/schema/schema.rb
@@ -680,6 +680,7 @@ ActiveRecord::Schema.define do
create_table :ship_parts, force: true do |t|
t.string :name
t.integer :ship_id
+ t.datetime :updated_at
end
create_table :speedometers, force: true, id: false do |t|
diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md
index 361571db98..43fb87f203 100644
--- a/activesupport/CHANGELOG.md
+++ b/activesupport/CHANGELOG.md
@@ -1,3 +1,13 @@
+* Added `#without` on `Enumerable` and `Array` to return a copy of an
+ enumerable without the specified elements.
+
+ *Todd Bealmear*
+
+* Fixed a problem where String#truncate_words would get stuck with a complex
+ string.
+
+ *Henrik Nygren*
+
* Fixed a roundtrip problem with AS::SafeBuffer where primitive-like strings
will be dumped as primitives:
diff --git a/activesupport/lib/active_support/cache.rb b/activesupport/lib/active_support/cache.rb
index 3a1e1ac3a1..fdef9cbfc0 100644
--- a/activesupport/lib/active_support/cache.rb
+++ b/activesupport/lib/active_support/cache.rb
@@ -325,19 +325,22 @@ module ActiveSupport
def read_multi(*names)
options = names.extract_options!
options = merged_options(options)
- results = {}
- names.each do |name|
- key = namespaced_key(name, options)
- entry = read_entry(key, options)
- if entry
- if entry.expired?
- delete_entry(key, options)
- else
- results[name] = entry.value
+
+ instrument_multi(:read, names, options) do |payload|
+ results = {}
+ names.each do |name|
+ key = namespaced_key(name, options)
+ entry = read_entry(key, options)
+ if entry
+ if entry.expired?
+ delete_entry(key, options)
+ else
+ results[name] = entry.value
+ end
end
end
+ results
end
- results
end
# Fetches data from the cache, using the given keys. If there is data in
@@ -527,16 +530,27 @@ module ActiveSupport
end
def instrument(operation, key, options = nil)
- log(operation, key, options)
+ log { "Cache #{operation}: #{key}#{options.blank? ? "" : " (#{options.inspect})"}" }
payload = { :key => key }
payload.merge!(options) if options.is_a?(Hash)
ActiveSupport::Notifications.instrument("cache_#{operation}.active_support", payload){ yield(payload) }
end
- def log(operation, key, options = nil)
+ def instrument_multi(operation, keys, options = nil)
+ log do
+ formatted_keys = keys.map { |k| "- #{k}" }.join("\n")
+ "Caches multi #{operation}:\n#{formatted_keys}#{options.blank? ? "" : " (#{options.inspect})"}"
+ end
+
+ payload = { key: keys }
+ payload.merge!(options) if options.is_a?(Hash)
+ ActiveSupport::Notifications.instrument("cache_#{operation}_multi.active_support", payload) { yield(payload) }
+ end
+
+ def log
return unless logger && logger.debug? && !silence?
- logger.debug("Cache #{operation}: #{key}#{options.blank? ? "" : " (#{options.inspect})"}")
+ logger.debug(yield)
end
def find_cached_entry(key, name, options)
diff --git a/activesupport/lib/active_support/cache/mem_cache_store.rb b/activesupport/lib/active_support/cache/mem_cache_store.rb
index 61b4f0b8b0..73ae3acea5 100644
--- a/activesupport/lib/active_support/cache/mem_cache_store.rb
+++ b/activesupport/lib/active_support/cache/mem_cache_store.rb
@@ -66,14 +66,17 @@ module ActiveSupport
def read_multi(*names)
options = names.extract_options!
options = merged_options(options)
- keys_to_names = Hash[names.map{|name| [escape_key(namespaced_key(name, options)), name]}]
- raw_values = @data.get_multi(keys_to_names.keys, :raw => true)
- values = {}
- raw_values.each do |key, value|
- entry = deserialize_entry(value)
- values[keys_to_names[key]] = entry.value unless entry.expired?
+
+ instrument_multi(:read, names, options) do
+ keys_to_names = Hash[names.map{|name| [escape_key(namespaced_key(name, options)), name]}]
+ raw_values = @data.get_multi(keys_to_names.keys, :raw => true)
+ values = {}
+ raw_values.each do |key, value|
+ entry = deserialize_entry(value)
+ values[keys_to_names[key]] = entry.value unless entry.expired?
+ end
+ values
end
- values
end
# Increment a cached value. This method uses the memcached incr atomic
diff --git a/activesupport/lib/active_support/core_ext/array/grouping.rb b/activesupport/lib/active_support/core_ext/array/grouping.rb
index 87ae052eb0..b3ada47880 100644
--- a/activesupport/lib/active_support/core_ext/array/grouping.rb
+++ b/activesupport/lib/active_support/core_ext/array/grouping.rb
@@ -113,4 +113,16 @@ class Array
results
end
end
+
+ # Returns a copy of the Array without the specified elements.
+ #
+ # people = ["David", "Rafael", "Aaron", "Todd"]
+ # people.without "Aaron", "Todd"
+ # => ["David", "Rafael"]
+ #
+ # Note: This is an optimization of `Enumerable#without` that uses `Array#-`
+ # instead of `Array#reject` for performance reasons.
+ def without(*elements)
+ self - elements
+ end
end
diff --git a/activesupport/lib/active_support/core_ext/enumerable.rb b/activesupport/lib/active_support/core_ext/enumerable.rb
index 1343beb87a..7a893292b3 100644
--- a/activesupport/lib/active_support/core_ext/enumerable.rb
+++ b/activesupport/lib/active_support/core_ext/enumerable.rb
@@ -60,6 +60,17 @@ module Enumerable
def exclude?(object)
!include?(object)
end
+
+ # Returns a copy of the enumerable without the specified elements.
+ #
+ # ["David", "Rafael", "Aaron", "Todd"].without "Aaron", "Todd"
+ # => ["David", "Rafael"]
+ #
+ # {foo: 1, bar: 2, baz: 3}.without :bar
+ # => {foo: 1, baz: 3}
+ def without(*elements)
+ reject { |element| elements.include?(element) }
+ end
end
class Range #:nodoc:
diff --git a/activesupport/lib/active_support/core_ext/module/anonymous.rb b/activesupport/lib/active_support/core_ext/module/anonymous.rb
index b0c7b021db..0ecc67a855 100644
--- a/activesupport/lib/active_support/core_ext/module/anonymous.rb
+++ b/activesupport/lib/active_support/core_ext/module/anonymous.rb
@@ -7,6 +7,13 @@ class Module
# m = Module.new
# m.name # => nil
#
+ # +anonymous?+ method returns true if module does not have a name:
+ #
+ # Module.new.anonymous? # => true
+ #
+ # module M; end
+ # M.anonymous? # => false
+ #
# A module gets a name when it is first assigned to a constant. Either
# via the +module+ or +class+ keyword or by an explicit assignment:
#
diff --git a/activesupport/lib/active_support/core_ext/module/delegation.rb b/activesupport/lib/active_support/core_ext/module/delegation.rb
index a5f4d03256..9b7a429db9 100644
--- a/activesupport/lib/active_support/core_ext/module/delegation.rb
+++ b/activesupport/lib/active_support/core_ext/module/delegation.rb
@@ -167,7 +167,7 @@ class Module
''
end
- file, line = caller.first.split(':', 2)
+ file, line = caller(1, 1).first.split(':', 2)
line = line.to_i
to = to.to_s
diff --git a/activesupport/lib/active_support/core_ext/range/conversions.rb b/activesupport/lib/active_support/core_ext/range/conversions.rb
index b1a12781f3..83eced50bf 100644
--- a/activesupport/lib/active_support/core_ext/range/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/range/conversions.rb
@@ -3,9 +3,24 @@ class Range
:db => Proc.new { |start, stop| "BETWEEN '#{start.to_s(:db)}' AND '#{stop.to_s(:db)}'" }
}
- # Gives a human readable format of the range.
+ # Convert range to a formatted string. See RANGE_FORMATS for predefined formats.
#
- # (1..100).to_formatted_s # => "1..100"
+ # This method is aliased to <tt>to_s</tt>.
+ #
+ # range = (1..100) # => 1..100
+ #
+ # range.to_formatted_s # => "1..100"
+ # range.to_s # => "1..100"
+ #
+ # range.to_formatted_s(:db) # => "BETWEEN '1' AND '100'"
+ # range.to_s(:db) # => "BETWEEN '1' AND '100'"
+ #
+ # == Adding your own range formats to to_formatted_s
+ # You can add your own formats to the Range::RANGE_FORMATS hash.
+ # Use the format name as the hash key and a Proc instance.
+ #
+ # # config/initializers/range_formats.rb
+ # Range::RANGE_FORMATS[:short] = ->(start, stop) { "Between #{start.to_s(:db)} and #{stop.to_s(:db)}" }
def to_formatted_s(format = :default)
if formatter = RANGE_FORMATS[format]
formatter.call(first, last)
diff --git a/activesupport/lib/active_support/core_ext/string/filters.rb b/activesupport/lib/active_support/core_ext/string/filters.rb
index 096292dc58..7461d03acc 100644
--- a/activesupport/lib/active_support/core_ext/string/filters.rb
+++ b/activesupport/lib/active_support/core_ext/string/filters.rb
@@ -26,6 +26,7 @@ class String
# Returns a new string with all occurrences of the patterns removed.
# str = "foo bar test"
# str.remove(" test") # => "foo bar"
+ # str.remove(" test", /bar/) # => "foo "
# str # => "foo bar test"
def remove(*patterns)
dup.remove!(*patterns)
@@ -33,8 +34,8 @@ class String
# Alters the string by removing all occurrences of the patterns.
# str = "foo bar test"
- # str.remove!(" test") # => "foo bar"
- # str # => "foo bar"
+ # str.remove!(" test", /bar/) # => "foo "
+ # str # => "foo "
def remove!(*patterns)
patterns.each do |pattern|
gsub! pattern, ""
@@ -93,7 +94,7 @@ class String
def truncate_words(words_count, options = {})
sep = options[:separator] || /\s+/
sep = Regexp.escape(sep.to_s) unless Regexp === sep
- if self =~ /\A((?:.+?#{sep}){#{words_count - 1}}.+?)#{sep}.*/m
+ if self =~ /\A((?>.+?#{sep}){#{words_count - 1}}.+?)#{sep}.*/m
$1 + (options[:omission] || '...')
else
dup
diff --git a/activesupport/lib/active_support/core_ext/string/multibyte.rb b/activesupport/lib/active_support/core_ext/string/multibyte.rb
index 2eedd4fdb1..57d7f8d1e7 100644
--- a/activesupport/lib/active_support/core_ext/string/multibyte.rb
+++ b/activesupport/lib/active_support/core_ext/string/multibyte.rb
@@ -35,6 +35,13 @@ class String
ActiveSupport::Multibyte.proxy_class.new(self)
end
+ # Return +true+ if string has utf_8 encoding.
+ #
+ # utf_8_str = "some string".encode "UTF-8"
+ # iso_str = "some string".encode "ISO-8859-1"
+ #
+ # utf_8_str.is_utf8? # => true
+ # iso_str.is_utf8? # => false
def is_utf8?
case encoding
when Encoding::UTF_8
diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb
index 98f3ea7a14..7f5f8feb0d 100644
--- a/activesupport/test/caching_test.rb
+++ b/activesupport/test/caching_test.rb
@@ -1021,6 +1021,15 @@ class CacheStoreLoggerTest < ActiveSupport::TestCase
@cache.mute { @cache.fetch('foo') { 'bar' } }
assert @buffer.string.blank?
end
+
+ def test_multi_read_loggin
+ @cache.write 'hello', 'goodbye'
+ @cache.write 'world', 'earth'
+
+ @cache.read_multi('hello', 'world')
+
+ assert_match "Caches multi read:\n- hello\n- world", @buffer.string
+ end
end
class CacheEntryTest < ActiveSupport::TestCase
diff --git a/activesupport/test/core_ext/enumerable_test.rb b/activesupport/test/core_ext/enumerable_test.rb
index 346dc3d208..e5d8ae7882 100644
--- a/activesupport/test/core_ext/enumerable_test.rb
+++ b/activesupport/test/core_ext/enumerable_test.rb
@@ -103,4 +103,11 @@ class EnumerableTests < ActiveSupport::TestCase
assert_equal true, GenericEnumerable.new([ 1 ]).exclude?(2)
assert_equal false, GenericEnumerable.new([ 1 ]).exclude?(1)
end
+
+ def test_without
+ assert_equal [1, 2, 4], GenericEnumerable.new((1..5).to_a).without(3, 5)
+ assert_equal [1, 2, 4], (1..5).to_a.without(3, 5)
+ assert_equal [1, 2, 4], (1..5).to_set.without(3, 5)
+ assert_equal({foo: 1, baz: 3}, {foo: 1, bar: 2, baz: 3}.without(:bar))
+ end
end
diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb
index 24037c665a..cb24147ab3 100644
--- a/activesupport/test/core_ext/string_ext_test.rb
+++ b/activesupport/test/core_ext/string_ext_test.rb
@@ -249,6 +249,15 @@ class StringInflectionsTest < ActiveSupport::TestCase
assert_equal "Hello<br>Big<br>World!", "Hello<br>Big<br>World!".truncate_words(3, :omission => "[...]", :separator => '<br>')
end
+ def test_truncate_words_with_complex_string
+ Timeout.timeout(10) do
+ complex_string = "aa aa aaa aa aaa aaa aaa aa aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa aaaa aaaaa aaaaa aaaaaa aa aa aa aaa aa aaa aa aa aa aa a aaa aaa \n a aaa <<s"
+ assert_equal complex_string.truncate_words(80), complex_string
+ end
+ rescue Timeout::Error
+ assert false
+ end
+
def test_truncate_multibyte
assert_equal "\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 ...".force_encoding(Encoding::UTF_8),
"\354\225\204\353\246\254\353\236\221 \354\225\204\353\246\254 \354\225\204\353\235\274\353\246\254\354\230\244".force_encoding(Encoding::UTF_8).truncate(10)
diff --git a/guides/Rakefile b/guides/Rakefile
index fd093b94c1..3c2099ac02 100644
--- a/guides/Rakefile
+++ b/guides/Rakefile
@@ -11,7 +11,7 @@ namespace :guides do
ruby "rails_guides.rb"
end
- desc "Generate .mobi file. The kindlegen executable must be in your PATH. You can get it for free from http://www.amazon.com/kindlepublishing"
+ desc "Generate .mobi file. The kindlegen executable must be in your PATH. You can get it for free from http://www.amazon.com/gp/feature.html?docId=1000765211"
task :kindle do
unless `kindlerb -v 2> /dev/null` =~ /kindlerb 0.1.1/
abort "Please `gem install kindlerb` and make sure you have `kindlegen` in your PATH"
diff --git a/guides/rails_guides/levenshtein.rb b/guides/rails_guides/levenshtein.rb
index 8a908a4339..36183fd321 100644
--- a/guides/rails_guides/levenshtein.rb
+++ b/guides/rails_guides/levenshtein.rb
@@ -7,11 +7,9 @@ module RailsGuides
t = str2
n = s.length
m = t.length
- max = n/2
return m if (0 == n)
return n if (0 == m)
- return n if (n - m).abs > max
d = (0..m).to_a
x = nil
diff --git a/guides/source/4_0_release_notes.md b/guides/source/4_0_release_notes.md
index 67f4a3c02c..bd35e2d31a 100644
--- a/guides/source/4_0_release_notes.md
+++ b/guides/source/4_0_release_notes.md
@@ -73,7 +73,7 @@ Major Features
* **Strong parameters** ([commit](https://github.com/rails/rails/commit/a8f6d5c6450a7fe058348a7f10a908352bb6c7fc)) - Only allow whitelisted parameters to update model objects (`params.permit(:title, :text)`).
* **Routing concerns** ([commit](https://github.com/rails/rails/commit/0dd24728a088fcb4ae616bb5d62734aca5276b1b)) - In the routing DSL, factor out common subroutes (`comments` from `/posts/1/comments` and `/videos/1/comments`).
* **ActionController::Live** ([commit](https://github.com/rails/rails/commit/af0a9f9eefaee3a8120cfd8d05cbc431af376da3)) - Stream JSON with `response.stream`.
- * **Declarative ETags** ([commit](https://github.com/rails/rails/commit/ed5c938fa36995f06d4917d9543ba78ed506bb8d)) - Add controller-level etag additions that will be part of the action etag computation
+ * **Declarative ETags** ([commit](https://github.com/rails/rails/commit/ed5c938fa36995f06d4917d9543ba78ed506bb8d)) - Add controller-level etag additions that will be part of the action etag computation.
* **[Russian doll caching](http://37signals.com/svn/posts/3113-how-key-based-cache-expiration-works)** ([commit](https://github.com/rails/rails/commit/4154bf012d2bec2aae79e4a49aa94a70d3e91d49)) - Cache nested fragments of views. Each fragment expires based on a set of dependencies (a cache key). The cache key is usually a template version number and a model object.
* **Turbolinks** ([commit](https://github.com/rails/rails/commit/e35d8b18d0649c0ecc58f6b73df6b3c8d0c6bb74)) - Serve only one initial HTML page. When the user navigates to another page, use pushState to update the URL and use AJAX to update the title and body.
* **Decouple ActionView from ActionController** ([commit](https://github.com/rails/rails/commit/78b0934dd1bb84e8f093fb8ef95ca99b297b51cd)) - ActionView was decoupled from ActionPack and will be moved to a separated gem in Rails 4.1.
@@ -181,7 +181,7 @@ Please refer to the [Changelog](https://github.com/rails/rails/blob/4-0-stable/a
* `String#to_date` now raises `ArgumentError: invalid date` instead of `NoMethodError: undefined method 'div' for nil:NilClass`
when given an invalid date. It is now the same as `Date.parse`, and it accepts more invalid dates than 3.x, such as:
- ```
+ ```ruby
# ActiveSupport 3.x
"asdf".to_date # => NoMethodError: undefined method `div' for nil:NilClass
"333".to_date # => NoMethodError: undefined method `div' for nil:NilClass
diff --git a/guides/source/4_1_release_notes.md b/guides/source/4_1_release_notes.md
index 8d5557be6e..6bf65757ec 100644
--- a/guides/source/4_1_release_notes.md
+++ b/guides/source/4_1_release_notes.md
@@ -317,15 +317,15 @@ for detailed changes.
* Removed deprecated constants from Action Controller:
- | Removed | Successor |
- |:-----------------------------------|:--------------------------------|
- | ActionController::AbstractRequest | ActionDispatch::Request |
- | ActionController::Request | ActionDispatch::Request |
- | ActionController::AbstractResponse | ActionDispatch::Response |
- | ActionController::Response | ActionDispatch::Response |
- | ActionController::Routing | ActionDispatch::Routing |
- | ActionController::Integration | ActionDispatch::Integration |
- | ActionController::IntegrationTest | ActionDispatch::IntegrationTest |
+| Removed | Successor |
+|:-----------------------------------|:--------------------------------|
+| ActionController::AbstractRequest | ActionDispatch::Request |
+| ActionController::Request | ActionDispatch::Request |
+| ActionController::AbstractResponse | ActionDispatch::Response |
+| ActionController::Response | ActionDispatch::Response |
+| ActionController::Routing | ActionDispatch::Routing |
+| ActionController::Integration | ActionDispatch::Integration |
+| ActionController::IntegrationTest | ActionDispatch::IntegrationTest |
### Notable changes
diff --git a/guides/source/active_record_validations.md b/guides/source/active_record_validations.md
index d65c15bcf3..f19934fe89 100644
--- a/guides/source/active_record_validations.md
+++ b/guides/source/active_record_validations.md
@@ -917,8 +917,8 @@ write your own validators or validation methods as you prefer.
### Custom Validators
-Custom validators are classes that extend `ActiveModel::Validator`. These
-classes must implement a `validate` method which takes a record as an argument
+Custom validators are classes that inherit from `ActiveModel::Validator`. These
+classes must implement the `validate` method which takes a record as an argument
and performs the validation on it. The custom validator is called using the
`validates_with` method.
diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md
index 0fbd6ed7e1..66626f41d1 100644
--- a/guides/source/active_support_core_extensions.md
+++ b/guides/source/active_support_core_extensions.md
@@ -349,7 +349,7 @@ end
we get:
```ruby
-current_user.to_query('user') # => user=357-john-smith
+current_user.to_query('user') # => "user=357-john-smith"
```
This method escapes whatever is needed, both for the key and the value:
@@ -727,7 +727,7 @@ NOTE: Defined in `active_support/core_ext/module/introspection.rb`.
#### Qualified Constant Names
-The standard methods `const_defined?`, `const_get` , and `const_set` accept
+The standard methods `const_defined?`, `const_get`, and `const_set` accept
bare constant names. Active Support extends this API to be able to pass
relative qualified constant names.
@@ -1237,7 +1237,7 @@ Calling `dup` or `clone` on safe strings yields safe strings.
The method `remove` will remove all occurrences of the pattern:
```ruby
-"Hello World".remove(/Hello /) => "World"
+"Hello World".remove(/Hello /) # => "World"
```
There's also the destructive version `String#remove!`.
@@ -2182,6 +2182,17 @@ to_visit << node if visited.exclude?(node)
NOTE: Defined in `active_support/core_ext/enumerable.rb`.
+### `without`
+
+The method `without` returns a copy of an enumerable with the specified elements
+removed:
+
+```ruby
+people.without("Aaron", "Todd")
+```
+
+NOTE: Defined in `active_support/core_ext/enumerable.rb`.
+
Extensions to `Array`
---------------------
diff --git a/guides/source/active_support_instrumentation.md b/guides/source/active_support_instrumentation.md
index 9d9f40e956..352da43b5f 100644
--- a/guides/source/active_support_instrumentation.md
+++ b/guides/source/active_support_instrumentation.md
@@ -218,7 +218,7 @@ Action View
```ruby
{
- identifier: "/Users/adam/projects/notifications/app/views/posts/_form.html.erb",
+ identifier: "/Users/adam/projects/notifications/app/views/posts/_form.html.erb"
}
```
@@ -307,7 +307,7 @@ Action Mailer
}
```
-ActiveResource
+Active Resource
--------------
### request.active_resource
diff --git a/guides/source/asset_pipeline.md b/guides/source/asset_pipeline.md
index 52ea605a72..6f8b4f4d15 100644
--- a/guides/source/asset_pipeline.md
+++ b/guides/source/asset_pipeline.md
@@ -729,27 +729,6 @@ include, you can add them to the `precompile` array in `config/initializers/asse
Rails.application.config.assets.precompile += ['admin.js', 'admin.css', 'swfObject.js']
```
-Or, you can opt to precompile all assets with something like this:
-
-```ruby
-# config/initializers/assets.rb
-Rails.application.config.assets.precompile << Proc.new do |path|
- if path =~ /\.(css|js)\z/
- full_path = Rails.application.assets.resolve(path).to_path
- app_assets_path = Rails.root.join('app', 'assets').to_path
- if full_path.starts_with? app_assets_path
- logger.info "including asset: " + full_path
- true
- else
- logger.info "excluding asset: " + full_path
- false
- end
- else
- false
- end
-end
-```
-
NOTE. Always specify an expected compiled filename that ends with .js or .css,
even if you want to add Sass or CoffeeScript files to the precompile array.
diff --git a/guides/source/association_basics.md b/guides/source/association_basics.md
index d6b2e75e1e..280c3008e9 100644
--- a/guides/source/association_basics.md
+++ b/guides/source/association_basics.md
@@ -460,7 +460,7 @@ class CreatePictures < ActiveRecord::Migration
t.timestamps null: false
end
- add_index :pictures, :imageable_id
+ add_index :pictures, [:imageable_type, :imageable_id]
end
end
```
diff --git a/guides/source/caching_with_rails.md b/guides/source/caching_with_rails.md
index 0fa20f7ccf..716beb9178 100644
--- a/guides/source/caching_with_rails.md
+++ b/guides/source/caching_with_rails.md
@@ -32,7 +32,7 @@ config.action_controller.perform_caching = true
Page caching is a Rails mechanism which allows the request for a generated page to be fulfilled by the webserver (i.e. Apache or NGINX), without ever having to go through the Rails stack at all. Obviously, this is super-fast. Unfortunately, it can't be applied to every situation (such as pages that need authentication) and since the webserver is literally just serving a file from the filesystem, cache expiration is an issue that needs to be dealt with.
-INFO: Page Caching has been removed from Rails 4. See the [actionpack-page_caching gem](https://github.com/rails/actionpack-page_caching). See [DHH's key-based cache expiration overview](http://signalvnoise.com/posts/3113-how-key-based-cache-expiration-works) for the newly-preferred method.
+INFO: Page Caching has been removed from Rails 4. See the [actionpack-page_caching gem](https://github.com/rails/actionpack-page_caching).
### Action Caching
diff --git a/guides/source/command_line.md b/guides/source/command_line.md
index 19ccdc5488..6f5a6b7957 100644
--- a/guides/source/command_line.md
+++ b/guides/source/command_line.md
@@ -338,6 +338,12 @@ You can specify the environment in which the `runner` command should operate usi
$ bin/rails runner -e staging "Model.long_running_method"
```
+You can even execute ruby code written in a file with runner.
+
+```bash
+$ bin/rails runner lib/code_to_be_run.rb
+```
+
### `rails destroy`
Think of `destroy` as the opposite of `generate`. It'll figure out what generate did, and undo it.
diff --git a/guides/source/debugging_rails_applications.md b/guides/source/debugging_rails_applications.md
index 926a048762..9cb2efb9a2 100644
--- a/guides/source/debugging_rails_applications.md
+++ b/guides/source/debugging_rails_applications.md
@@ -242,55 +242,6 @@ The contents of the block, and therefore the string interpolation, is only
evaluated if debug is enabled. This performance savings is only really
noticeable with large amounts of logging, but it's a good practice to employ.
-
-Debugging with the `web-console` gem
--------------------------------------
-
-The web console allows you to start an interactive Ruby session in your browser.
-An interactive console is launched automatically in case of an error but can also
-be launched for debugging purposes by invoking `console` in a view or controller.
-
-For example in a view:
-
-```ruby
-# new.html.erb
-<%= console %>
-```
-
-Or in a controller:
-
-```ruby
-# posts_controller.rb
-class PostsController < ApplicationController
- def new
- console
- @post = Post.new
- end
-end
-```
-
-### config.web_console.whitelisted_ips
-
-By default the web console can only be accessed from localhost.
-`config.web_console.whitelisted_ips` lets you control which IPs have access to
-the console.
-
-For example, to allow access from both localhost and 192.168.0.100, you can put
-inside your configuration file:
-
-```ruby
-config.web_console.whitelisted_ips = %w( 127.0.0.1 192.168.0.100 )
-```
-
-Or to allow access from an entire network:
-
-```ruby
-config.web_console.whitelisted_ips = %w( 127.0.0.1 192.168.0.0/16 )
-```
-
-The web console is a powerful tool so be careful when you give access to an IP.
-
-
Debugging with the `byebug` gem
---------------------------------
@@ -831,10 +782,10 @@ will be stopped and you will have to start it again.
`byebug` has a few available options to tweak its behaviour:
-* `set autoreload`: Reload source code when changed (default: true).
-* `set autolist`: Execute `list` command on every breakpoint (default: true).
+* `set autoreload`: Reload source code when changed (defaults: true).
+* `set autolist`: Execute `list` command on every breakpoint (defaults: true).
* `set listsize _n_`: Set number of source lines to list by default to _n_
-(default: 10)
+(defaults: 10)
* `set forcestep`: Make sure the `next` and `step` commands always move to a new
line.
@@ -849,6 +800,63 @@ set forcestep
set listsize 25
```
+Debugging with the `web-console` gem
+------------------------------------
+
+Web Console is a bit like `byebug`, but it runs in the browser. In any page you
+are developing, you can request a console in the context of a view or a
+controller. The console would be rendered next to your HTML content.
+
+### Console
+
+Inside any controller action or view, you can then invoke the console by
+calling the `console` method.
+
+For example, in a controller:
+
+```ruby
+class PostController < ApplicationController
+ def new
+ console
+ @post = Post.new
+ end
+end
+```
+
+Or in a view:
+
+```html+erb
+<% console %>
+
+<h2>New Post</h2>
+```
+
+This will render a console inside your view. You don't need to care about the
+location of the `console` call; it won't be rendered on the spot of its
+invocation but next to your HTML content.
+
+The console executes pure Ruby code. You can define and instantiate
+custom classes, create new models and inspect variables.
+
+NOTE: Only one console can be rendered per request. Otherwise `web-console`
+will raise an error on the second `console` invocation.
+
+### Inspecting Variables
+
+You can invoke `instance_variables` to list all the instance variables
+available in your context. If you want to list all the local variables, you can
+do that with `local_variables`.
+
+### Settings
+
+* `config.web_console.whitelisted_ips`: Authorized list of IPv4 or IPv6
+addresses and networks (defaults: `127.0.0.1/8, ::1`).
+* `config.web_console.whiny_requests`: Log a message when a console rendering
+is prevented (defaults: `true`).
+
+Since `web-console` evaluates plain Ruby code remotely on the server, don't try
+to use it in production.
+
Debugging Memory Leaks
----------------------
@@ -905,6 +913,7 @@ References
* [ruby-debug Homepage](http://bashdb.sourceforge.net/ruby-debug/home-page.html)
* [debugger Homepage](https://github.com/cldwalker/debugger)
* [byebug Homepage](https://github.com/deivid-rodriguez/byebug)
+* [web-console Homepage](https://github.com/rails/web-console)
* [Article: Debugging a Rails application with ruby-debug](http://www.sitepoint.com/debug-rails-app-ruby-debug/)
* [Ryan Bates' debugging ruby (revised) screencast](http://railscasts.com/episodes/54-debugging-ruby-revised)
* [Ryan Bates' stack trace screencast](http://railscasts.com/episodes/24-the-stack-trace)
diff --git a/guides/source/form_helpers.md b/guides/source/form_helpers.md
index 90004c611b..c21a2ba613 100644
--- a/guides/source/form_helpers.md
+++ b/guides/source/form_helpers.md
@@ -729,7 +729,7 @@ The two basic structures are arrays and hashes. Hashes mirror the syntax used fo
the `params` hash will contain
-```erb
+```ruby
{'person' => {'name' => 'Henry'}}
```
diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md
index 51b8a2ca5f..66cfb72aaf 100644
--- a/guides/source/getting_started.md
+++ b/guides/source/getting_started.md
@@ -1479,13 +1479,14 @@ Finally, add a 'Destroy' link to your `index` action template
```
Here we're using `link_to` in a different way. We pass the named route as the
-second argument, and then the options as another argument. The `:method` and
-`:'data-confirm'` options are used as HTML5 attributes so that when the link is
-clicked, Rails will first show a confirm dialog to the user, and then submit the
-link with method `delete`. This is done via the JavaScript file `jquery_ujs`
-which is automatically included into your application's layout
-(`app/views/layouts/application.html.erb`) when you generated the application.
-Without this file, the confirmation dialog box wouldn't appear.
+second argument, and then the options as another argument. The `method: :delete`
+and `data: { confirm: 'Are you sure?' }` options are used as HTML5 attributes so
+that when the link is clicked, Rails will first show a confirm dialog to the
+user, and then submit the link with method `delete`. This is done via the
+JavaScript file `jquery_ujs` which is automatically included in your
+application's layout (`app/views/layouts/application.html.erb`) when you
+generated the application. Without this file, the confirmation dialog box won't
+appear.
![Confirm Dialog](images/getting_started/confirm_dialog.png)
diff --git a/guides/source/i18n.md b/guides/source/i18n.md
index 4dc4c5a660..1e34261272 100644
--- a/guides/source/i18n.md
+++ b/guides/source/i18n.md
@@ -1093,11 +1093,8 @@ Resources
Authors
-------
-* [Sven Fuchs](http://www.workingwithrails.com/person/9963-sven-fuchs) (initial author)
-* [Karel Minařík](http://www.workingwithrails.com/person/7476-karel-mina-k)
-
-If you found this guide useful, please consider recommending its authors on [workingwithrails](http://www.workingwithrails.com).
-
+* [Sven Fuchs](http://svenfuchs.com) (initial author)
+* [Karel Minařík](http://www.karmi.cz)
Footnotes
---------
diff --git a/guides/source/layouts_and_rendering.md b/guides/source/layouts_and_rendering.md
index 329d501ce0..5c7fad09ed 100644
--- a/guides/source/layouts_and_rendering.md
+++ b/guides/source/layouts_and_rendering.md
@@ -563,6 +563,42 @@ In this application:
* `OldArticlesController#show` will use no layout at all
* `OldArticlesController#index` will use the `old` layout
+##### Template Inheritance
+
+Similar to the Layout Inheritance logic, if a template or partial is not found in the conventional path, the controller will look for a template or partial to render in its inheritance chain. For example:
+
+```ruby
+# in app/controllers/application_controller
+class ApplicationController < ActionController::Base
+end
+
+# in app/controllers/admin_controller
+class AdminController < ApplicationController
+end
+
+# in app/controllers/admin/products_controller
+class Admin::ProductsController < AdminController
+ def index
+ end
+end
+```
+
+The lookup order for a `admin/products#index` action will be:
+
+* `app/views/admin/products/`
+* `app/views/admin/`
+* `app/views/application/`
+
+This makes `app/views/application/` a great place for your shared partials, which can then be rendered in your ERb as such:
+
+```erb
+<%# app/views/admin/products/index.html.erb %>
+<%= render @products || "empty_list" %>
+
+<%# app/views/application/_empty_list.html.erb %>
+There are no items in this list <em>yet</em>.
+```
+
#### Avoiding Double Render Errors
Sooner or later, most Rails developers will see the error message "Can only render or redirect once per action". While this is annoying, it's relatively easy to fix. Usually it happens because of a fundamental misunderstanding of the way that `render` works.
diff --git a/guides/source/routing.md b/guides/source/routing.md
index a689e131ff..b5defc9d20 100644
--- a/guides/source/routing.md
+++ b/guides/source/routing.md
@@ -229,7 +229,7 @@ or, for a single case:
resources :articles, path: '/admin/articles'
```
-In each of these cases, the named routes remain the same as if you did not use `scope`. In the last case, the following paths map to `PostsController`:
+In each of these cases, the named routes remain the same as if you did not use `scope`. In the last case, the following paths map to `ArticlesController`:
| HTTP Verb | Path | Controller#Action | Named Helper |
| --------- | ------------------------ | -------------------- | ---------------------- |
diff --git a/guides/source/testing.md b/guides/source/testing.md
index 14bc75aa7d..cb3bd68fbe 100644
--- a/guides/source/testing.md
+++ b/guides/source/testing.md
@@ -450,6 +450,7 @@ All the basic assertions such as `assert_equal` defined in `Minitest::Assertions
* `ActionMailer::TestCase`
* `ActionView::TestCase`
* `ActionDispatch::IntegrationTest`
+* `ActiveJob::TestCase`
Each of these classes include `Minitest::Assertions`, allowing us to use all of the basic assertions in our tests.
diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md
index df9f8fe993..8b10144413 100644
--- a/railties/CHANGELOG.md
+++ b/railties/CHANGELOG.md
@@ -1,3 +1,17 @@
+* Created rake restart task. Restarts your Rails app by touching the
+ `tmp/restart.txt`.
+
+ Fixes #18876.
+
+ *Hyonjee Joo*
+
+* Set Rails console to use log formatter and log level as specified for the
+ given environment.
+
+ Fixes #15470.
+
+ *Jacob Evelyn*
+
* Add `config/initializers/active_record_belongs_to_required_by_default.rb`
Newly generated Rails apps have a new initializer called
diff --git a/railties/lib/rails/code_statistics.rb b/railties/lib/rails/code_statistics.rb
index 0bdf63943f..583d005d46 100644
--- a/railties/lib/rails/code_statistics.rb
+++ b/railties/lib/rails/code_statistics.rb
@@ -71,12 +71,12 @@ class CodeStatistics #:nodoc:
def print_header
print_splitter
- puts "| Name | Lines | LOC | Classes | Methods | M/C | LOC/M |"
+ puts "| Name | Lines | LOC | Classes | Methods | M/C | LOC/M |"
print_splitter
end
def print_splitter
- puts "+----------------------+-------+-------+---------+---------+-----+-------+"
+ puts "+----------------------+--------+--------+---------+---------+-----+-------+"
end
def print_line(name, statistics)
@@ -84,8 +84,8 @@ class CodeStatistics #:nodoc:
loc_over_m = (statistics.code_lines / statistics.methods) - 2 rescue loc_over_m = 0
puts "| #{name.ljust(20)} " \
- "| #{statistics.lines.to_s.rjust(5)} " \
- "| #{statistics.code_lines.to_s.rjust(5)} " \
+ "| #{statistics.lines.to_s.rjust(6)} " \
+ "| #{statistics.code_lines.to_s.rjust(6)} " \
"| #{statistics.classes.to_s.rjust(7)} " \
"| #{statistics.methods.to_s.rjust(7)} " \
"| #{m_over_c.to_s.rjust(3)} " \
diff --git a/railties/lib/rails/info_controller.rb b/railties/lib/rails/info_controller.rb
index 49e5431a16..6e61cc3cb5 100644
--- a/railties/lib/rails/info_controller.rb
+++ b/railties/lib/rails/info_controller.rb
@@ -17,7 +17,28 @@ class Rails::InfoController < Rails::ApplicationController # :nodoc:
end
def routes
- @routes_inspector = ActionDispatch::Routing::RoutesInspector.new(_routes.routes)
- @page_title = 'Routes'
+ if path = params[:path]
+ path = URI.escape path
+ normalized_path = with_leading_slash path
+ render json: {
+ exact: match_route {|it| it.match normalized_path },
+ fuzzy: match_route {|it| it.spec.to_s.match path }
+ }
+ else
+ @routes_inspector = ActionDispatch::Routing::RoutesInspector.new(_routes.routes)
+ @page_title = 'Routes'
+ end
+ end
+
+ private
+
+ def match_route
+ _routes.routes.select {|route|
+ yield route.path
+ }.map {|route| route.path.spec.to_s }
+ end
+
+ def with_leading_slash(path)
+ ('/' + path).squeeze('/')
end
end
diff --git a/railties/lib/rails/paths.rb b/railties/lib/rails/paths.rb
index 5458036219..ebcaaaba46 100644
--- a/railties/lib/rails/paths.rb
+++ b/railties/lib/rails/paths.rb
@@ -7,7 +7,7 @@ module Rails
# root = Root.new "/rails"
# root.add "app/controllers", eager_load: true
#
- # The command above creates a new root object and add "app/controllers" as a path.
+ # The command above creates a new root object and adds "app/controllers" as a path.
# This means we can get a <tt>Rails::Paths::Path</tt> object back like below:
#
# path = root["app/controllers"]
diff --git a/railties/lib/rails/tasks.rb b/railties/lib/rails/tasks.rb
index 945fbdb3e2..a5e4d2935e 100644
--- a/railties/lib/rails/tasks.rb
+++ b/railties/lib/rails/tasks.rb
@@ -7,6 +7,7 @@ require 'rake'
log
middleware
misc
+ restart
routes
statistics
tmp
diff --git a/railties/lib/rails/tasks/restart.rake b/railties/lib/rails/tasks/restart.rake
new file mode 100644
index 0000000000..1e8940b675
--- /dev/null
+++ b/railties/lib/rails/tasks/restart.rake
@@ -0,0 +1,4 @@
+desc "Restart app by touching tmp/restart.txt"
+task :restart do
+ FileUtils.touch('tmp/restart.txt')
+end
diff --git a/railties/test/application/rake/restart_test.rb b/railties/test/application/rake/restart_test.rb
new file mode 100644
index 0000000000..35099913fb
--- /dev/null
+++ b/railties/test/application/rake/restart_test.rb
@@ -0,0 +1,31 @@
+require "isolation/abstract_unit"
+
+module ApplicationTests
+ module RakeTests
+ class RakeRestartTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ test 'rake restart touches tmp/restart.txt' do
+ Dir.chdir(app_path) do
+ `rake restart`
+ assert File.exist?("tmp/restart.txt")
+
+ prev_mtime = File.mtime("tmp/restart.txt")
+ sleep(1)
+ `rake restart`
+ curr_mtime = File.mtime("tmp/restart.txt")
+ assert_not_equal prev_mtime, curr_mtime
+ end
+ end
+ end
+ end
+end
diff --git a/railties/test/rails_info_controller_test.rb b/railties/test/rails_info_controller_test.rb
index 25b0e761cb..d87b51d852 100644
--- a/railties/test/rails_info_controller_test.rb
+++ b/railties/test/rails_info_controller_test.rb
@@ -53,4 +53,29 @@ class InfoControllerTest < ActionController::TestCase
assert_response :success
end
+ test "info controller returns exact matches" do
+ exact_count = -> { JSON(response.body)['exact'].size }
+
+ get :routes, path: 'rails/info/route'
+ assert exact_count.call == 0, 'should not match incomplete routes'
+
+ get :routes, path: 'rails/info/routes'
+ assert exact_count.call == 1, 'should match complete routes'
+
+ get :routes, path: 'rails/info/routes.html'
+ assert exact_count.call == 1, 'should match complete routes with optional parts'
+ end
+
+ test "info controller returns fuzzy matches" do
+ fuzzy_count = -> { JSON(response.body)['fuzzy'].size }
+
+ get :routes, path: 'rails/info'
+ assert fuzzy_count.call == 2, 'should match incomplete routes'
+
+ get :routes, path: 'rails/info/routes'
+ assert fuzzy_count.call == 1, 'should match complete routes'
+
+ get :routes, path: 'rails/info/routes.html'
+ assert fuzzy_count.call == 0, 'should match optional parts of route literally'
+ end
end