aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Gemfile.lock2
-rw-r--r--actionpack/CHANGELOG.md12
-rw-r--r--actionpack/lib/action_controller/api.rb20
-rw-r--r--actionpack/lib/action_controller/metal/head.rb14
-rw-r--r--actionpack/lib/action_controller/metal/http_authentication.rb2
-rw-r--r--actionpack/lib/action_controller/metal/params_wrapper.rb2
-rw-r--r--actionpack/lib/action_dispatch/http/cache.rb8
-rw-r--r--actionpack/lib/action_dispatch/http/response.rb37
-rw-r--r--actionpack/lib/action_dispatch/middleware/ssl.rb2
-rw-r--r--actionpack/lib/action_dispatch/request/session.rb24
-rw-r--r--actionpack/test/controller/caching_test.rb1
-rw-r--r--actionpack/test/controller/log_subscriber_test.rb2
-rw-r--r--actionpack/test/controller/render_test.rb35
-rw-r--r--actionpack/test/controller/rescue_test.rb4
-rw-r--r--actionpack/test/dispatch/response_test.rb2
-rw-r--r--actionpack/test/dispatch/ssl_test.rb11
-rw-r--r--actionview/lib/action_view/helpers/form_options_helper.rb21
-rw-r--r--actionview/lib/action_view/helpers/form_tag_helper.rb17
-rw-r--r--actionview/test/actionpack/controller/render_test.rb20
-rw-r--r--actionview/test/template/form_tag_helper_test.rb7
-rw-r--r--actionview/test/template/record_tag_helper_test.rb3
-rw-r--r--activerecord/CHANGELOG.md11
-rw-r--r--activerecord/lib/active_record/associations/belongs_to_association.rb2
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb2
-rw-r--r--activerecord/lib/active_record/enum.rb6
-rw-r--r--activerecord/lib/active_record/fixtures.rb2
-rw-r--r--activerecord/lib/active_record/migration.rb3
-rw-r--r--activerecord/lib/active_record/migration/command_recorder.rb16
-rw-r--r--activerecord/lib/active_record/railties/databases.rake29
-rw-r--r--activerecord/test/cases/associations/belongs_to_associations_test.rb4
-rw-r--r--activerecord/test/cases/invertible_migration_test.rb16
-rw-r--r--activerecord/test/cases/migration/command_recorder_test.rb5
-rw-r--r--activerecord/test/cases/primary_keys_test.rb6
-rw-r--r--activesupport/lib/active_support/core_ext/hash/conversions.rb20
-rw-r--r--activesupport/lib/active_support/json/encoding.rb4
-rw-r--r--activesupport/lib/active_support/message_verifier.rb2
-rw-r--r--activesupport/lib/active_support/xml_mini.rb3
-rw-r--r--activesupport/lib/active_support/xml_mini/jdom.rb11
-rw-r--r--activesupport/lib/active_support/xml_mini/rexml.rb11
-rw-r--r--activesupport/test/inflector_test.rb154
-rw-r--r--activesupport/test/json/encoding_test.rb7
-rw-r--r--activesupport/test/message_verifier_test.rb1
-rw-r--r--guides/source/3_0_release_notes.md2
-rw-r--r--guides/source/3_1_release_notes.md2
-rw-r--r--guides/source/3_2_release_notes.md2
-rw-r--r--guides/source/4_0_release_notes.md2
-rw-r--r--guides/source/action_controller_overview.md4
-rw-r--r--guides/source/active_job_basics.md34
-rw-r--r--guides/source/active_record_postgresql.md12
-rw-r--r--guides/source/api_app.md723
-rw-r--r--guides/source/caching_with_rails.md186
-rw-r--r--guides/source/development_dependencies_install.md6
-rw-r--r--guides/source/i18n.md10
-rw-r--r--guides/source/rails_on_rack.md4
-rw-r--r--railties/CHANGELOG.md5
-rw-r--r--railties/lib/rails/commands/server.rb1
-rw-r--r--railties/lib/rails/generators/named_base.rb4
-rw-r--r--railties/lib/rails/generators/rails/app/templates/Gemfile4
-rw-r--r--railties/test/generators/app_generator_test.rb4
59 files changed, 859 insertions, 707 deletions
diff --git a/Gemfile.lock b/Gemfile.lock
index c6d7ad0926..2140881170 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -308,4 +308,4 @@ DEPENDENCIES
w3c_validators
BUNDLED WITH
- 1.10.3
+ 1.10.4
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md
index 78ae506389..cb5e7516fb 100644
--- a/actionpack/CHANGELOG.md
+++ b/actionpack/CHANGELOG.md
@@ -1,3 +1,7 @@
+* Deprecate passing first parameter as `Hash` and default status code for `head` method.
+
+ *Mehmet Emin İNAÇ*
+
* Adds`Rack::Utils::ParameterTypeError` and `Rack::Utils::InvalidParameterError`
to the rescue_responses hash in `ExceptionWrapper` (Rack recommends
integrators serve 400s for both of these).
@@ -218,13 +222,13 @@
* Preserve default url options when generating URLs.
- Fixes an issue that would cause default_url_options to be lost when
+ Fixes an issue that would cause `default_url_options` to be lost when
generating URLs with fewer positional arguments than parameters in the
route definition.
*Tekin Suleyman*
-* Deprecate *_via_redirect integration test methods.
+* Deprecate `*_via_redirect` integration test methods.
Use `follow_redirect!` manually after the request call for the same behavior.
@@ -247,11 +251,11 @@
*Jonas Baumann*
-* Deprecate all *_filter callbacks in favor of *_action callbacks.
+* Deprecate all `*_filter` callbacks in favor of `*_action` callbacks.
*Rafael Mendonça França*
-* Allow you to pass `prepend: false` to protect_from_forgery to have the
+* Allow you to pass `prepend: false` to `protect_from_forgery` to have the
verification callback appended instead of prepended to the chain.
This allows you to let the verification step depend on prior callbacks.
diff --git a/actionpack/lib/action_controller/api.rb b/actionpack/lib/action_controller/api.rb
index d8149e0232..3af63b8892 100644
--- a/actionpack/lib/action_controller/api.rb
+++ b/actionpack/lib/action_controller/api.rb
@@ -4,7 +4,7 @@ require 'action_controller/log_subscriber'
module ActionController
# API Controller is a lightweight version of <tt>ActionController::Base</tt>,
- # created for applications that don't require all functionality that a complete
+ # created for applications that don't require all functionalities that a complete
# \Rails controller provides, allowing you to create controllers with just the
# features that you need for API only applications.
#
@@ -61,10 +61,10 @@ module ActionController
# In some scenarios you may want to add back some functionality provided by
# <tt>ActionController::Base</tt> that is not present by default in
# <tt>ActionController::API</tt>, for instance <tt>MimeResponds</tt>. This
- # module gives you the <tt>respond_to</tt> and <tt>respond_with</tt> methods.
- # Adding it is quite simple, you just need to include the module in a specific
- # controller or in <tt>ApplicationController</tt> in case you want it
- # available to your entire app:
+ # module gives you the <tt>respond_to</tt> method. Adding it is quite simple,
+ # you just need to include the module in a specific controller or in
+ # +ApplicationController+ in case you want it available in your entire
+ # application:
#
# class ApplicationController < ActionController::API
# include ActionController::MimeResponds
@@ -87,16 +87,18 @@ module ActionController
class API < Metal
abstract!
- # Shortcut helper that returns all the ActionController::API modules except the ones passed in the argument:
+ # Shortcut helper that returns all the ActionController::API modules except
+ # the ones passed as arguments:
#
# class MetalController
- # ActionController::API.without_modules(:Redirecting, :DataStreaming).each do |left|
+ # ActionController::API.without_modules(:ForceSSL, :UrlFor).each do |left|
# include left
# end
# end
#
# This gives better control over what you want to exclude and makes it easier
- # to create an api controller class, instead of listing the modules required manually.
+ # to create an API controller class, instead of listing the modules required
+ # manually.
def self.without_modules(*modules)
modules = modules.map do |m|
m.is_a?(Symbol) ? ActionController.const_get(m) : m
@@ -120,7 +122,7 @@ module ActionController
ForceSSL,
DataStreaming,
- # Before callbacks should also be executed the earliest as possible, so
+ # Before callbacks should also be executed as early as possible, so
# also include them at the bottom.
AbstractController::Callbacks,
diff --git a/actionpack/lib/action_controller/metal/head.rb b/actionpack/lib/action_controller/metal/head.rb
index 70f42bf565..f445094bdc 100644
--- a/actionpack/lib/action_controller/metal/head.rb
+++ b/actionpack/lib/action_controller/metal/head.rb
@@ -17,8 +17,18 @@ module ActionController
#
# See Rack::Utils::SYMBOL_TO_STATUS_CODE for a full list of valid +status+ symbols.
def head(status, options = {})
- options, status = status, nil if status.is_a?(Hash)
- status ||= options.delete(:status) || :ok
+ if status.is_a?(Hash)
+ msg = status[:status] ? 'The :status option' : 'The implicit :ok status'
+ options, status = status, status.delete(:status)
+
+ ActiveSupport::Deprecation.warn(<<-MSG.squish)
+ #{msg} on `head` has been deprecated and will be removed in Rails 5.1.
+ Please pass the status as a separate parameter before the options, instead.
+ MSG
+ end
+
+ status ||= :ok
+
location = options.delete(:location)
content_type = options.delete(:content_type)
diff --git a/actionpack/lib/action_controller/metal/http_authentication.rb b/actionpack/lib/action_controller/metal/http_authentication.rb
index fb0a52b076..39bed955a4 100644
--- a/actionpack/lib/action_controller/metal/http_authentication.rb
+++ b/actionpack/lib/action_controller/metal/http_authentication.rb
@@ -493,7 +493,7 @@ module ActionController
"Token #{values * ", "}"
end
- # Sets a WWW-Authenticate to let the client know a token is desired.
+ # Sets a WWW-Authenticate header to let the client know a token is desired.
#
# controller - ActionController::Base instance for the outgoing response.
# realm - String realm to use in the header.
diff --git a/actionpack/lib/action_controller/metal/params_wrapper.rb b/actionpack/lib/action_controller/metal/params_wrapper.rb
index 8a4ea70649..cdfc523bd4 100644
--- a/actionpack/lib/action_controller/metal/params_wrapper.rb
+++ b/actionpack/lib/action_controller/metal/params_wrapper.rb
@@ -40,7 +40,7 @@ module ActionController
# wrap_parameters :person, include: [:username, :password]
# end
#
- # On ActiveRecord models with no +:include+ or +:exclude+ option set,
+ # On Active Record models with no +:include+ or +:exclude+ option set,
# it will only wrap the parameters returned by the class method
# <tt>attribute_names</tt>.
#
diff --git a/actionpack/lib/action_dispatch/http/cache.rb b/actionpack/lib/action_dispatch/http/cache.rb
index 747d295261..cc1cb3f0f0 100644
--- a/actionpack/lib/action_dispatch/http/cache.rb
+++ b/actionpack/lib/action_dispatch/http/cache.rb
@@ -151,11 +151,11 @@ module ActionDispatch
control.merge! @cache_control
if control.empty?
- headers[CACHE_CONTROL] = DEFAULT_CACHE_CONTROL
+ self[CACHE_CONTROL] = DEFAULT_CACHE_CONTROL
elsif control[:no_cache]
- headers[CACHE_CONTROL] = NO_CACHE
+ self[CACHE_CONTROL] = NO_CACHE
if control[:extras]
- headers[CACHE_CONTROL] += ", #{control[:extras].join(', ')}"
+ self[CACHE_CONTROL] += ", #{control[:extras].join(', ')}"
end
else
extras = control[:extras]
@@ -167,7 +167,7 @@ module ActionDispatch
options << MUST_REVALIDATE if control[:must_revalidate]
options.concat(extras) if extras
- headers[CACHE_CONTROL] = options.join(", ")
+ self[CACHE_CONTROL] = options.join(", ")
end
end
end
diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb
index 9e53a0f08b..c5939adb9f 100644
--- a/actionpack/lib/action_dispatch/http/response.rb
+++ b/actionpack/lib/action_dispatch/http/response.rb
@@ -40,10 +40,9 @@ module ActionDispatch # :nodoc:
attr_writer :sending_file
- # Get and set headers for this response.
- attr_accessor :header
+ # Get headers for this response.
+ attr_reader :header
- alias_method :headers=, :header=
alias_method :headers, :header
delegate :[], :[]=, :to => :@header
@@ -61,7 +60,7 @@ module ActionDispatch # :nodoc:
# The charset of the response. HTML wants to know the encoding of the
# content you're giving them, so we need to send that along.
- attr_accessor :charset
+ attr_reader :charset
CONTENT_TYPE = "Content-Type".freeze
SET_COOKIE = "Set-Cookie".freeze
@@ -117,8 +116,9 @@ module ActionDispatch # :nodoc:
super()
header = merge_default_headers(header, default_headers)
+ @header = header
- self.body, self.header, self.status = body, header, status
+ self.body, self.status = body, status
@sending_file = false
@blank = false
@@ -127,7 +127,7 @@ module ActionDispatch # :nodoc:
@sending = false
@sent = false
@content_type = nil
- @charset = nil
+ @charset = self.class.default_charset
if content_type = self[CONTENT_TYPE]
type, charset = content_type.split(/;\s*charset=/)
@@ -187,6 +187,15 @@ module ActionDispatch # :nodoc:
@content_type = content_type.to_s
end
+ # Sets the HTTP character set.
+ def charset=(charset)
+ if nil == charset
+ @charset = self.class.default_charset
+ else
+ @charset = charset
+ end
+ end
+
# The response code of the request.
def response_code
@status
@@ -278,6 +287,7 @@ module ActionDispatch # :nodoc:
#
# status, headers, body = *response
def to_a
+ commit!
rack_response @status, @header.to_hash
end
alias prepare! to_a
@@ -302,6 +312,9 @@ module ActionDispatch # :nodoc:
private
def before_committed
+ return if committed?
+ assign_default_content_type_and_charset!
+ handle_conditional_get!
end
def before_sending
@@ -319,16 +332,15 @@ module ActionDispatch # :nodoc:
body.respond_to?(:each) ? body : [body]
end
- def assign_default_content_type_and_charset!(headers)
- return if headers[CONTENT_TYPE].present?
+ def assign_default_content_type_and_charset!
+ return if self[CONTENT_TYPE].present?
@content_type ||= Mime::HTML
- @charset ||= self.class.default_charset unless @charset == false
type = @content_type.to_s.dup
- type << "; charset=#{@charset}" if append_charset?
+ type << "; charset=#{charset}" if append_charset?
- headers[CONTENT_TYPE] = type
+ self[CONTENT_TYPE] = type
end
def append_charset?
@@ -372,9 +384,6 @@ module ActionDispatch # :nodoc:
end
def rack_response(status, header)
- assign_default_content_type_and_charset!(header)
- handle_conditional_get!
-
header[SET_COOKIE] = header[SET_COOKIE].join("\n") if header[SET_COOKIE].respond_to?(:join)
if NO_CONTENT_CODES.include?(@status)
diff --git a/actionpack/lib/action_dispatch/middleware/ssl.rb b/actionpack/lib/action_dispatch/middleware/ssl.rb
index 0c7caef25d..7b3d8bcc5b 100644
--- a/actionpack/lib/action_dispatch/middleware/ssl.rb
+++ b/actionpack/lib/action_dispatch/middleware/ssl.rb
@@ -22,7 +22,7 @@ module ActionDispatch
if request.ssl?
status, headers, body = @app.call(env)
- headers = hsts_headers.merge(headers)
+ headers.reverse_merge!(hsts_headers)
flag_cookies_as_secure!(headers)
[status, headers, body]
else
diff --git a/actionpack/lib/action_dispatch/request/session.rb b/actionpack/lib/action_dispatch/request/session.rb
index 773d41de88..a8a3cd20b9 100644
--- a/actionpack/lib/action_dispatch/request/session.rb
+++ b/actionpack/lib/action_dispatch/request/session.rb
@@ -17,7 +17,7 @@ module ActionDispatch
session.merge! session_was if session_was
set(env, session)
- Options.set(env, Request::Session::Options.new(store, env, default_options))
+ Options.set(env, Request::Session::Options.new(store, default_options))
session
end
@@ -38,20 +38,19 @@ module ActionDispatch
env[ENV_SESSION_OPTIONS_KEY]
end
- def initialize(by, env, default_options)
+ def initialize(by, default_options)
@by = by
- @env = env
@delegate = default_options.dup
end
def [](key)
- if key == :id
- @delegate.fetch(key) {
- @delegate[:id] = @by.send(:extract_session_id, @env)
- }
- else
- @delegate[key]
- end
+ @delegate[key]
+ end
+
+ def id(env)
+ @delegate.fetch(:id) {
+ @by.send(:extract_session_id, env)
+ }
end
def []=(k,v); @delegate[k] = v; end
@@ -68,7 +67,7 @@ module ActionDispatch
end
def id
- options[:id]
+ options.id(@env)
end
def options
@@ -78,8 +77,7 @@ module ActionDispatch
def destroy
clear
options = self.options || {}
- new_sid = @by.send(:destroy_session, @env, options[:id], options)
- options[:id] = new_sid # Reset session id with a new value or nil
+ @by.send(:destroy_session, @env, options.id(@env), options)
# Load the new sid to be written with the response
@loaded = false
diff --git a/actionpack/test/controller/caching_test.rb b/actionpack/test/controller/caching_test.rb
index de697858c3..f21dd87400 100644
--- a/actionpack/test/controller/caching_test.rb
+++ b/actionpack/test/controller/caching_test.rb
@@ -380,6 +380,7 @@ class AutomaticCollectionCacheTest < ActionController::TestCase
@controller = CollectionCacheController.new
@controller.perform_caching = true
@controller.partial_rendered_times = 0
+ @controller.cache_store = ActiveSupport::Cache::MemoryStore.new
end
def test_collection_fetches_cached_views
diff --git a/actionpack/test/controller/log_subscriber_test.rb b/actionpack/test/controller/log_subscriber_test.rb
index ccbf336acf..7835d2768a 100644
--- a/actionpack/test/controller/log_subscriber_test.rb
+++ b/actionpack/test/controller/log_subscriber_test.rb
@@ -10,7 +10,7 @@ module Another
end
rescue_from SpecialException do
- head :status => 406
+ head 406
end
before_action :redirector, only: :never_executed
diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb
index c9c43de37d..43e992d432 100644
--- a/actionpack/test/controller/render_test.rb
+++ b/actionpack/test/controller/render_test.rb
@@ -138,6 +138,14 @@ class TestController < ActionController::Base
fresh_when(:last_modified => Time.now.utc.beginning_of_day, :etag => [ :foo, 123 ])
end
+ def head_with_status_hash
+ head status: :created
+ end
+
+ def head_with_hash_does_not_include_status
+ head warning: :deprecated
+ end
+
def head_created
head :created
end
@@ -151,31 +159,31 @@ class TestController < ActionController::Base
end
def head_with_location_header
- head :location => "/foo"
+ head :ok, :location => "/foo"
end
def head_with_location_object
- head :location => Customer.new("david", 1)
+ head :ok, :location => Customer.new("david", 1)
end
def head_with_symbolic_status
- head :status => params[:status].intern
+ head params[:status].intern
end
def head_with_integer_status
- head :status => params[:status].to_i
+ head params[:status].to_i
end
def head_with_string_status
- head :status => params[:status]
+ head params[:status]
end
def head_with_custom_header
- head :x_custom_header => "something"
+ head :ok, :x_custom_header => "something"
end
def head_with_www_authenticate_header
- head 'WWW-Authenticate' => 'something'
+ head :ok, 'WWW-Authenticate' => 'something'
end
def head_with_status_code_first
@@ -490,6 +498,19 @@ class HeadRenderTest < ActionController::TestCase
assert_response :created
end
+ def test_passing_hash_to_head_as_first_parameter_deprecated
+ assert_deprecated do
+ get :head_with_status_hash
+ end
+ end
+
+ def test_head_with_default_value_is_deprecated
+ assert_deprecated do
+ get :head_with_hash_does_not_include_status
+ assert_response :ok
+ end
+ end
+
def test_head_created_with_application_json_content_type
post :head_created_with_application_json_content_type
assert @response.body.blank?
diff --git a/actionpack/test/controller/rescue_test.rb b/actionpack/test/controller/rescue_test.rb
index 4898b0c57f..2cfd0b8023 100644
--- a/actionpack/test/controller/rescue_test.rb
+++ b/actionpack/test/controller/rescue_test.rb
@@ -47,10 +47,10 @@ class RescueController < ActionController::Base
rescue_from 'InvalidRequestToRescueAsString', :with => proc { |exception| render :text => exception.message }
rescue_from BadGateway do
- head :status => 502
+ head 502
end
rescue_from 'BadGatewayToRescueAsString' do
- head :status => 502
+ head 502
end
rescue_from ResourceUnavailable do |exception|
diff --git a/actionpack/test/dispatch/response_test.rb b/actionpack/test/dispatch/response_test.rb
index 5fbd19acdf..7aca251066 100644
--- a/actionpack/test/dispatch/response_test.rb
+++ b/actionpack/test/dispatch/response_test.rb
@@ -72,12 +72,14 @@ class ResponseTest < ActiveSupport::TestCase
test "content type" do
[204, 304].each do |c|
+ @response = ActionDispatch::Response.new
@response.status = c.to_s
_, headers, _ = @response.to_a
assert !headers.has_key?("Content-Type"), "#{c} should not have Content-Type header"
end
[200, 302, 404, 500].each do |c|
+ @response = ActionDispatch::Response.new
@response.status = c.to_s
_, headers, _ = @response.to_a
assert headers.has_key?("Content-Type"), "#{c} did not have Content-Type header"
diff --git a/actionpack/test/dispatch/ssl_test.rb b/actionpack/test/dispatch/ssl_test.rb
index 7ced41bc2e..017e9ba2dd 100644
--- a/actionpack/test/dispatch/ssl_test.rb
+++ b/actionpack/test/dispatch/ssl_test.rb
@@ -216,4 +216,15 @@ class SSLTest < ActionDispatch::IntegrationTest
assert_equal "https://example.co.uk/path?key=value",
response.headers['Location']
end
+
+ def test_keeps_original_headers_behavior
+ headers = Rack::Utils::HeaderHash.new(
+ "Content-Type" => "text/html",
+ "Connection" => ["close"]
+ )
+ self.app = ActionDispatch::SSL.new(lambda { |env| [200, headers, ["OK"]] })
+
+ get "https://example.org/"
+ assert_equal "close", response.headers["Connection"]
+ end
end
diff --git a/actionview/lib/action_view/helpers/form_options_helper.rb b/actionview/lib/action_view/helpers/form_options_helper.rb
index d3deee0df3..1b7b188d65 100644
--- a/actionview/lib/action_view/helpers/form_options_helper.rb
+++ b/actionview/lib/action_view/helpers/form_options_helper.rb
@@ -707,6 +707,27 @@ module ActionView
# collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b|
# b.label(:"data-value" => b.value) { b.check_box + b.text }
# end
+ #
+ # ==== Gotcha
+ #
+ # When no selection is made for a collection of checkboxes most
+ # web browsers will not send any value.
+ #
+ # For example, if we have a +User+ model with +category_ids+ field and we
+ # have the following code in our update action:
+ #
+ # @user.update(params[:user])
+ #
+ # If no +category_ids+ are selected then we can safely assume this field
+ # will not be updated.
+ #
+ # This is possible thanks to a hidden field generated by the helper method
+ # for every collection of checkboxes.
+ # This hidden field is given the same field name as the checkboxes with a
+ # blank value.
+ #
+ # In the rare case you don't want this hidden field, you can pass the
+ # <tt>include_hidden: false</tt> option to the helper method.
def collection_check_boxes(object, method, collection, value_method, text_method, options = {}, html_options = {}, &block)
Tags::CollectionCheckBoxes.new(object, method, self, collection, value_method, text_method, options, html_options).render(&block)
end
diff --git a/actionview/lib/action_view/helpers/form_tag_helper.rb b/actionview/lib/action_view/helpers/form_tag_helper.rb
index 1f76f40138..896020bc15 100644
--- a/actionview/lib/action_view/helpers/form_tag_helper.rb
+++ b/actionview/lib/action_view/helpers/form_tag_helper.rb
@@ -448,8 +448,9 @@ module ActionView
# <tt>reset</tt>button or a generic button which can be used in
# JavaScript, for example. You can use the button tag as a regular
# submit tag but it isn't supported in legacy browsers. However,
- # the button tag allows richer labels such as images and emphasis,
- # so this helper will also accept a block.
+ # the button tag does allow for richer labels such as images and emphasis,
+ # so this helper will also accept a block. By default, it will create
+ # a button tag with type `submit`, if type is not given.
#
# ==== Options
# * <tt>:data</tt> - This option can be used to add custom data attributes.
@@ -472,6 +473,15 @@ module ActionView
# button_tag
# # => <button name="button" type="submit">Button</button>
#
+ # button_tag 'Reset', type: 'reset'
+ # # => <button name="button" type="reset">Reset</button>
+ #
+ # button_tag 'Button', type: 'button'
+ # # => <button name="button" type="button">Button</button>
+ #
+ # button_tag 'Reset', type: 'reset', disabled: true
+ # # => <button name="button" type="reset" disabled="disabled">Reset</button>
+ #
# button_tag(type: 'button') do
# content_tag(:strong, 'Ask me!')
# end
@@ -479,6 +489,9 @@ module ActionView
# # <strong>Ask me!</strong>
# # </button>
#
+ # button_tag "Save", data: { confirm: "Are you sure?" }
+ # # => <button name="button" type="submit" data-confirm="Are you sure?">Save</button>
+ #
# button_tag "Checkout", data: { disable_with: "Please wait..." }
# # => <button data-disable-with="Please wait..." name="button" type="submit">Checkout</button>
#
diff --git a/actionview/test/actionpack/controller/render_test.rb b/actionview/test/actionpack/controller/render_test.rb
index c4228b5683..ebaf39a12d 100644
--- a/actionview/test/actionpack/controller/render_test.rb
+++ b/actionview/test/actionpack/controller/render_test.rb
@@ -1,6 +1,5 @@
require 'abstract_unit'
require 'active_model'
-require 'fileutils'
class ApplicationController < ActionController::Base
self.view_paths = File.join(FIXTURE_LOAD_PATH, "actionpack")
@@ -679,14 +678,6 @@ class RenderTest < ActionController::TestCase
ActionView::Base.logger = nil
end
- def case_sensitive_file_system?
- fname = '.case_sensitive_file_system_test'
- FileUtils.touch(fname)
- !File.exist?(fname.upcase)
- ensure
- FileUtils.rm_f(fname)
- end
-
# :ported:
def test_simple_show
get :hello_world
@@ -753,15 +744,8 @@ class RenderTest < ActionController::TestCase
end
def test_render_action_upcased
- action = :render_action_upcased_hello_world
-
- if case_sensitive_file_system?
- assert_raise ActionView::MissingTemplate do
- get action
- end
- else
- get action
- assert_equal 'Hello world!', @response.body
+ assert_raise ActionView::MissingTemplate do
+ get :render_action_upcased_hello_world
end
end
diff --git a/actionview/test/template/form_tag_helper_test.rb b/actionview/test/template/form_tag_helper_test.rb
index cad1c82309..f602c82c42 100644
--- a/actionview/test/template/form_tag_helper_test.rb
+++ b/actionview/test/template/form_tag_helper_test.rb
@@ -510,6 +510,13 @@ class FormTagHelperTest < ActionView::TestCase
)
end
+ def test_button_tag_with_data_disable_with_option
+ assert_dom_equal(
+ %(<button name="button" type="submit" data-disable-with="Please wait...">Checkout</button>),
+ button_tag("Checkout", data: { disable_with: "Please wait..." })
+ )
+ end
+
def test_image_submit_tag_with_confirmation
assert_dom_equal(
%(<input alt="Save" type="image" src="/images/save.gif" data-confirm="Are you sure?" />),
diff --git a/actionview/test/template/record_tag_helper_test.rb b/actionview/test/template/record_tag_helper_test.rb
index 4b7b653916..bfc5d04bed 100644
--- a/actionview/test/template/record_tag_helper_test.rb
+++ b/actionview/test/template/record_tag_helper_test.rb
@@ -2,7 +2,7 @@ require 'abstract_unit'
class RecordTagPost
extend ActiveModel::Naming
- include ActiveModel::Conversion
+
attr_accessor :id, :body
def initialize
@@ -14,7 +14,6 @@ class RecordTagPost
end
class RecordTagHelperTest < ActionView::TestCase
- include RenderERBUtils
tests ActionView::Helpers::RecordTagHelper
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md
index d389d7f6fe..d570f8e965 100644
--- a/activerecord/CHANGELOG.md
+++ b/activerecord/CHANGELOG.md
@@ -1,3 +1,7 @@
+* Make `remove_index :table, :column` reversible.
+
+ *Yves Senn*
+
* Fixed an error which would occur in dirty checking when calling
`update_attributes` from a getter.
@@ -12,7 +16,7 @@
* Add `:enum_prefix`/`:enum_suffix` option to `enum` definition.
- Fixes #17511 and #17415
+ Fixes #17511, #17415.
*Igor Kapkov*
@@ -22,7 +26,7 @@
*Sean Griffin & jmondo*
-* Deprecate the PG `:point` type in favor of a new one which will return
+* Deprecate the PostgreSQL `:point` type in favor of a new one which will return
`Point` objects instead of an `Array`
*Sean Griffin*
@@ -84,7 +88,8 @@
*Jonathan Worek*
-* Pass `:extend` option for `has_and_belongs_to_many` associations to the underlying `has_many :through`.
+* Pass `:extend` option for `has_and_belongs_to_many` associations to the
+ underlying `has_many :through`.
*Jaehyun Shin*
diff --git a/activerecord/lib/active_record/associations/belongs_to_association.rb b/activerecord/lib/active_record/associations/belongs_to_association.rb
index 265a65c4c1..260a0c6a2d 100644
--- a/activerecord/lib/active_record/associations/belongs_to_association.rb
+++ b/activerecord/lib/active_record/associations/belongs_to_association.rb
@@ -107,7 +107,7 @@ module ActiveRecord
end
def stale_state
- result = owner._read_attribute(reflection.foreign_key)
+ result = owner._read_attribute(reflection.foreign_key) { |n| owner.send(:missing_attribute, n, caller) }
result && result.to_s
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
index c8be038d76..49ffd7ccf0 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
@@ -587,7 +587,7 @@ module ActiveRecord
#
# Removes the +index_accounts_on_column+ in the +accounts+ table.
#
- # remove_index :accounts, :column
+ # remove_index :accounts, :branch_id
#
# Removes the index named +index_accounts_on_branch_id+ in the +accounts+ table.
#
diff --git a/activerecord/lib/active_record/enum.rb b/activerecord/lib/active_record/enum.rb
index ad33c84dbc..c0d9d9c1c8 100644
--- a/activerecord/lib/active_record/enum.rb
+++ b/activerecord/lib/active_record/enum.rb
@@ -75,8 +75,8 @@ module ActiveRecord
#
# Conversation.where("status <> ?", Conversation.statuses[:archived])
#
- # You can use <tt>:enum_prefix</tt>/<tt>:enum_suffix</tt> option then you need
- # to define multiple enums with same values. If option value is <tt>true</tt>,
+ # You can use the +:enum_prefix+ or +:enum_suffix+ options when you need
+ # to define multiple enums with same values. If the passed value is +true+,
# the methods are prefixed/suffixed with the name of the enum.
#
# class Invoice < ActiveRecord::Base
@@ -89,7 +89,7 @@ module ActiveRecord
# enum verification: [:done, :fail], enum_prefix: :verification_status
# end
#
- # Note that <tt>:enum_prefix</tt>/<tt>:enum_postfix</tt> are reserved keywords
+ # Note that <tt>:enum_prefix</tt>/<tt>:enum_suffix</tt> are reserved keywords
# and can not be used as an enum name.
module Enum
diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb
index 738fab2bd9..b01444a090 100644
--- a/activerecord/lib/active_record/fixtures.rb
+++ b/activerecord/lib/active_record/fixtures.rb
@@ -110,7 +110,7 @@ module ActiveRecord
# <% 1.upto(1000) do |i| %>
# fix_<%= i %>:
# id: <%= i %>
- # name: guy_<%= 1 %>
+ # name: guy_<%= i %>
# <% end %>
#
# This will create 1000 very simple fixtures.
diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb
index 192a456846..1e0c04cd23 100644
--- a/activerecord/lib/active_record/migration.rb
+++ b/activerecord/lib/active_record/migration.rb
@@ -142,6 +142,9 @@ module ActiveRecord
# specified by +column_name+.
# * <tt>remove_index(table_name, name: index_name)</tt>: Removes the index
# specified by +index_name+.
+ # * <tt>add_reference(:table_name, :reference_name)</tt>: Adds a new column
+ # +reference_name_id+ by default a integer. See
+ # ActiveRecord::ConnectionAdapters::SchemaStatements#add_reference for details.
#
# == Irreversible transformations
#
diff --git a/activerecord/lib/active_record/migration/command_recorder.rb b/activerecord/lib/active_record/migration/command_recorder.rb
index ee4545ed71..b592c004aa 100644
--- a/activerecord/lib/active_record/migration/command_recorder.rb
+++ b/activerecord/lib/active_record/migration/command_recorder.rb
@@ -151,14 +151,16 @@ module ActiveRecord
end
def invert_remove_index(args)
- table, options = *args
-
- unless options && options.is_a?(Hash) && options[:column]
- raise ActiveRecord::IrreversibleMigration, "remove_index is only reversible if given a :column option."
+ table, options_or_column = *args
+ if (options = options_or_column).is_a?(Hash)
+ unless options[:column]
+ raise ActiveRecord::IrreversibleMigration, "remove_index is only reversible if given a :column option."
+ end
+ options = options.dup
+ [:add_index, [table, options.delete(:column), options]]
+ elsif (column = options_or_column).present?
+ [:add_index, [table, column]]
end
-
- options = options.dup
- [:add_index, [table, options.delete(:column), options]]
end
alias :invert_add_belongs_to :invert_add_reference
diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake
index d168786e71..66fb3ae44b 100644
--- a/activerecord/lib/active_record/railties/databases.rake
+++ b/activerecord/lib/active_record/railties/databases.rake
@@ -12,7 +12,7 @@ db_namespace = namespace :db do
end
end
- desc 'Creates the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:create:all to create all databases in the config). Without RAILS_ENV it defaults to creating the development and test databases.'
+ desc 'Creates the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:create:all to create all databases in the config). Without RAILS_ENV, it defaults to creating the development and test databases.'
task :create => [:load_config] do
ActiveRecord::Tasks::DatabaseTasks.create_current
end
@@ -23,7 +23,7 @@ db_namespace = namespace :db do
end
end
- desc 'Drops the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:drop:all to drop all databases in the config). Without RAILS_ENV it defaults to dropping the development and test databases.'
+ desc 'Drops the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:drop:all to drop all databases in the config). Without RAILS_ENV, it defaults to dropping the development and test databases.'
task :drop => [:load_config] do
ActiveRecord::Tasks::DatabaseTasks.drop_current
end
@@ -134,10 +134,7 @@ db_namespace = namespace :db do
end
# desc 'Drops and recreates the database from db/schema.rb for the current environment and loads the seeds.'
- task :reset => [:environment, :load_config] do
- db_namespace["drop"].invoke
- db_namespace["setup"].invoke
- end
+ task :reset => [ 'db:drop', 'db:setup' ]
# desc "Retrieves the charset for the current environment's database"
task :charset => [:environment, :load_config] do
@@ -159,7 +156,7 @@ db_namespace = namespace :db do
end
# desc "Raises an error if there are pending migrations"
- task :abort_if_pending_migrations => :environment do
+ task :abort_if_pending_migrations => [:environment, :load_config] do
pending_migrations = ActiveRecord::Migrator.open(ActiveRecord::Migrator.migrations_paths).pending_migrations
if pending_migrations.any?
@@ -171,17 +168,17 @@ db_namespace = namespace :db do
end
end
- desc 'Create the database, load the schema, and initialize with the seed data (use db:reset to also drop the database first)'
+ desc 'Creates the database, loads the schema, and initializes with the seed data (use db:reset to also drop the database first)'
task :setup => ['db:schema:load_if_ruby', 'db:structure:load_if_sql', :seed]
- desc 'Load the seed data from db/seeds.rb'
+ desc 'Loads the seed data from db/seeds.rb'
task :seed do
db_namespace['abort_if_pending_migrations'].invoke
ActiveRecord::Tasks::DatabaseTasks.load_seed
end
namespace :fixtures do
- desc "Load fixtures into the current environment's database. Load specific fixtures using FIXTURES=x,y. Load from subdirectory in test/fixtures using FIXTURES_DIR=z. Specify an alternative path (eg. spec/fixtures) using FIXTURES_PATH=spec/fixtures."
+ desc "Loads fixtures into the current environment's database. Load specific fixtures using FIXTURES=x,y. Load from subdirectory in test/fixtures using FIXTURES_DIR=z. Specify an alternative path (eg. spec/fixtures) using FIXTURES_PATH=spec/fixtures."
task :load => [:environment, :load_config] do
require 'active_record/fixtures'
@@ -229,7 +226,7 @@ db_namespace = namespace :db do
end
namespace :schema do
- desc 'Create a db/schema.rb file that is portable against any DB supported by AR'
+ desc 'Creates a db/schema.rb file that is portable against any DB supported by AR'
task :dump => [:environment, :load_config] do
require 'active_record/schema_dumper'
filename = ENV['SCHEMA'] || File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, 'schema.rb')
@@ -239,7 +236,7 @@ db_namespace = namespace :db do
db_namespace['schema:dump'].reenable
end
- desc 'Load a schema.rb file into the database'
+ desc 'Loads a schema.rb file into the database'
task :load => [:environment, :load_config] do
ActiveRecord::Tasks::DatabaseTasks.load_schema_current(:ruby, ENV['SCHEMA'])
end
@@ -249,7 +246,7 @@ db_namespace = namespace :db do
end
namespace :cache do
- desc 'Create a db/schema_cache.dump file.'
+ desc 'Creates a db/schema_cache.dump file.'
task :dump => [:environment, :load_config] do
con = ActiveRecord::Base.connection
filename = File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "schema_cache.dump")
@@ -259,7 +256,7 @@ db_namespace = namespace :db do
open(filename, 'wb') { |f| f.write(Marshal.dump(con.schema_cache)) }
end
- desc 'Clear a db/schema_cache.dump file.'
+ desc 'Clears a db/schema_cache.dump file.'
task :clear => [:environment, :load_config] do
filename = File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "schema_cache.dump")
FileUtils.rm(filename) if File.exist?(filename)
@@ -269,7 +266,7 @@ db_namespace = namespace :db do
end
namespace :structure do
- desc 'Dump the database structure to db/structure.sql. Specify another file with SCHEMA=db/my_structure.sql'
+ desc 'Dumps the database structure to db/structure.sql. Specify another file with SCHEMA=db/my_structure.sql'
task :dump => [:environment, :load_config] do
filename = ENV['SCHEMA'] || File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "structure.sql")
current_config = ActiveRecord::Tasks::DatabaseTasks.current_config
@@ -285,7 +282,7 @@ db_namespace = namespace :db do
db_namespace['structure:dump'].reenable
end
- desc "Recreate the databases from the structure.sql file"
+ desc "Recreates the databases from the structure.sql file"
task :load => [:load_config] do
ActiveRecord::Tasks::DatabaseTasks.load_schema_current(:sql, ENV['SCHEMA'])
end
diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb
index ba90c61d65..039cc46b0b 100644
--- a/activerecord/test/cases/associations/belongs_to_associations_test.rb
+++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb
@@ -31,6 +31,10 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
assert_equal companies(:first_firm).name, firm.name
end
+ def test_missing_attribute_error_is_raised_when_no_foreign_key_attribute
+ assert_raises(ActiveModel::MissingAttributeError) { Client.select(:id).first.firm }
+ end
+
def test_belongs_to_does_not_use_order_by
ActiveRecord::SQLCounter.clear_log
Client.find(3).firm
diff --git a/activerecord/test/cases/invertible_migration_test.rb b/activerecord/test/cases/invertible_migration_test.rb
index 8144f3e5c5..99230aa3d5 100644
--- a/activerecord/test/cases/invertible_migration_test.rb
+++ b/activerecord/test/cases/invertible_migration_test.rb
@@ -144,13 +144,17 @@ module ActiveRecord
end
def test_exception_on_removing_index_without_column_option
- RemoveIndexMigration1.new.migrate(:up)
- migration = RemoveIndexMigration2.new
- migration.migrate(:up)
+ index_definition = ["horses", [:name, :color]]
+ migration1 = RemoveIndexMigration1.new
+ migration1.migrate(:up)
+ assert migration1.connection.index_exists?(*index_definition)
- assert_raises(IrreversibleMigration) do
- migration.migrate(:down)
- end
+ migration2 = RemoveIndexMigration2.new
+ migration2.migrate(:up)
+ assert_not migration2.connection.index_exists?(*index_definition)
+
+ migration2.migrate(:down)
+ assert migration2.connection.index_exists?(*index_definition)
end
def test_migrate_up
diff --git a/activerecord/test/cases/migration/command_recorder_test.rb b/activerecord/test/cases/migration/command_recorder_test.rb
index 24d3c085a7..90b7c6b38a 100644
--- a/activerecord/test/cases/migration/command_recorder_test.rb
+++ b/activerecord/test/cases/migration/command_recorder_test.rb
@@ -206,6 +206,11 @@ module ActiveRecord
end
def test_invert_remove_index
+ add = @recorder.inverse_of :remove_index, [:table, :one]
+ assert_equal [:add_index, [:table, :one]], add
+ end
+
+ def test_invert_remove_index_with_column
add = @recorder.inverse_of :remove_index, [:table, {column: [:one, :two], options: true}]
assert_equal [:add_index, [:table, [:one, :two], options: true]], add
end
diff --git a/activerecord/test/cases/primary_keys_test.rb b/activerecord/test/cases/primary_keys_test.rb
index b8433f0bba..0745a37ee9 100644
--- a/activerecord/test/cases/primary_keys_test.rb
+++ b/activerecord/test/cases/primary_keys_test.rb
@@ -182,6 +182,12 @@ class PrimaryKeysTest < ActiveRecord::TestCase
assert_equal "nextval('\"mixed_case_monkeys_monkeyID_seq\"'::regclass)", column.default_function
assert column.serial?
end
+
+ def test_serial_with_unquoted_sequence_name
+ column = Topic.columns_hash[Topic.primary_key]
+ assert_equal "nextval('topics_id_seq'::regclass)", column.default_function
+ assert column.serial?
+ end
end
end
diff --git a/activesupport/lib/active_support/core_ext/hash/conversions.rb b/activesupport/lib/active_support/core_ext/hash/conversions.rb
index 2149d4439d..8594d9bf2e 100644
--- a/activesupport/lib/active_support/core_ext/hash/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/hash/conversions.rb
@@ -106,7 +106,25 @@ class Hash
# # => {"hash"=>{"foo"=>1, "bar"=>2}}
#
# +DisallowedType+ is raised if the XML contains attributes with <tt>type="yaml"</tt> or
- # <tt>type="symbol"</tt>. Use <tt>Hash.from_trusted_xml</tt> to parse this XML.
+ # <tt>type="symbol"</tt>. Use <tt>Hash.from_trusted_xml</tt> to
+ # parse this XML.
+ #
+ # Custom +disallowed_types+ can also be passed in the form of an
+ # array.
+ #
+ # xml = <<-XML
+ # <?xml version="1.0" encoding="UTF-8"?>
+ # <hash>
+ # <foo type="integer">1</foo>
+ # <bar type="string">"David"</bar>
+ # </hash>
+ # XML
+ #
+ # hash = Hash.from_xml(xml, ['integer'])
+ # # => ActiveSupport::XMLConverter::DisallowedType: Disallowed type attribute: "integer"
+ #
+ # Note that passing custom disallowed types will override the default types,
+ # which are Symbol and YAML.
def from_xml(xml, disallowed_types = nil)
ActiveSupport::XMLConverter.new(xml, disallowed_types).to_h
end
diff --git a/activesupport/lib/active_support/json/encoding.rb b/activesupport/lib/active_support/json/encoding.rb
index 48f4967892..031c5e9339 100644
--- a/activesupport/lib/active_support/json/encoding.rb
+++ b/activesupport/lib/active_support/json/encoding.rb
@@ -57,6 +57,10 @@ module ActiveSupport
super.gsub ESCAPE_REGEX_WITHOUT_HTML_ENTITIES, ESCAPED_CHARS
end
end
+
+ def to_s
+ self
+ end
end
# Mark these as private so we don't leak encoding-specific constructs
diff --git a/activesupport/lib/active_support/message_verifier.rb b/activesupport/lib/active_support/message_verifier.rb
index eee9bbaead..b2a4404968 100644
--- a/activesupport/lib/active_support/message_verifier.rb
+++ b/activesupport/lib/active_support/message_verifier.rb
@@ -44,7 +44,7 @@ module ActiveSupport
# tampered_message = signed_message.chop # editing the message invalidates the signature
# verifier.valid_message?(tampered_message) # => false
def valid_message?(signed_message)
- return if signed_message.blank?
+ return if signed_message.nil? || !signed_message.valid_encoding? || signed_message.blank?
data, digest = signed_message.split("--")
data.present? && digest.present? && ActiveSupport::SecurityUtils.secure_compare(digest, generate_digest(data))
diff --git a/activesupport/lib/active_support/xml_mini.rb b/activesupport/lib/active_support/xml_mini.rb
index 009ee4db90..df7b081993 100644
--- a/activesupport/lib/active_support/xml_mini.rb
+++ b/activesupport/lib/active_support/xml_mini.rb
@@ -78,6 +78,9 @@ module ActiveSupport
)
end
+ attr_accessor :depth
+ self.depth = 100
+
delegate :parse, :to => :backend
def backend
diff --git a/activesupport/lib/active_support/xml_mini/jdom.rb b/activesupport/lib/active_support/xml_mini/jdom.rb
index f303daa1a7..94751bbc04 100644
--- a/activesupport/lib/active_support/xml_mini/jdom.rb
+++ b/activesupport/lib/active_support/xml_mini/jdom.rb
@@ -46,7 +46,7 @@ module ActiveSupport
xml_string_reader = StringReader.new(data)
xml_input_source = InputSource.new(xml_string_reader)
doc = @dbf.new_document_builder.parse(xml_input_source)
- merge_element!({CONTENT_KEY => ''}, doc.document_element)
+ merge_element!({CONTENT_KEY => ''}, doc.document_element, XmlMini.depth)
end
end
@@ -58,9 +58,10 @@ module ActiveSupport
# Hash to merge the converted element into.
# element::
# XML element to merge into hash
- def merge_element!(hash, element)
+ def merge_element!(hash, element, depth)
+ raise 'Document too deep!' if depth == 0
delete_empty(hash)
- merge!(hash, element.tag_name, collapse(element))
+ merge!(hash, element.tag_name, collapse(element, depth))
end
def delete_empty(hash)
@@ -71,14 +72,14 @@ module ActiveSupport
#
# element::
# The document element to be collapsed.
- def collapse(element)
+ def collapse(element, depth)
hash = get_attributes(element)
child_nodes = element.child_nodes
if child_nodes.length > 0
(0...child_nodes.length).each do |i|
child = child_nodes.item(i)
- merge_element!(hash, child) unless child.node_type == Node.TEXT_NODE
+ merge_element!(hash, child, depth - 1) unless child.node_type == Node.TEXT_NODE
end
merge_texts!(hash, element) unless empty_content?(element)
hash
diff --git a/activesupport/lib/active_support/xml_mini/rexml.rb b/activesupport/lib/active_support/xml_mini/rexml.rb
index 5c7c78bf70..924ed72345 100644
--- a/activesupport/lib/active_support/xml_mini/rexml.rb
+++ b/activesupport/lib/active_support/xml_mini/rexml.rb
@@ -29,7 +29,7 @@ module ActiveSupport
doc = REXML::Document.new(data)
if doc.root
- merge_element!({}, doc.root)
+ merge_element!({}, doc.root, XmlMini.depth)
else
raise REXML::ParseException,
"The document #{doc.to_s.inspect} does not have a valid root"
@@ -44,19 +44,20 @@ module ActiveSupport
# Hash to merge the converted element into.
# element::
# XML element to merge into hash
- def merge_element!(hash, element)
- merge!(hash, element.name, collapse(element))
+ def merge_element!(hash, element, depth)
+ raise REXML::ParseException, "The document is too deep" if depth == 0
+ merge!(hash, element.name, collapse(element, depth))
end
# Actually converts an XML document element into a data structure.
#
# element::
# The document element to be collapsed.
- def collapse(element)
+ def collapse(element, depth)
hash = get_attributes(element)
if element.has_elements?
- element.each_element {|child| merge_element!(hash, child) }
+ element.each_element {|child| merge_element!(hash, child, depth - 1) }
merge_texts!(hash, element) unless empty_content?(element)
hash
else
diff --git a/activesupport/test/inflector_test.rb b/activesupport/test/inflector_test.rb
index be68bb2e2e..a0764f6d6b 100644
--- a/activesupport/test/inflector_test.rb
+++ b/activesupport/test/inflector_test.rb
@@ -8,6 +8,20 @@ class InflectorTest < ActiveSupport::TestCase
include InflectorTestCases
include ConstantizeTestCases
+ def setup
+ # Dups the singleton before each test, restoring the original inflections later.
+ #
+ # This helper is implemented by setting @__instance__ because in some tests
+ # there are module functions that access ActiveSupport::Inflector.inflections,
+ # so we need to replace the singleton itself.
+ @original_inflections = ActiveSupport::Inflector::Inflections.instance_variable_get(:@__instance__)[:en]
+ ActiveSupport::Inflector::Inflections.instance_variable_set(:@__instance__, en: @original_inflections.dup)
+ end
+
+ def teardown
+ ActiveSupport::Inflector::Inflections.instance_variable_set(:@__instance__, en: @original_inflections)
+ end
+
def test_pluralize_plurals
assert_equal "plurals", ActiveSupport::Inflector.pluralize("plurals")
assert_equal "Plurals", ActiveSupport::Inflector.pluralize("Plurals")
@@ -26,20 +40,18 @@ class InflectorTest < ActiveSupport::TestCase
end
def test_uncountable_word_is_not_greedy
- with_dup do
- uncountable_word = "ors"
- countable_word = "sponsor"
+ uncountable_word = "ors"
+ countable_word = "sponsor"
- ActiveSupport::Inflector.inflections.uncountable << uncountable_word
+ ActiveSupport::Inflector.inflections.uncountable << uncountable_word
- assert_equal uncountable_word, ActiveSupport::Inflector.singularize(uncountable_word)
- assert_equal uncountable_word, ActiveSupport::Inflector.pluralize(uncountable_word)
- assert_equal ActiveSupport::Inflector.pluralize(uncountable_word), ActiveSupport::Inflector.singularize(uncountable_word)
+ assert_equal uncountable_word, ActiveSupport::Inflector.singularize(uncountable_word)
+ assert_equal uncountable_word, ActiveSupport::Inflector.pluralize(uncountable_word)
+ assert_equal ActiveSupport::Inflector.pluralize(uncountable_word), ActiveSupport::Inflector.singularize(uncountable_word)
- assert_equal "sponsor", ActiveSupport::Inflector.singularize(countable_word)
- assert_equal "sponsors", ActiveSupport::Inflector.pluralize(countable_word)
- assert_equal "sponsor", ActiveSupport::Inflector.singularize(ActiveSupport::Inflector.pluralize(countable_word))
- end
+ assert_equal "sponsor", ActiveSupport::Inflector.singularize(countable_word)
+ assert_equal "sponsors", ActiveSupport::Inflector.pluralize(countable_word)
+ assert_equal "sponsor", ActiveSupport::Inflector.singularize(ActiveSupport::Inflector.pluralize(countable_word))
end
SingularToPlural.each do |singular, plural|
@@ -70,11 +82,9 @@ class InflectorTest < ActiveSupport::TestCase
def test_overwrite_previous_inflectors
- with_dup do
- assert_equal("series", ActiveSupport::Inflector.singularize("series"))
- ActiveSupport::Inflector.inflections.singular "series", "serie"
- assert_equal("serie", ActiveSupport::Inflector.singularize("series"))
- end
+ assert_equal("series", ActiveSupport::Inflector.singularize("series"))
+ ActiveSupport::Inflector.inflections.singular "series", "serie"
+ assert_equal("serie", ActiveSupport::Inflector.singularize("series"))
end
MixtureToTitleCase.each_with_index do |(before, titleized), index|
@@ -367,10 +377,8 @@ class InflectorTest < ActiveSupport::TestCase
%w{plurals singulars uncountables humans}.each do |inflection_type|
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def test_clear_#{inflection_type}
- with_dup do
- ActiveSupport::Inflector.inflections.clear :#{inflection_type}
- assert ActiveSupport::Inflector.inflections.#{inflection_type}.empty?, \"#{inflection_type} inflections should be empty after clear :#{inflection_type}\"
- end
+ ActiveSupport::Inflector.inflections.clear :#{inflection_type}
+ assert ActiveSupport::Inflector.inflections.#{inflection_type}.empty?, \"#{inflection_type} inflections should be empty after clear :#{inflection_type}\"
end
RUBY
end
@@ -405,73 +413,63 @@ class InflectorTest < ActiveSupport::TestCase
end
def test_clear_all
- with_dup do
- ActiveSupport::Inflector.inflections do |inflect|
- # ensure any data is present
- inflect.plural(/(quiz)$/i, '\1zes')
- inflect.singular(/(database)s$/i, '\1')
- inflect.uncountable('series')
- inflect.human("col_rpted_bugs", "Reported bugs")
-
- inflect.clear :all
-
- assert inflect.plurals.empty?
- assert inflect.singulars.empty?
- assert inflect.uncountables.empty?
- assert inflect.humans.empty?
- end
+ ActiveSupport::Inflector.inflections do |inflect|
+ # ensure any data is present
+ inflect.plural(/(quiz)$/i, '\1zes')
+ inflect.singular(/(database)s$/i, '\1')
+ inflect.uncountable('series')
+ inflect.human("col_rpted_bugs", "Reported bugs")
+
+ inflect.clear :all
+
+ assert inflect.plurals.empty?
+ assert inflect.singulars.empty?
+ assert inflect.uncountables.empty?
+ assert inflect.humans.empty?
end
end
def test_clear_with_default
- with_dup do
- ActiveSupport::Inflector.inflections do |inflect|
- # ensure any data is present
- inflect.plural(/(quiz)$/i, '\1zes')
- inflect.singular(/(database)s$/i, '\1')
- inflect.uncountable('series')
- inflect.human("col_rpted_bugs", "Reported bugs")
-
- inflect.clear
-
- assert inflect.plurals.empty?
- assert inflect.singulars.empty?
- assert inflect.uncountables.empty?
- assert inflect.humans.empty?
- end
+ ActiveSupport::Inflector.inflections do |inflect|
+ # ensure any data is present
+ inflect.plural(/(quiz)$/i, '\1zes')
+ inflect.singular(/(database)s$/i, '\1')
+ inflect.uncountable('series')
+ inflect.human("col_rpted_bugs", "Reported bugs")
+
+ inflect.clear
+
+ assert inflect.plurals.empty?
+ assert inflect.singulars.empty?
+ assert inflect.uncountables.empty?
+ assert inflect.humans.empty?
end
end
Irregularities.each do |singular, plural|
define_method("test_irregularity_between_#{singular}_and_#{plural}") do
- with_dup do
- ActiveSupport::Inflector.inflections do |inflect|
- inflect.irregular(singular, plural)
- assert_equal singular, ActiveSupport::Inflector.singularize(plural)
- assert_equal plural, ActiveSupport::Inflector.pluralize(singular)
- end
+ ActiveSupport::Inflector.inflections do |inflect|
+ inflect.irregular(singular, plural)
+ assert_equal singular, ActiveSupport::Inflector.singularize(plural)
+ assert_equal plural, ActiveSupport::Inflector.pluralize(singular)
end
end
end
Irregularities.each do |singular, plural|
define_method("test_pluralize_of_irregularity_#{plural}_should_be_the_same") do
- with_dup do
- ActiveSupport::Inflector.inflections do |inflect|
- inflect.irregular(singular, plural)
- assert_equal plural, ActiveSupport::Inflector.pluralize(plural)
- end
+ ActiveSupport::Inflector.inflections do |inflect|
+ inflect.irregular(singular, plural)
+ assert_equal plural, ActiveSupport::Inflector.pluralize(plural)
end
end
end
Irregularities.each do |singular, plural|
define_method("test_singularize_of_irregularity_#{singular}_should_be_the_same") do
- with_dup do
- ActiveSupport::Inflector.inflections do |inflect|
- inflect.irregular(singular, plural)
- assert_equal singular, ActiveSupport::Inflector.singularize(singular)
- end
+ ActiveSupport::Inflector.inflections do |inflect|
+ inflect.irregular(singular, plural)
+ assert_equal singular, ActiveSupport::Inflector.singularize(singular)
end
end
end
@@ -503,12 +501,10 @@ class InflectorTest < ActiveSupport::TestCase
%w(plurals singulars uncountables humans acronyms).each do |scope|
define_method("test_clear_inflections_with_#{scope}") do
- with_dup do
- # clear the inflections
- ActiveSupport::Inflector.inflections do |inflect|
- inflect.clear(scope)
- assert_equal [], inflect.send(scope)
- end
+ # clear the inflections
+ ActiveSupport::Inflector.inflections do |inflect|
+ inflect.clear(scope)
+ assert_equal [], inflect.send(scope)
end
end
end
@@ -520,18 +516,4 @@ class InflectorTest < ActiveSupport::TestCase
assert_equal "HTTP", ActiveSupport::Inflector.pluralize("HTTP")
end
-
- # Dups the singleton and yields, restoring the original inflections later.
- # Use this in tests what modify the state of the singleton.
- #
- # This helper is implemented by setting @__instance__ because in some tests
- # there are module functions that access ActiveSupport::Inflector.inflections,
- # so we need to replace the singleton itself.
- def with_dup
- original = ActiveSupport::Inflector::Inflections.instance_variable_get(:@__instance__)[:en]
- ActiveSupport::Inflector::Inflections.instance_variable_set(:@__instance__, en: original.dup)
- yield
- ensure
- ActiveSupport::Inflector::Inflections.instance_variable_set(:@__instance__, en: original)
- end
end
diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb
index 2f269a66f0..ee47b97a8a 100644
--- a/activesupport/test/json/encoding_test.rb
+++ b/activesupport/test/json/encoding_test.rb
@@ -147,6 +147,13 @@ class TestJSONEncoding < ActiveSupport::TestCase
assert_equal %({\"a\":\"b\",\"c\":\"d\"}), sorted_json(ActiveSupport::JSON.encode(:a => :b, :c => :d))
end
+ def test_hash_keys_encoding
+ ActiveSupport.escape_html_entities_in_json = true
+ assert_equal "{\"\\u003c\\u003e\":\"\\u003c\\u003e\"}", ActiveSupport::JSON.encode("<>" => "<>")
+ ensure
+ ActiveSupport.escape_html_entities_in_json = false
+ end
+
def test_utf8_string_encoded_properly
result = ActiveSupport::JSON.encode('€2.99')
assert_equal '"€2.99"', result
diff --git a/activesupport/test/message_verifier_test.rb b/activesupport/test/message_verifier_test.rb
index 6c3519df9a..668d78492e 100644
--- a/activesupport/test/message_verifier_test.rb
+++ b/activesupport/test/message_verifier_test.rb
@@ -24,6 +24,7 @@ class MessageVerifierTest < ActiveSupport::TestCase
data, hash = @verifier.generate(@data).split("--")
assert !@verifier.valid_message?(nil)
assert !@verifier.valid_message?("")
+ assert !@verifier.valid_message?("\xff") # invalid encoding
assert !@verifier.valid_message?("#{data.reverse}--#{hash}")
assert !@verifier.valid_message?("#{data}--#{hash.reverse}")
assert !@verifier.valid_message?("purejunk")
diff --git a/guides/source/3_0_release_notes.md b/guides/source/3_0_release_notes.md
index 9ad32e8168..696493a3cf 100644
--- a/guides/source/3_0_release_notes.md
+++ b/guides/source/3_0_release_notes.md
@@ -88,7 +88,7 @@ $ cd myapp
Rails now uses a `Gemfile` in the application root to determine the gems you require for your application to start. This `Gemfile` is processed by the [Bundler](http://github.com/carlhuda/bundler,) which then installs all your dependencies. It can even install all the dependencies locally to your application so that it doesn't depend on the system gems.
-More information: - [bundler homepage](http://gembundler.com)
+More information: - [bundler homepage](http://bundler.io/)
### Living on the Edge
diff --git a/guides/source/3_1_release_notes.md b/guides/source/3_1_release_notes.md
index d753346fa3..327495704a 100644
--- a/guides/source/3_1_release_notes.md
+++ b/guides/source/3_1_release_notes.md
@@ -151,7 +151,7 @@ $ cd myapp
Rails now uses a `Gemfile` in the application root to determine the gems you require for your application to start. This `Gemfile` is processed by the [Bundler](https://github.com/carlhuda/bundler) gem, which then installs all your dependencies. It can even install all the dependencies locally to your application so that it doesn't depend on the system gems.
-More information: - [bundler homepage](http://gembundler.com)
+More information: - [bundler homepage](http://bundler.io/)
### Living on the Edge
diff --git a/guides/source/3_2_release_notes.md b/guides/source/3_2_release_notes.md
index 6ddf77d9c0..c52c39b705 100644
--- a/guides/source/3_2_release_notes.md
+++ b/guides/source/3_2_release_notes.md
@@ -81,7 +81,7 @@ $ cd myapp
Rails now uses a `Gemfile` in the application root to determine the gems you require for your application to start. This `Gemfile` is processed by the [Bundler](https://github.com/carlhuda/bundler) gem, which then installs all your dependencies. It can even install all the dependencies locally to your application so that it doesn't depend on the system gems.
-More information: [Bundler homepage](http://gembundler.com)
+More information: [Bundler homepage](http://bundler.io/)
### Living on the Edge
diff --git a/guides/source/4_0_release_notes.md b/guides/source/4_0_release_notes.md
index 9feaff098a..b9444510ea 100644
--- a/guides/source/4_0_release_notes.md
+++ b/guides/source/4_0_release_notes.md
@@ -36,7 +36,7 @@ $ cd myapp
Rails now uses a `Gemfile` in the application root to determine the gems you require for your application to start. This `Gemfile` is processed by the [Bundler](https://github.com/carlhuda/bundler) gem, which then installs all your dependencies. It can even install all the dependencies locally to your application so that it doesn't depend on the system gems.
-More information: [Bundler homepage](http://gembundler.com)
+More information: [Bundler homepage](http://bundler.io)
### Living on the Edge
diff --git a/guides/source/action_controller_overview.md b/guides/source/action_controller_overview.md
index 7d95d4792e..d506722f75 100644
--- a/guides/source/action_controller_overview.md
+++ b/guides/source/action_controller_overview.md
@@ -185,7 +185,9 @@ end
These options will be used as a starting point when generating URLs, so it's possible they'll be overridden by the options passed to `url_for` calls.
-If you define `default_url_options` in `ApplicationController`, as in the example above, it will be used for all URL generation. The method can also be defined in a specific controller, in which case it only affects URLs generated there.
+If you define `default_url_options` in `ApplicationController`, as in the example above, these defaults will be used for all URL generation. The method can also be defined in a specific controller, in which case it only affects URLs generated there.
+
+In a given request, the method is not actually called for every single generated URL; for performance reasons, the returned hash is cached, there is at most one invocation per request.
### Strong Parameters
diff --git a/guides/source/active_job_basics.md b/guides/source/active_job_basics.md
index 29d0c32b09..22f3c0146a 100644
--- a/guides/source/active_job_basics.md
+++ b/guides/source/active_job_basics.md
@@ -4,7 +4,7 @@ Active Job Basics
=================
This guide provides you with all you need to get started in creating,
-enqueueing and executing background jobs.
+enqueuing and executing background jobs.
After reading this guide, you will know:
@@ -20,7 +20,7 @@ Introduction
------------
Active Job is a framework for declaring jobs and making them run on a variety
-of queueing backends. These jobs can be everything from regularly scheduled
+of queuing backends. These jobs can be everything from regularly scheduled
clean-ups, to billing charges, to mailings. Anything that can be chopped up
into small units of work and run in parallel, really.
@@ -28,11 +28,14 @@ into small units of work and run in parallel, really.
The Purpose of Active Job
-----------------------------
The main point is to ensure that all Rails apps will have a job infrastructure
-in place, even if it's in the form of an "immediate runner". We can then have
-framework features and other gems build on top of that, without having to
-worry about API differences between various job runners such as Delayed Job
-and Resque. Picking your queuing backend becomes more of an operational concern,
-then. And you'll be able to switch between them without having to rewrite your jobs.
+in place. We can then have framework features and other gems build on top of that,
+without having to worry about API differences between various job runners such as
+Delayed Job and Resque. Picking your queuing backend becomes more of an operational
+concern, then. And you'll be able to switch between them without having to rewrite
+your jobs.
+
+NOTE: Rails by default comes with an "immediate runner" queuing implementation.
+That means that each job that has been enqueued will run immediately.
Creating a Job
@@ -78,7 +81,7 @@ end
Enqueue a job like so:
```ruby
-# Enqueue a job to be performed as soon the queueing system is
+# Enqueue a job to be performed as soon the queuing system is
# free.
MyJob.perform_later record
```
@@ -99,17 +102,20 @@ That's it!
Job Execution
-------------
-If no adapter is set, the job is immediately executed.
+For enqueuing and executing jobs you need to set up a queuing backend, that is to
+say you need to decide for a 3rd-party queuing library that Rails should use.
+Rails itself does not provide a sophisticated queuing system and just executes the
+job immediately if no adapter is set.
### Backends
-Active Job has built-in adapters for multiple queueing backends (Sidekiq,
+Active Job has built-in adapters for multiple queuing backends (Sidekiq,
Resque, Delayed Job and others). To get an up-to-date list of the adapters
see the API Documentation for [ActiveJob::QueueAdapters](http://api.rubyonrails.org/classes/ActiveJob/QueueAdapters.html).
### Setting the Backend
-You can easily set your queueing backend:
+You can easily set your queuing backend:
```ruby
# config/application.rb
@@ -123,6 +129,10 @@ module YourApp
end
```
+NOTE: Since jobs run in parallel to your Rails application, most queuing libraries
+require that you start a library-specific queuing service (in addition to
+starting your Rails app) for the job processing to work. For information on
+how to do that refer to the documentation of your respective library.
Queues
------
@@ -212,7 +222,7 @@ end
ProcessVideoJob.perform_later(Video.last)
```
-NOTE: Make sure your queueing backend "listens" on your queue name. For some
+NOTE: Make sure your queuing backend "listens" on your queue name. For some
backends you need to specify the queues to listen to.
diff --git a/guides/source/active_record_postgresql.md b/guides/source/active_record_postgresql.md
index dcc523eb0f..fe112a4708 100644
--- a/guides/source/active_record_postgresql.md
+++ b/guides/source/active_record_postgresql.md
@@ -266,13 +266,14 @@ revision = Revision.first
revision.identifier # => "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11"
```
-You can use `uuid` type to define references in migrations
+You can use `uuid` type to define references in migrations:
```ruby
# db/migrate/20150418012400_create_blog.rb
-create_table :posts, id: :uuid
+enable_extension 'pgcrypto' unless extension_enabled?('pgcrypto')
+create_table :posts, id: :uuid, default: 'gen_random_uuid()'
-create_table :comments, id: :uuid do |t|
+create_table :comments, id: :uuid, default: 'gen_random_uuid()' do |t|
# t.belongs_to :post, type: :uuid
t.references :post, type: :uuid
end
@@ -288,6 +289,8 @@ class Comment < ActiveRecord::Base
end
```
+See [this section](#uuid-primary-keys) for more details on using UUIDs as primary key.
+
### Bit String Types
* [type definition](http://www.postgresql.org/docs/current/static/datatype-bit.html)
@@ -377,6 +380,9 @@ device = Device.create
device.id # => "814865cd-5a1d-4771-9306-4268f188fe9e"
```
+NOTE: `uuid_generate_v4()` (from `uuid-ossp`) is assumed if no `:default` option was
+passed to `create_table`.
+
Full Text Search
----------------
diff --git a/guides/source/api_app.md b/guides/source/api_app.md
index 0a6335ed88..29ca872254 100644
--- a/guides/source/api_app.md
+++ b/guides/source/api_app.md
@@ -1,435 +1,408 @@
-Using Rails for API-only Apps
-=============================
+**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON http://guides.rubyonrails.org.**
+
+
+Using Rails for API-only Applications
+=====================================
In this guide you will learn:
-- What Rails provides for API-only applications
-- How to configure Rails to start without any browser features
-- How to decide which middlewares you will want to include
-- How to decide which modules to use in your controller
+* What Rails provides for API-only applications
+* How to configure Rails to start without any browser features
+* How to decide which middlewares you will want to include
+* How to decide which modules to use in your controller
-endprologue.
+--------------------------------------------------------------------------------
-### What is an API app?
+What is an API app?
+-------------------
-Traditionally, when people said that they used Rails as an “API”, they
-meant providing a programmatically accessible API alongside their web
-application.\
-For example, GitHub provides [an API](http://developer.github.com) that
-you can use from your own custom clients.
+Traditionally, when people said that they used Rails as an "API", they meant
+providing a programmatically accessible API alongside their web application.
+For example, GitHub provides [an API](http://developer.github.com) that you
+can use from your own custom clients.
-With the advent of client-side frameworks, more developers are using
-Rails to build a backend that is shared between their web application
-and other native applications.
+With the advent of client-side frameworks, more developers are using Rails to
+build a back-end that is shared between their web application and other native
+applications.
-For example, Twitter uses its [public API](https://dev.twitter.com) in
-its web application, which is built as a static site that consumes JSON
-resources.
+For example, Twitter uses its [public API](https://dev.twitter.com) in its web
+application, which is built as a static site that consumes JSON resources.
-Instead of using Rails to generate dynamic HTML that will communicate
-with the server through forms and links, many developers are treating
-their web application as just another client, delivered as static HTML,
-CSS and JavaScript, and consuming a simple JSON API
+Instead of using Rails to generate dynamic HTML that will communicate with the
+server through forms and links, many developers are treating their web application
+as just another client, delivered as static HTML, CSS and JavaScript consuming
+a simple JSON API.
-This guide covers building a Rails application that serves JSON
-resources to an API client **or** client-side framework.
+This guide covers building a Rails application that serves JSON resources to an
+API client **or** a client-side framework.
-### Why use Rails for JSON APIs?
+Why use Rails for JSON APIs?
+----------------------------
-The first question a lot of people have when thinking about building a
-JSON API using Rails is: “isn’t using Rails to spit out some JSON
-overkill? Shouldn’t I just use something like Sinatra?”
+The first question a lot of people have when thinking about building a JSON API
+using Rails is: "isn't using Rails to spit out some JSON overkill? Shouldn't I
+just use something like Sinatra?".
For very simple APIs, this may be true. However, even in very HTML-heavy
-applications, most of an application’s logic is actually outside of the
-view layer.
+applications, most of an application's logic is actually outside of the view
+layer.
-The reason most people use Rails is that it provides a set of defaults
-that allows us to get up and running quickly without having to make a
-lot of trivial decisions.
+The reason most people use Rails is that it provides a set of defaults that
+allows us to get up and running quickly without having to make a lot of trivial
+decisions.
-Let’s take a look at some of the things that Rails provides out of the
-box that are still applicable to API applications.
+Let's take a look at some of the things that Rails provides out of the box that are
+still applicable to API applications.
Handled at the middleware layer:
-- Reloading: Rails applications support transparent reloading. This
- works even if your application gets big and restarting the server
- for every request becomes non-viable.
-- Development Mode: Rails application come with smart defaults for
- development, making development pleasant without compromising
- production-time performance.
-- Test Mode: Ditto test mode.
-- Logging: Rails applications log every request, with a level of
- verbosity appropriate for the current mode. Rails logs in
- development include information about the request environment,
- database queries, and basic performance information.
-- Security: Rails detects and thwarts [IP spoofing
- attacks](http://en.wikipedia.org/wiki/IP_address_spoofing) and
- handles cryptographic signatures in a [timing
- attack](http://en.wikipedia.org/wiki/Timing_attack) aware way. Don’t
- know what an IP spoofing attack or a timing attack is? Exactly.
-- Parameter Parsing: Want to specify your parameters as JSON instead
- of as a URL-encoded String? No problem. Rails will decode the JSON
- for you and make it available in *params*. Want to use nested
- URL-encoded params? That works too.
-- Conditional GETs: Rails handles conditional *GET*, (*ETag* and
- *Last-Modified*), processing request headers and returning the
- correct response headers and status code. All you need to do is use
- the
- [stale?](http://api.rubyonrails.org/classes/ActionController/ConditionalGet.html#method-i-stale-3F)
- check in your controller, and Rails will handle all of the HTTP
- details for you.
-- Caching: If you use *dirty?* with public cache control, Rails will
- automatically cache your responses. You can easily configure the
- cache store.
-- HEAD requests: Rails will transparently convert *HEAD* requests into
- *GET* requests, and return just the headers on the way out. This
- makes *HEAD* work reliably in all Rails APIs.
-
-While you could obviously build these up in terms of existing Rack
-middlewares, I think this list demonstrates that the default Rails
-middleware stack provides a lot of value, even if you’re “just
-generating JSON”.
-
-Handled at the ActionPack layer:
-
-- Resourceful Routing: If you’re building a RESTful JSON API, you want
- to be using the Rails router. Clean and conventional mapping from
- HTTP to controllers means not having to spend time thinking about
- how to model your API in terms of HTTP.
-- URL Generation: The flip side of routing is URL generation. A good
- API based on HTTP includes URLs (see [the GitHub gist
- API](http://developer.github.com/v3/gists/) for an example).
-- Header and Redirection Responses: *head :no\_content* and
- *redirect\_to user\_url(current\_user)* come in handy. Sure, you
- could manually add the response headers, but why?
-- Caching: Rails provides page, action and fragment caching. Fragment
- caching is especially helpful when building up a nested JSON object.
-- Basic, Digest and Token Authentication: Rails comes with
- out-of-the-box support for three kinds of HTTP authentication.
-- Instrumentation: Rails 3.0 added an instrumentation API that will
- trigger registered handlers for a variety of events, such as action
- processing, sending a file or data, redirection, and database
- queries. The payload of each event comes with relevant information
- (for the action processing event, the payload includes the
- controller, action, params, request format, request method and the
- request’s full path).
-- Generators: This may be passé for advanced Rails users, but it can
- be nice to generate a resource and get your model, controller, test
- stubs, and routes created for you in a single command.
-- Plugins: Many third-party libraries come with support for Rails that
- reduces or eliminates the cost of setting up and gluing together the
- library and the web framework. This includes things like overriding
- default generators, adding rake tasks, and honoring Rails choices
- (like the logger and cache backend).
-
-Of course, the Rails boot process also glues together all registered
-components. For example, the Rails boot process is what uses your
-*config/database.yml* file when configuring ActiveRecord.
-
-**The short version is**: you may not have thought about which parts of
-Rails are still applicable even if you remove the view layer, but the
-answer turns out to be “most of it”.
-
-### The Basic Configuration
-
-If you’re building a Rails application that will be an API server first
-and foremost, you can start with a more limited subset of Rails and add
-in features as needed.
+- Reloading: Rails applications support transparent reloading. This works even if
+ your application gets big and restarting the server for every request becomes
+ non-viable.
+- Development Mode: Rails applications come with smart defaults for development,
+ making development pleasant without compromising production-time performance.
+- Test Mode: Ditto development mode.
+- Logging: Rails applications log every request, with a level of verbosity
+ appropriate for the current mode. Rails logs in development include information
+ about the request environment, database queries, and basic performance
+ information.
+- Security: Rails detects and thwarts [IP spoofing
+ attacks](http://en.wikipedia.org/wiki/IP_address_spoofing) and handles
+ cryptographic signatures in a [timing
+ attack](http://en.wikipedia.org/wiki/Timing_attack) aware way. Don't know what
+ an IP spoofing attack or a timing attack is? Exactly.
+- Parameter Parsing: Want to specify your parameters as JSON instead of as a
+ URL-encoded String? No problem. Rails will decode the JSON for you and make
+ it available in `params`. Want to use nested URL-encoded parameters? That
+ works too.
+- Conditional GETs: Rails handles conditional `GET`, (`ETag` and `Last-Modified`),
+ processing request headers and returning the correct response headers and status
+ code. All you need to do is use the
+ [`stale?`](http://api.rubyonrails.org/classes/ActionController/ConditionalGet.html#method-i-stale-3F)
+ check in your controller, and Rails will handle all of the HTTP details for you.
+- Caching: If you use `dirty?` with public cache control, Rails will automatically
+ cache your responses. You can easily configure the cache store.
+- HEAD requests: Rails will transparently convert `HEAD` requests into `GET` ones,
+ and return just the headers on the way out. This makes `HEAD` work reliably in
+ all Rails APIs.
+
+While you could obviously build these up in terms of existing Rack middlewares,
+this list demonstrates that the default Rails middleware stack provides a lot
+of value, even if you're "just generating JSON".
+
+Handled at the Action Pack layer:
+
+- Resourceful Routing: If you're building a RESTful JSON API, you want to be
+ using the Rails router. Clean and conventional mapping from HTTP to controllers
+ means not having to spend time thinking about how to model your API in terms
+ of HTTP.
+- URL Generation: The flip side of routing is URL generation. A good API based
+ on HTTP includes URLs (see [the GitHub gist API](http://developer.github.com/v3/gists/)
+ for an example).
+- Header and Redirection Responses: `head :no_content` and
+ `redirect_to user_url(current_user)` come in handy. Sure, you could manually
+ add the response headers, but why?
+- Caching: Rails provides page, action and fragment caching. Fragment caching
+ is especially helpful when building up a nested JSON object.
+- Basic, Digest and Token Authentication: Rails comes with out-of-the-box support
+ for three kinds of HTTP authentication.
+- Instrumentation: Rails has an instrumentation API that will trigger registered
+ handlers for a variety of events, such as action processing, sending a file or
+ data, redirection, and database queries. The payload of each event comes with
+ relevant information (for the action processing event, the payload includes
+ the controller, action, parameters, request format, request method and the
+ request's full path).
+- Generators: This may be passé for advanced Rails users, but it can be nice to
+ generate a resource and get your model, controller, test stubs, and routes
+ created for you in a single command.
+- Plugins: Many third-party libraries come with support for Rails that reduce
+ or eliminate the cost of setting up and gluing together the library and the
+ web framework. This includes things like overriding default generators, adding
+ rake tasks, and honoring Rails choices (like the logger and cache back-end).
+
+Of course, the Rails boot process also glues together all registered components.
+For example, the Rails boot process is what uses your `config/database.yml` file
+when configuring Active Record.
+
+**The short version is**: you may not have thought about which parts of Rails
+are still applicable even if you remove the view layer, but the answer turns out
+to be "most of it".
+
+The Basic Configuration
+-----------------------
+
+If you're building a Rails application that will be an API server first and
+foremost, you can start with a more limited subset of Rails and add in features
+as needed.
You can generate a new api Rails app:
-<shell>\
-\$ rails new my\_api --api\
-</shell>
+```bash
+$ rails new my_api --api
+```
This will do three main things for you:
-- Configure your application to start with a more limited set of
- middleware than normal. Specifically, it will not include any
- middleware primarily useful for browser applications (like cookie
- support) by default.
-- Make *ApplicationController* inherit from *ActionController::API*
- instead of *ActionController::Base*. As with middleware, this will
- leave out any *ActionController* modules that provide functionality
- primarily used by browser applications.
-- Configure the generators to skip generating views, helpers and
- assets when you generate a new resource.
-
-If you want to take an existing app and make it an API app, follow the
+- Configure your application to start with a more limited set of middlewares
+ than normal. Specifically, it will not include any middleware primarily useful
+ for browser applications (like cookies support) by default.
+- Make `ApplicationController` inherit from `ActionController::API` instead of
+ `ActionController::Base`. As with middlewares, this will leave out any Action
+ Controller modules that provide functionalities primarily used by browser
+ applications.
+- Configure the generators to skip generating views, helpers and assets when
+ you generate a new resource.
+
+If you want to take an existing application and make it an API one, read the
following steps.
-In *config/application.rb* add the following line at the top of the
-*Application* class:
-
-<ruby>\
-config.api\_only!\
-</ruby>
-
-Change *app/controllers/application\_controller.rb*:
-
-<ruby>
-
-1. instead of\
- class ApplicationController \< ActionController::Base\
- end
-
-<!-- -->
-
-1. do\
- class ApplicationController \< ActionController::API\
- end\
- </ruby>
-
-### Choosing Middlewares
-
-An API application comes with the following middlewares by default.
-
-- *Rack::Cache*: Caches responses with public *Cache-Control* headers
- using HTTP caching semantics. See below for more information.
-- *Rack::Sendfile*: Uses a front-end server’s file serving support
- from your Rails application.
-- *Rack::Lock*: If your application is not marked as threadsafe
- (*config.threadsafe!*), this middleware will add a mutex around your
- requests.
-- *ActionDispatch::RequestId*:
-- *Rails::Rack::Logger*:
-- *Rack::Runtime*: Adds a header to the response listing the total
- runtime of the request.
-- *ActionDispatch::ShowExceptions*: Rescue exceptions and re-dispatch
- them to an exception handling application
-- *ActionDispatch::DebugExceptions*: Log exceptions
-- *ActionDispatch::RemoteIp*: Protect against IP spoofing attacks
-- *ActionDispatch::Reloader*: In development mode, support code
- reloading.
-- *ActionDispatch::ParamsParser*: Parse XML, YAML and JSON parameters
- when the request’s *Content-Type* is one of those.
-- *ActionDispatch::Head*: Dispatch *HEAD* requests as *GET* requests,
- and return only the status code and headers.
-- *Rack::ConditionalGet*: Supports the *stale?* feature in Rails
- controllers.
-- *Rack::ETag*: Automatically set an *ETag* on all string responses.
- This means that if the same response is returned from a controller
- for the same URL, the server will return a *304 Not Modified*, even
- if no additional caching steps are taken. This is primarily a
- client-side optimization; it reduces bandwidth costs but not server
- processing time.
-
-Other plugins, including *ActiveRecord*, may add additional middlewares.
-In general, these middlewares are agnostic to the type of app you are
+In `config/application.rb` add the following line at the top of the `Application`
+class definition:
+
+```ruby
+config.api_only = true
+```
+
+Finally, inside `app/controllers/application_controller.rb`, instead of:
+
+```ruby
+class ApplicationController < ActionController::Base
+end
+```
+
+do:
+
+```ruby
+class ApplicationController < ActionController::API
+end
+```
+
+Choosing Middlewares
+--------------------
+
+An API application comes with the following middlewares by default:
+
+- `Rack::Sendfile`
+- `ActionDispatch::Static`
+- `Rack::Lock`
+- `ActiveSupport::Cache::Strategy::LocalCache::Middleware`
+- `ActionDispatch::RequestId`
+- `Rails::Rack::Logger`
+- `Rack::Runtime`
+- `ActionDispatch::ShowExceptions`
+- `ActionDispatch::DebugExceptions`
+- `ActionDispatch::RemoteIp`
+- `ActionDispatch::Reloader`
+- `ActionDispatch::Callbacks`
+- `ActionDispatch::ParamsParser`
+- `Rack::Head`
+- `Rack::ConditionalGet`
+- `Rack::ETag`
+
+See the [internal middlewares](rails_on_rack.html#internal-middleware-stack)
+section of the Rack guide for further information on them.
+
+Other plugins, including Active Record, may add additional middlewares. In
+general, these middlewares are agnostic to the type of application you are
building, and make sense in an API-only Rails application.
You can get a list of all middlewares in your application via:
-<shell>\
-\$ rake middleware\
-</shell>
+```bash
+$ rake middleware
+```
-#### Using Rack::Cache
+### Using the Cache Middleware
-When used with Rails, *Rack::Cache* uses the Rails cache store for its
-entity and meta stores. This means that if you use memcache, for your
-Rails app, for instance, the built-in HTTP cache will use memcache.
+By default, Rails will add a middleware that provides a cache store based on
+the configuration of your application (memcache by default). This means that
+the built-in HTTP cache will rely on it.
-To make use of *Rack::Cache*, you will want to use *stale?* in your
-controller. Here’s an example of *stale?* in use.
+For instance, using the `stale?` method:
-<ruby>\
-def show\
+```ruby
+def show
@post = Post.find(params[:id])
-if stale?(:last\_modified =\> `post.updated_at)
- render json: `post\
- end\
-end\
-</ruby>
+ if stale?(last_modified: @post.updated_at)
+ render json: @post
+ end
+end
+```
-The call to *stale?* will compare the *If-Modified-Since* header in the
-request with *@post.updated\_at*. If the header is newer than the last
-modified, this action will return a *304 Not Modified* response.
-Otherwise, it will render the response and include a *Last-Modified*
-header with the response.
+The call to `stale?` will compare the `If-Modified-Since` header in the request
+with `@post.updated_at`. If the header is newer than the last modified, this
+action will return a "304 Not Modified" response. Otherwise, it will render the
+response and include a `Last-Modified` header in it.
-Normally, this mechanism is used on a per-client basis. *Rack::Cache*
+Normally, this mechanism is used on a per-client basis. The cache middleware
allows us to share this caching mechanism across clients. We can enable
-cross-client caching in the call to *stale?*
+cross-client caching in the call to `stale?`:
-<ruby>\
-def show\
+```ruby
+def show
@post = Post.find(params[:id])
-if stale?(:last\_modified =\> `post.updated_at, :public => true)
- render json: `post\
- end\
-end\
-</ruby>
+ if stale?(last_modified: @post.updated_at, public: true)
+ render json: @post
+ end
+end
+```
-This means that *Rack::Cache* will store off *Last-Modified* value for a
-URL in the Rails cache, and add an *If-Modified-Since* header to any
+This means that the cache middleware will store off the `Last-Modified` value
+for a URL in the Rails cache, and add an `If-Modified-Since` header to any
subsequent inbound requests for the same URL.
Think of it as page caching using HTTP semantics.
-NOTE: The *Rack::Cache* middleware is always outside of the *Rack::Lock*
-mutex, even in single-threaded apps.
+NOTE: This middleware is always outside of the `Rack::Lock` mutex, even in
+single-threaded applications.
-#### Using Rack::Sendfile
+### Using Rack::Sendfile
-When you use the *send\_file* method in a Rails controller, it sets the
-*X-Sendfile* header. *Rack::Sendfile* is responsible for actually
-sending the file.
+When you use the `send_file` method inside a Rails controller, it sets the
+`X-Sendfile` header. `Rack::Sendfile` is responsible for actually sending the
+file.
-If your front-end server supports accelerated file sending,
-*Rack::Sendfile* will offload the actual file sending work to the
-front-end server.
+If your front-end server supports accelerated file sending, `Rack::Sendfile`
+will offload the actual file sending work to the front-end server.
-You can configure the name of the header that your front-end server uses
-for this purposes using *config.action\_dispatch.x\_sendfile\_header* in
-the appropriate environment config file.
+You can configure the name of the header that your front-end server uses for
+this purpose using `config.action_dispatch.x_sendfile_header` in the appropriate
+environment's configuration file.
-You can learn more about how to use *Rack::Sendfile* with popular
+You can learn more about how to use `Rack::Sendfile` with popular
front-ends in [the Rack::Sendfile
-documentation](http://rubydoc.info/github/rack/rack/master/Rack/Sendfile)
+documentation](http://rubydoc.info/github/rack/rack/master/Rack/Sendfile).
-The values for popular servers once they are configured to support
+Here are some values for popular servers, once they are configured, to support
accelerated file sending:
-<ruby>
-
-1. Apache and lighttpd\
- config.action\_dispatch.x\_sendfile\_header = “X-Sendfile”
-
-<!-- -->
-
-1. nginx\
- config.action\_dispatch.x\_sendfile\_header = “X-Accel-Redirect”\
- </ruby>
-
-Make sure to configure your server to support these options following
-the instructions in the *Rack::Sendfile* documentation.
-
-NOTE: The *Rack::Sendfile* middleware is always outside of the
-*Rack::Lock* mutex, even in single-threaded apps.
-
-#### Using ActionDispatch::ParamsParser
-
-*ActionDispatch::ParamsParser* will take parameters from the client in
-JSON and make them available in your controller as *params*.
-
-To use this, your client will need to make a request with JSON-encoded
-parameters and specify the *Content-Type* as *application/json*.
-
-Here’s an example in jQuery:
-
-<plain>\
-jQuery.ajax({\
- type: ‘POST’,\
- url: ‘/people’\
- dataType: ‘json’,\
- contentType: ‘application/json’,\
- data: JSON.stringify({ person: { firstName: “Yehuda”, lastName: “Katz”
-} }),
-
-success: function(json) { }\
-});\
-</plain>
-
-*ActionDispatch::ParamsParser* will see the *Content-Type* and your
-params will be *{ :person =\> { :firstName =\> “Yehuda”, :lastName =\>
-“Katz” } }*.
-
-#### Other Middlewares
-
-Rails ships with a number of other middlewares that you might want to
-use in an API app, especially if one of your API clients is the browser:
-
-- *Rack::MethodOverride*: Allows the use of the *\_method* hack to
- route POST requests to other verbs.
-- *ActionDispatch::Cookies*: Supports the *cookie* method in
- *ActionController*, including support for signed and encrypted
- cookies.
-- *ActionDispatch::Flash*: Supports the *flash* mechanism in
- *ActionController*.
-- *ActionDispatch::BestStandards*: Tells Internet Explorer to use the
- most standards-compliant available renderer. In production mode, if
- ChromeFrame is available, use ChromeFrame.
-- Session Management: If a *config.session\_store* is supplied, this
- middleware makes the session available as the *session* method in
- *ActionController*.
-
-Any of these middlewares can be adding via:
-
-<ruby>\
-config.middleware.use Rack::MethodOverride\
-</ruby>
-
-#### Removing Middlewares
-
-If you don’t want to use a middleware that is included by default in the
-API-only middleware set, you can remove it using
-*config.middleware.delete*:
-
-<ruby>\
-config.middleware.delete ::Rack::Sendfile\
-</ruby>
-
-Keep in mind that removing these features may remove support for certain
-features in *ActionController*.
-
-### Choosing Controller Modules
-
-An API application (using *ActionController::API*) comes with the
-following controller modules by default:
-
-- *ActionController::UrlFor*: Makes *url\_for* and friends available
-- *ActionController::Redirecting*: Support for *redirect\_to*
-- *ActionController::Rendering*: Basic support for rendering
-- *ActionController::Renderers::All*: Support for *render :json* and
- friends
-- *ActionController::ConditionalGet*: Support for *stale?*
-- *ActionController::ForceSSL*: Support for *force\_ssl*
-- *ActionController::RackDelegation*: Support for the *request* and
- *response* methods returning *ActionDispatch::Request* and
- *ActionDispatch::Response* objects.
-- *ActionController::DataStreaming*: Support for *send\_file* and
- *send\_data*
-- *AbstractController::Callbacks*: Support for *before\_filter* and
- friends
-- *ActionController::Instrumentation*: Support for the instrumentation
- hooks defined by *ActionController* (see [the
- source](https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal/instrumentation.rb)
- for more).
-- *ActionController::Rescue*: Support for *rescue\_from*.
-
-Other plugins may add additional modules. You can get a list of all
-modules included into *ActionController::API* in the rails console:
-
-<shell>\
-\$ irb\
-\>\> ActionController::API.ancestors -
-ActionController::Metal.ancestors\
-</shell>
-
-#### Adding Other Modules
-
-All ActionController modules know about their dependent modules, so you
-can feel free to include any modules into your controllers, and all
-dependencies will be included and set up as well.
+```ruby
+# Apache and lighttpd
+config.action_dispatch.x_sendfile_header = "X-Sendfile"
+
+# Nginx
+config.action_dispatch.x_sendfile_header = "X-Accel-Redirect"
+```
+
+Make sure to configure your server to support these options following the
+instructions in the `Rack::Sendfile` documentation.
+
+NOTE: The `Rack::Sendfile` middleware is always outside of the `Rack::Lock`
+mutex, even in single-threaded applications.
+
+### Using ActionDispatch::ParamsParser
+
+`ActionDispatch::ParamsParser` will take parameters from the client in the JSON
+format and make them available in your controller inside `params`.
+
+To use this, your client will need to make a request with JSON-encoded parameters
+and specify the `Content-Type` as `application/json`.
+
+Here's an example in jQuery:
+
+```javascript
+jQuery.ajax({
+ type: 'POST',
+ url: '/people',
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify({ person: { firstName: "Yehuda", lastName: "Katz" } }),
+ success: function(json) { }
+});
+```
+
+`ActionDispatch::ParamsParser` will see the `Content-Type` and your parameters
+will be:
+
+```ruby
+{ :person => { :firstName => "Yehuda", :lastName => "Katz" } }
+```
+
+### Other Middlewares
+
+Rails ships with a number of other middlewares that you might want to use in an
+API application, especially if one of your API clients is the browser:
+
+- `Rack::MethodOverride`
+- `ActionDispatch::Cookies`
+- `ActionDispatch::Flash`
+- For sessions management
+ * `ActionDispatch::Session::CacheStore`
+ * `ActionDispatch::Session::CookieStore`
+ * `ActionDispatch::Session::MemCacheStore`
+
+Any of these middlewares can be added via:
+
+```ruby
+config.middleware.use Rack::MethodOverride
+```
+
+### Removing Middlewares
+
+If you don't want to use a middleware that is included by default in the API-only
+middleware set, you can remove it with:
+
+```ruby
+config.middleware.delete ::Rack::Sendfile
+```
+
+Keep in mind that removing these middlewares will remove support for certain
+features in Action Controller.
+
+Choosing Controller Modules
+---------------------------
+
+An API application (using `ActionController::API`) comes with the following
+controller modules by default:
+
+- `ActionController::UrlFor`: Makes `url_for` and friends available.
+- `ActionController::Redirecting`: Support for `redirect_to`.
+- `ActionController::Rendering`: Basic support for rendering.
+- `ActionController::Renderers::All`: Support for `render :json` and friends.
+- `ActionController::ConditionalGet`: Support for `stale?`.
+- `ActionController::ForceSSL`: Support for `force_ssl`.
+- `ActionController::RackDelegation`: Support for the `request` and `response`
+ methods returning `ActionDispatch::Request` and `ActionDispatch::Response`
+ objects.
+- `ActionController::DataStreaming`: Support for `send_file` and `send_data`.
+- `AbstractController::Callbacks`: Support for `before_filter` and friends.
+- `ActionController::Instrumentation`: Support for the instrumentation
+ hooks defined by Action Controller (see [the instrumentation
+ guide](active_support_instrumentation.html#action-controller)).
+- `ActionController::Rescue`: Support for `rescue_from`.
+- `ActionController::BasicImplicitRender`: Makes sure to return an empty response
+ if there's not an explicit one.
+- `ActionController::StrongParameters`: Support for parameters white-listing in
+ combination with Active Model mass assignment.
+- `ActionController::ParamsWrapper`: Wraps the parameters hash into a nested hash
+ so you don't have to specify root elements sending POST requests for instance.
+
+Other plugins may add additional modules. You can get a list of all modules
+included into `ActionController::API` in the rails console:
+
+```bash
+$ bin/rails c
+>> ActionController::API.ancestors - ActionController::Metal.ancestors
+```
+
+### Adding Other Modules
+
+All Action Controller modules know about their dependent modules, so you can feel
+free to include any modules into your controllers, and all dependencies will be
+included and set up as well.
Some common modules you might want to add:
-- *AbstractController::Translation*: Support for the *l* and *t*
- localization and translation methods. These delegate to
- *I18n.translate* and *I18n.localize*.
-- *ActionController::HTTPAuthentication::Basic* (or *Digest*
- or +Token): Support for basic, digest or token HTTP authentication.
-- *AbstractController::Layouts*: Support for layouts when rendering.
-- *ActionController::MimeResponds*: Support for content negotiation
- (*respond\_to*, *respond\_with*).
-- *ActionController::Cookies*: Support for *cookies*, which includes
- support for signed and encrypted cookies. This requires the cookie
- middleware.
-
-The best place to add a module is in your *ApplicationController*. You
-can also add modules to individual controllers.
+- `AbstractController::Translation`: Support for the `l` and `t` localization
+ and translation methods.
+- `ActionController::HTTPAuthentication::Basic` (or `Digest` or `Token`): Support
+ for basic, digest or token HTTP authentication.
+- `AbstractController::Layouts`: Support for layouts when rendering.
+- `ActionController::MimeResponds`: Support for `respond_to`.
+- `ActionController::Cookies`: Support for `cookies`, which includes
+ support for signed and encrypted cookies. This requires the cookies middleware.
+
+The best place to add a module is in your `ApplicationController` but you can
+also add modules to individual controllers.
diff --git a/guides/source/caching_with_rails.md b/guides/source/caching_with_rails.md
index 782406659d..b0103c9af4 100644
--- a/guides/source/caching_with_rails.md
+++ b/guides/source/caching_with_rails.md
@@ -1,14 +1,14 @@
**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON http://guides.rubyonrails.org.**
-Caching with Rails: An overview
+Caching with Rails: An Overview
===============================
-This guide will teach you what you need to know about avoiding that expensive round-trip to your database and returning what you need to return to the web clients in the shortest time possible.
+This guide is an introduction to speeding up your Rails app with caching.
After reading this guide, you will know:
-* Page and action caching (moved to separate gems as of Rails 4).
-* Fragment caching.
+* Page and action caching.
+* Fragment and Russian doll caching.
* Alternative cache stores.
* Conditional GET support.
@@ -18,11 +18,14 @@ Basic Caching
-------------
This is an introduction to three types of caching techniques: page, action and
-fragment caching. Rails provides by default fragment caching. In order to use
-page and action caching, you will need to add `actionpack-page_caching` and
+fragment caching. By default Rails provides fragment caching. In order to use
+page and action caching you will need to add `actionpack-page_caching` and
`actionpack-action_caching` to your Gemfile.
-To start playing with caching you'll want to ensure that `config.action_controller.perform_caching` is set to `true` if you're running in development mode. This flag is normally set in the corresponding `config/environments/*.rb` and caching is disabled by default for development and test, and enabled for production.
+By default, caching is only enabled in your production environment. To play
+around with caching locally you'll want to enable caching in your local
+environment by setting `config.action_controller.perform_caching` to `true` in
+the relevant `config/environments/*.rb` file:
```ruby
config.action_controller.perform_caching = true
@@ -30,7 +33,12 @@ config.action_controller.perform_caching = true
### Page Caching
-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.
+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 having to go
+through the entire Rails stack. While this is super fast it can't be applied to
+every situation (such as pages that need authentication). Also, because the
+webserver is serving a file directly from the filesystem you will need to
+implement cache expiration.
INFO: Page Caching has been removed from Rails 4. See the [actionpack-page_caching gem](https://github.com/rails/actionpack-page_caching).
@@ -42,105 +50,102 @@ INFO: Action Caching has been removed from Rails 4. See the [actionpack-action_c
### Fragment Caching
-Life would be perfect if we could get away with caching the entire contents of a page or action and serving it out to the world. Unfortunately, dynamic web applications usually build pages with a variety of components not all of which have the same caching characteristics. In order to address such a dynamically created page where different parts of the page need to be cached and expired differently, Rails provides a mechanism called Fragment Caching.
+Dynamic web applications usually build pages with a variety of components not
+all of which have the same caching characteristics. When different parts of the
+page need to be cached and expired separately you can use Fragment Caching.
Fragment Caching allows a fragment of view logic to be wrapped in a cache block and served out of the cache store when the next request comes in.
-As an example, if you wanted to show all the orders placed on your website in real time and didn't want to cache that part of the page, but did want to cache the part of the page which lists all products available, you could use this piece of code:
+For example, if you wanted to cache each product on a page, you could use this
+code:
```html+erb
-<% Order.find_recent.each do |o| %>
- <%= o.buyer.name %> bought <%= o.product.name %>
-<% end %>
-
-<% cache do %>
- All available products:
- <% Product.all.each do |p| %>
- <%= link_to p.name, product_url(p) %>
+<% @products.each do |product| %>
+ <% cache product do %>
+ <%= render product %>
<% end %>
<% end %>
```
-The cache block in our example will bind to the action that called it and is written out to the same place as the Action Cache, which means that if you want to cache multiple fragments per action, you should provide an `action_suffix` to the cache call:
+When your application receives its first request to this page, Rails will write
+a new cache entry with a unique key. A key looks something like this:
-```html+erb
-<% cache(action: 'recent', action_suffix: 'all_products') do %>
- All available products:
+```
+views/products/1-201505056193031061005000/bea67108094918eeba42cd4a6e786901
```
-and you can expire it using the `expire_fragment` method, like so:
+The number in the middle is the `product_id` followed by the timestamp value in
+the `updated_at` attribute of the product record. Rails uses the timestamp value
+to make sure it is not serving stale data. If the value of `updated_at` has
+changed, a new key will be generated. Then Rails will write a new cache to that
+key, and the old cache written to the old key will never be used again. This is
+called key-based expiration.
-```ruby
-expire_fragment(controller: 'products', action: 'recent', action_suffix: 'all_products')
-```
+Cache fragments will also be expired when the view fragment changes (e.g., the
+HTML in the view changes). The string of characters at the end of the key is a
+template tree digest. It is an md5 hash computed based on the contents of the
+view fragment you are caching. If you change the view fragment, the md5 hash
+will change, expiring the existing file.
+
+TIP: Cache stores like Memcached will automatically delete old cache files.
-If you don't want the cache block to bind to the action that called it, you can also use globally keyed fragments by calling the `cache` method with a key:
+If you want to cache a fragment under certain conditions, you can use
+`cache_if` or `cache_unless`:
```erb
-<% cache('all_available_products') do %>
- All available products:
+<% cache_if admin?, product do %>
+ <%= render product %>
<% end %>
```
-This fragment is then available to all actions in the `ProductsController` using the key and can be expired the same way:
+### Russian Doll Caching
-```ruby
-expire_fragment('all_available_products')
-```
-If you want to avoid expiring the fragment manually, whenever an action updates a product, you can define a helper method:
+You may want to nest cached fragments inside other cached fragments. This is
+called Russian doll caching.
-```ruby
-module ProductsHelper
- def cache_key_for_products
- count = Product.count
- max_updated_at = Product.maximum(:updated_at).try(:utc).try(:to_s, :number)
- "products/all-#{count}-#{max_updated_at}"
- end
-end
-```
+The advantage of Russian doll caching is that if a single product is updated,
+all the other inner fragments can be reused when regenerating the outer
+fragment.
-This method generates a cache key that depends on all products and can be used in the view:
+As explained in the previous section, a cached file will expire if the value of
+`updated_at` changes for a record on which the cached file directly depends.
+However, this will not expire any cache the fragment is nested within.
-```erb
-<% cache(cache_key_for_products) do %>
- All available products:
-<% end %>
-```
-
-If you want to cache a fragment under certain conditions, you can use `cache_if` or `cache_unless`
+For example, take the following view:
```erb
-<% cache_if (condition, cache_key_for_products) do %>
- All available products:
+<% cache product do %>
+ <%= render product.games %>
<% end %>
```
-You can also use an Active Record model as the cache key:
+Which in turn renders this view:
```erb
-<% Product.all.each do |p| %>
- <% cache(p) do %>
- <%= link_to p.name, product_url(p) %>
- <% end %>
+<% cache game %>
+ <%= render game %>
<% end %>
```
-Behind the scenes, a method called `cache_key` will be invoked on the model and it returns a string like `products/23-20130109142513`. The cache key includes the model name, the id and finally the updated_at timestamp. Thus it will automatically generate a new fragment when the product is updated because the key changes.
+If any attribute of game is changed, the `updated_at` value will be set to the
+current time, thereby expiring the cache. However, because `updated_at`
+will not be changed for the product object, that cache will not be expired and
+your app will serve stale data. To fix this, we tie the models together with
+the `touch` method:
-You can also combine the two schemes which is called "Russian Doll Caching":
+```ruby
+class Product < ActiveRecord::Base
+ has_many :games
+end
-```erb
-<% cache(cache_key_for_products) do %>
- All available products:
- <% Product.all.each do |p| %>
- <% cache(p) do %>
- <%= link_to p.name, product_url(p) %>
- <% end %>
- <% end %>
-<% end %>
+class Game < ActiveRecord::Base
+ belongs_to :product, touch: true
+end
```
-It's called "Russian Doll Caching" because it nests multiple fragments. The advantage is that if a single product is updated, all the other inner fragments can be reused when regenerating the outer fragment.
+With `touch` set to true, any action which changes `updated_at` for a game
+record will also change it for the associated product, thereby expiring the
+cache.
### Low-Level Caching
@@ -164,7 +169,10 @@ NOTE: Notice that in this example we used the `cache_key` method, so the resulti
### SQL Caching
-Query caching is a Rails feature that caches the result set returned by each query so that if Rails encounters the same query again for that request, it will use the cached result set as opposed to running the query against the database again.
+Query caching is a Rails feature that caches the result set returned by each
+query. If Rails encounters the same query again for that request, it will use
+the cached result set as opposed to running the query against the database
+again.
For example:
@@ -186,7 +194,10 @@ end
The second time the same query is run against the database, it's not actually going to hit the database. The first time the result is returned from the query it is stored in the query cache (in memory) and the second time it's pulled from memory.
-However, it's important to note that query caches are created at the start of an action and destroyed at the end of that action and thus persist only for the duration of the action. If you'd like to store query results in a more persistent fashion, you can in Rails by using low level caching.
+However, it's important to note that query caches are created at the start of
+an action and destroyed at the end of that action and thus persist only for the
+duration of the action. If you'd like to store query results in a more
+persistent fashion, you can with low level caching.
Cache Stores
------------
@@ -227,13 +238,21 @@ There are some common options used by all cache implementations. These can be pa
### ActiveSupport::Cache::MemoryStore
-This cache store keeps entries in memory in the same Ruby process. The cache store has a bounded size specified by the `:size` option to the initializer (default is 32Mb). When the cache exceeds the allotted size, a cleanup will occur and the least recently used entries will be removed.
+This cache store keeps entries in memory in the same Ruby process. The cache
+store has a bounded size specified by sending the `:size` option to the
+initializer (default is 32Mb). When the cache exceeds the allotted size, a
+cleanup will occur and the least recently used entries will be removed.
```ruby
config.cache_store = :memory_store, { size: 64.megabytes }
```
-If you're running multiple Ruby on Rails server processes (which is the case if you're using mongrel_cluster or Phusion Passenger), then your Rails server process instances won't be able to share cache data with each other. This cache store is not appropriate for large application deployments, but can work well for small, low traffic sites with only a couple of server processes or for development and test environments.
+If you're running multiple Ruby on Rails server processes (which is the case
+if you're using mongrel_cluster or Phusion Passenger), then your Rails server
+process instances won't be able to share cache data with each other. This cache
+store is not appropriate for large application deployments. However, it can
+work well for small, low traffic sites with only a couple of server processes,
+as well as development and test environments.
### ActiveSupport::Cache::FileStore
@@ -243,9 +262,13 @@ This cache store uses the file system to store entries. The path to the director
config.cache_store = :file_store, "/path/to/cache/directory"
```
-With this cache store, multiple server processes on the same host can share a cache. Server processes running on different hosts could share a cache by using a shared file system, but that set up would not be ideal and is not recommended. The cache store is appropriate for low to medium traffic sites that are served off one or two hosts.
+With this cache store, multiple server processes on the same host can share a
+cache. The cache store is appropriate for low to medium traffic sites that are
+served off one or two hosts. Server processes running on different hosts could
+share a cache by using a shared file system, but that setup is not recommended.
-Note that the cache will grow until the disk is full unless you periodically clear out old entries.
+As the cache will grow until the disk is full, it is recommended to
+periodically clear out old entries.
This is the default cache store implementation.
@@ -253,7 +276,10 @@ This is the default cache store implementation.
This cache store uses Danga's `memcached` server to provide a centralized cache for your application. Rails uses the bundled `dalli` gem by default. This is currently the most popular cache store for production websites. It can be used to provide a single, shared cache cluster with very high performance and redundancy.
-When initializing the cache, you need to specify the addresses for all memcached servers in your cluster. If none is specified, it will assume memcached is running on the local host on the default port, but this is not an ideal set up for larger sites.
+When initializing the cache, you need to specify the addresses for all
+memcached servers in your cluster. If none are specified, it will assume
+memcached is running on localhost on the default port, but this is not an ideal
+setup for larger sites.
The `write` and `fetch` methods on this cache accept two additional options that take advantage of features specific to memcached. You can specify `:raw` to send a value directly to the server with no serialization. The value must be a string or number. You can use memcached direct operations like `increment` and `decrement` only on raw values. You can also specify `:unless_exist` if you don't want memcached to overwrite an existing entry.
@@ -383,3 +409,9 @@ class ProductsController < ApplicationController
end
end
```
+
+References
+----------
+
+* [DHH's article on key-based expiration](https://signalvnoise.com/posts/3113-how-key-based-cache-expiration-works)
+* [Ryan Bates' Railscast on cache digests](http://railscasts.com/episodes/387-cache-digests)
diff --git a/guides/source/development_dependencies_install.md b/guides/source/development_dependencies_install.md
index 295e48f493..3c670a1221 100644
--- a/guides/source/development_dependencies_install.md
+++ b/guides/source/development_dependencies_install.md
@@ -9,7 +9,7 @@ After reading this guide, you will know:
* How to set up your machine for Rails development
* How to run specific groups of unit tests from the Rails test suite
-* How the ActiveRecord portion of the Rails test suite operates
+* How the Active Record portion of the Rails test suite operates
--------------------------------------------------------------------------------
@@ -60,7 +60,7 @@ In Ubuntu you're done with just:
$ sudo apt-get install sqlite3 libsqlite3-dev
```
-And if you are on Fedora or CentOS, you're done with
+If you are on Fedora or CentOS, you're done with
```bash
$ sudo yum install sqlite3 sqlite3-devel
@@ -213,7 +213,7 @@ FreeBSD users will have to run the following:
```bash
# pkg install mysql56-client mysql56-server
-# pkg install postgresql93-client postgresql93-server
+# pkg install postgresql94-client postgresql94-server
```
Or install them through ports (they are located under the `databases` folder).
diff --git a/guides/source/i18n.md b/guides/source/i18n.md
index 9f0ed1a85b..31682464ee 100644
--- a/guides/source/i18n.md
+++ b/guides/source/i18n.md
@@ -216,8 +216,8 @@ We can include something like this in our `ApplicationController` then:
```ruby
# app/controllers/application_controller.rb
-def default_url_options(options = {})
- { locale: I18n.locale }.merge options
+def default_url_options
+ { locale: I18n.locale }
end
```
@@ -225,7 +225,7 @@ Every helper method dependent on `url_for` (e.g. helpers for named routes like `
You may be satisfied with this. It does impact the readability of URLs, though, when the locale "hangs" at the end of every URL in your application. Moreover, from the architectural standpoint, locale is usually hierarchically above the other parts of the application domain: and URLs should reflect this.
-You probably want URLs to look like this: `www.example.com/en/books` (which loads the English locale) and `www.example.com/nl/books` (which loads the Dutch locale). This is achievable with the "over-riding `default_url_options`" strategy from above: you just have to set up your routes with [`scoping`](http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Scoping.html) option in this way:
+You probably want URLs to look like this: `http://www.example.com/en/books` (which loads the English locale) and `http://www.example.com/nl/books` (which loads the Dutch locale). This is achievable with the "over-riding `default_url_options`" strategy from above: you just have to set up your routes with [`scope`](http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Scoping.html):
```ruby
# config/routes.rb
@@ -234,7 +234,9 @@ scope "/:locale" do
end
```
-Now, when you call the `books_path` method you should get `"/en/books"` (for the default locale). An URL like `http://localhost:3001/nl/books` should load the Dutch locale, then, and following calls to `books_path` should return `"/nl/books"` (because the locale changed).
+Now, when you call the `books_path` method you should get `"/en/books"` (for the default locale). A URL like `http://localhost:3001/nl/books` should load the Dutch locale, then, and following calls to `books_path` should return `"/nl/books"` (because the locale changed).
+
+WARNING. Since the return value of `default_url_options` is cached per request, the URLs in a locale selector cannot be generated invoking helpers in a loop that sets the corresponding `I18n.locale` in each iteration. Instead, leave `I18n.locale` untouched, and pass an explicit `:locale` option to the helper, or edit `request.original_fullpath`.
If you don't want to force the use of a locale in your routes you can use an optional path scope (denoted by the parentheses) like so:
diff --git a/guides/source/rails_on_rack.md b/guides/source/rails_on_rack.md
index 993cd5ac44..117017af90 100644
--- a/guides/source/rails_on_rack.md
+++ b/guides/source/rails_on_rack.md
@@ -68,11 +68,10 @@ def middleware
end
```
-`Rails::Rack::Debugger` is primarily useful only in the development environment. The following table explains the usage of the loaded middlewares:
+The following table explains the usage of the loaded middlewares:
| Middleware | Purpose |
| ----------------------- | --------------------------------------------------------------------------------- |
-| `Rails::Rack::Debugger` | Starts Debugger |
| `Rack::ContentLength` | Counts the number of bytes in the response and set the HTTP Content-Length header |
### `rackup`
@@ -83,7 +82,6 @@ To use `rackup` instead of Rails' `rails server`, you can put the following insi
# Rails.root/config.ru
require ::File.expand_path('../config/environment', __FILE__)
-use Rails::Rack::Debugger
use Rack::ContentLength
run Rails.application
```
diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md
index ca07ff349c..c099ae2ec5 100644
--- a/railties/CHANGELOG.md
+++ b/railties/CHANGELOG.md
@@ -1,3 +1,8 @@
+* Remove ContentLength middleware from the defaults. If you want it, just
+ add it as a middleware in your config.
+
+ *Egg McMuffin*
+
* Make it possible to customize the executable inside rerun snippets.
*Yves Senn*
diff --git a/railties/lib/rails/commands/server.rb b/railties/lib/rails/commands/server.rb
index 546d3725d8..c1bd4072ac 100644
--- a/railties/lib/rails/commands/server.rb
+++ b/railties/lib/rails/commands/server.rb
@@ -78,7 +78,6 @@ module Rails
def middleware
middlewares = []
- middlewares << [::Rack::ContentLength]
# FIXME: add Rack::Lock in the case people are using webrick.
# This is to remain backwards compatible for those who are
diff --git a/railties/lib/rails/generators/named_base.rb b/railties/lib/rails/generators/named_base.rb
index 01a8e2e9b4..7b527831b0 100644
--- a/railties/lib/rails/generators/named_base.rb
+++ b/railties/lib/rails/generators/named_base.rb
@@ -18,8 +18,8 @@ module Rails
parse_attributes! if respond_to?(:attributes)
end
- # Defines the template that would be used for the migration file.
- # The arguments include the source template file, the migration filename etc.
+ # Overrides <tt>Thor::Actions#template</tt> so it can tell if
+ # a template is currently being created.
no_tasks do
def template(source, *args, &block)
inside_template do
diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile
index 606f1d4f96..b083381255 100644
--- a/railties/lib/rails/generators/rails/app/templates/Gemfile
+++ b/railties/lib/rails/generators/rails/app/templates/Gemfile
@@ -23,7 +23,7 @@ source 'https://rubygems.org'
<%- if options.api? -%>
# Use ActiveModelSerializers to serialize JSON responses
-gem 'active_model_serializers', '~> 0.10.0.rc1'
+gem 'active_model_serializers', '~> 0.10.0.rc2'
# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible
# gem 'rack-cors'
@@ -38,7 +38,7 @@ end
group :development do
# Access an IRB console on exception pages or by using <%%= console %> in views
<%- if options.dev? || options.edge? -%>
- gem 'web-console', github: "rails/web-console"
+ gem 'web-console', github: 'rails/web-console'
<%- else -%>
gem 'web-console', '~> 2.0'
<%- end -%>
diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb
index af1c05cab1..fc05127fb5 100644
--- a/railties/test/generators/app_generator_test.rb
+++ b/railties/test/generators/app_generator_test.rb
@@ -517,7 +517,7 @@ class AppGeneratorTest < Rails::Generators::TestCase
run_generator [destination_root, "--dev"]
assert_file "Gemfile" do |content|
- assert_match(/gem 'web-console',\s+github: "rails\/web-console"/, content)
+ assert_match(/gem 'web-console',\s+github: 'rails\/web-console'/, content)
assert_no_match(/gem 'web-console', '~> 2.0'/, content)
end
end
@@ -526,7 +526,7 @@ class AppGeneratorTest < Rails::Generators::TestCase
run_generator [destination_root, "--edge"]
assert_file "Gemfile" do |content|
- assert_match(/gem 'web-console',\s+github: "rails\/web-console"/, content)
+ assert_match(/gem 'web-console',\s+github: 'rails\/web-console'/, content)
assert_no_match(/gem 'web-console', '~> 2.0'/, content)
end
end