aboutsummaryrefslogtreecommitdiffstats
path: root/actionpack/lib
diff options
context:
space:
mode:
Diffstat (limited to 'actionpack/lib')
-rw-r--r--actionpack/lib/abstract_controller.rb5
-rw-r--r--actionpack/lib/abstract_controller/collector.rb10
-rw-r--r--actionpack/lib/abstract_controller/helpers.rb15
-rw-r--r--actionpack/lib/abstract_controller/rendering.rb16
-rw-r--r--actionpack/lib/abstract_controller/translation.rb8
-rw-r--r--actionpack/lib/action_controller.rb4
-rw-r--r--actionpack/lib/action_controller/caching.rb3
-rw-r--r--actionpack/lib/action_controller/caching/fragments.rb44
-rw-r--r--actionpack/lib/action_controller/caching/pages.rb2
-rw-r--r--actionpack/lib/action_controller/caching/sweeping.rb15
-rw-r--r--actionpack/lib/action_controller/log_subscriber.rb1
-rw-r--r--actionpack/lib/action_controller/metal.rb4
-rw-r--r--actionpack/lib/action_controller/metal/data_streaming.rb4
-rw-r--r--actionpack/lib/action_controller/metal/flash.rb33
-rw-r--r--actionpack/lib/action_controller/metal/force_ssl.rb24
-rw-r--r--actionpack/lib/action_controller/metal/head.rb8
-rw-r--r--actionpack/lib/action_controller/metal/helpers.rb5
-rw-r--r--actionpack/lib/action_controller/metal/hide_actions.rb1
-rw-r--r--actionpack/lib/action_controller/metal/http_authentication.rb39
-rw-r--r--actionpack/lib/action_controller/metal/live.rb141
-rw-r--r--actionpack/lib/action_controller/metal/mime_responds.rb9
-rw-r--r--actionpack/lib/action_controller/metal/params_wrapper.rb1
-rw-r--r--actionpack/lib/action_controller/metal/rack_delegation.rb12
-rw-r--r--actionpack/lib/action_controller/metal/renderers.rb2
-rw-r--r--actionpack/lib/action_controller/metal/request_forgery_protection.rb15
-rw-r--r--actionpack/lib/action_controller/metal/responder.rb2
-rw-r--r--actionpack/lib/action_controller/metal/streaming.rb3
-rw-r--r--actionpack/lib/action_controller/metal/testing.rb31
-rw-r--r--actionpack/lib/action_controller/metal/url_for.rb12
-rw-r--r--actionpack/lib/action_controller/model_naming.rb12
-rw-r--r--actionpack/lib/action_controller/record_identifier.rb8
-rw-r--r--actionpack/lib/action_controller/test_case.rb104
-rw-r--r--actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb1
-rw-r--r--actionpack/lib/action_dispatch.rb6
-rw-r--r--actionpack/lib/action_dispatch/http/cache.rb49
-rw-r--r--actionpack/lib/action_dispatch/http/filter_parameters.rb1
-rw-r--r--actionpack/lib/action_dispatch/http/mime_negotiation.rb21
-rw-r--r--actionpack/lib/action_dispatch/http/mime_type.rb23
-rw-r--r--actionpack/lib/action_dispatch/http/parameters.rb5
-rw-r--r--actionpack/lib/action_dispatch/http/request.rb36
-rw-r--r--actionpack/lib/action_dispatch/http/response.rb122
-rw-r--r--actionpack/lib/action_dispatch/http/url.rb6
-rw-r--r--actionpack/lib/action_dispatch/middleware/callbacks.rb1
-rw-r--r--actionpack/lib/action_dispatch/middleware/cookies.rb2
-rw-r--r--actionpack/lib/action_dispatch/middleware/debug_exceptions.rb18
-rw-r--r--actionpack/lib/action_dispatch/middleware/head.rb18
-rw-r--r--actionpack/lib/action_dispatch/middleware/public_exceptions.rb45
-rw-r--r--actionpack/lib/action_dispatch/middleware/request_id.rb1
-rw-r--r--actionpack/lib/action_dispatch/middleware/session/abstract_store.rb1
-rw-r--r--actionpack/lib/action_dispatch/middleware/session/cookie_store.rb1
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.erb10
-rw-r--r--actionpack/lib/action_dispatch/railtie.rb7
-rw-r--r--actionpack/lib/action_dispatch/routing.rb7
-rw-r--r--actionpack/lib/action_dispatch/routing/inspector.rb121
-rw-r--r--actionpack/lib/action_dispatch/routing/mapper.rb125
-rw-r--r--actionpack/lib/action_dispatch/routing/polymorphic_routes.rb14
-rw-r--r--actionpack/lib/action_dispatch/routing/route_set.rb72
-rw-r--r--actionpack/lib/action_dispatch/routing/url_for.rb2
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/response.rb1
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/routing.rb11
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/selector.rb1
-rw-r--r--actionpack/lib/action_dispatch/testing/integration.rb10
-rw-r--r--actionpack/lib/action_dispatch/testing/test_request.rb9
-rw-r--r--actionpack/lib/action_view.rb5
-rw-r--r--actionpack/lib/action_view/asset_paths.rb8
-rw-r--r--actionpack/lib/action_view/base.rb19
-rw-r--r--actionpack/lib/action_view/context.rb4
-rw-r--r--actionpack/lib/action_view/helpers/active_model_helper.rb1
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helper.rb86
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb3
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb18
-rw-r--r--actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb5
-rw-r--r--actionpack/lib/action_view/helpers/cache_helper.rb32
-rw-r--r--actionpack/lib/action_view/helpers/capture_helper.rb11
-rw-r--r--actionpack/lib/action_view/helpers/controller_helper.rb6
-rw-r--r--actionpack/lib/action_view/helpers/date_helper.rb12
-rw-r--r--actionpack/lib/action_view/helpers/debug_helper.rb8
-rw-r--r--actionpack/lib/action_view/helpers/form_helper.rb66
-rw-r--r--actionpack/lib/action_view/helpers/form_options_helper.rb11
-rw-r--r--actionpack/lib/action_view/helpers/form_tag_helper.rb62
-rw-r--r--actionpack/lib/action_view/helpers/javascript_helper.rb40
-rw-r--r--actionpack/lib/action_view/helpers/number_helper.rb228
-rw-r--r--actionpack/lib/action_view/helpers/sanitize_helper.rb2
-rw-r--r--actionpack/lib/action_view/helpers/tag_helper.rb1
-rw-r--r--actionpack/lib/action_view/helpers/tags/base.rb4
-rw-r--r--actionpack/lib/action_view/helpers/text_helper.rb35
-rw-r--r--actionpack/lib/action_view/helpers/url_helper.rb139
-rw-r--r--actionpack/lib/action_view/locale/en.yml98
-rw-r--r--actionpack/lib/action_view/lookup_context.rb10
-rw-r--r--actionpack/lib/action_view/renderer/abstract_renderer.rb9
-rw-r--r--actionpack/lib/action_view/renderer/partial_renderer.rb34
-rw-r--r--actionpack/lib/action_view/renderer/template_renderer.rb11
-rw-r--r--actionpack/lib/action_view/template.rb1
-rw-r--r--actionpack/lib/action_view/template/error.rb4
-rw-r--r--actionpack/lib/action_view/template/handlers/erb.rb1
-rw-r--r--actionpack/lib/action_view/template/resolver.rb105
-rw-r--r--actionpack/lib/action_view/template/text.rb10
-rw-r--r--actionpack/lib/action_view/test_case.rb5
98 files changed, 1535 insertions, 899 deletions
diff --git a/actionpack/lib/abstract_controller.rb b/actionpack/lib/abstract_controller.rb
index b95ea5f0b2..867a7954e0 100644
--- a/actionpack/lib/abstract_controller.rb
+++ b/actionpack/lib/abstract_controller.rb
@@ -1,9 +1,6 @@
require 'action_pack'
-require 'active_support/concern'
-require 'active_support/dependencies/autoload'
-require 'active_support/core_ext/class/attribute'
+require 'active_support/rails'
require 'active_support/core_ext/module/attr_internal'
-require 'active_support/core_ext/module/delegation'
require 'active_support/core_ext/module/anonymous'
require 'active_support/i18n'
diff --git a/actionpack/lib/abstract_controller/collector.rb b/actionpack/lib/abstract_controller/collector.rb
index 81fb514770..09b9e7ddf0 100644
--- a/actionpack/lib/abstract_controller/collector.rb
+++ b/actionpack/lib/abstract_controller/collector.rb
@@ -4,7 +4,7 @@ module AbstractController
module Collector
def self.generate_method_for_mime(mime)
sym = mime.is_a?(Symbol) ? mime : mime.to_sym
- const = sym.to_s.upcase
+ const = sym.upcase
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{sym}(*args, &block) # def html(*args, &block)
custom(Mime::#{const}, *args, &block) # custom(Mime::HTML, *args, &block)
@@ -16,10 +16,14 @@ module AbstractController
generate_method_for_mime(mime)
end
+ Mime::Type.register_callback do |mime|
+ generate_method_for_mime(mime) unless self.instance_methods.include?(mime.to_sym)
+ end
+
protected
def method_missing(symbol, &block)
- mime_constant = Mime.const_get(symbol.to_s.upcase)
+ mime_constant = Mime.const_get(symbol.upcase)
if Mime::SET.include?(mime_constant)
AbstractController::Collector.generate_method_for_mime(mime_constant)
@@ -29,4 +33,4 @@ module AbstractController
end
end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/abstract_controller/helpers.rb b/actionpack/lib/abstract_controller/helpers.rb
index 4e0672d590..d63d17f4c5 100644
--- a/actionpack/lib/abstract_controller/helpers.rb
+++ b/actionpack/lib/abstract_controller/helpers.rb
@@ -132,7 +132,11 @@ module AbstractController
case arg
when String, Symbol
file_name = "#{arg.to_s.underscore}_helper"
- require_dependency(file_name, "Missing helper file helpers/%s.rb")
+ begin
+ require_dependency(file_name)
+ rescue LoadError => e
+ raise MissingHelperError.new(e, file_name)
+ end
file_name.camelize.constantize
when Module
arg
@@ -142,6 +146,15 @@ module AbstractController
end
end
+ class MissingHelperError < LoadError
+ def initialize(error, path)
+ @error = error
+ @path = "helpers/#{path}.rb"
+ set_backtrace error.backtrace
+ super("Missing helper file helpers/%s.rb" % path)
+ end
+ end
+
private
# Makes all the (instance) methods in the helper module available to templates
# rendered through this controller.
diff --git a/actionpack/lib/abstract_controller/rendering.rb b/actionpack/lib/abstract_controller/rendering.rb
index 7d73c6af8d..3da2834af0 100644
--- a/actionpack/lib/abstract_controller/rendering.rb
+++ b/actionpack/lib/abstract_controller/rendering.rb
@@ -49,9 +49,19 @@ module AbstractController
module ClassMethods
def view_context_class
@view_context_class ||= begin
- routes = _routes if respond_to?(:_routes)
- helpers = _helpers if respond_to?(:_helpers)
- ActionView::Base.prepare(routes, helpers)
+ routes = respond_to?(:_routes) && _routes
+ helpers = respond_to?(:_helpers) && _helpers
+
+ Class.new(ActionView::Base) do
+ if routes
+ include routes.url_helpers
+ include routes.mounted_helpers
+ end
+
+ if helpers
+ include helpers
+ end
+ end
end
end
end
diff --git a/actionpack/lib/abstract_controller/translation.rb b/actionpack/lib/abstract_controller/translation.rb
index 6d68cf4944..b6c484d188 100644
--- a/actionpack/lib/abstract_controller/translation.rb
+++ b/actionpack/lib/abstract_controller/translation.rb
@@ -1,6 +1,12 @@
module AbstractController
module Translation
def translate(*args)
+ key = args.first
+ if key.is_a?(String) && (key[0] == '.')
+ key = "#{ controller_path.gsub('/', '.') }.#{ action_name }#{ key }"
+ args[0] = key
+ end
+
I18n.translate(*args)
end
alias :t :translate
@@ -10,4 +16,4 @@ module AbstractController
end
alias :l :localize
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/action_controller.rb b/actionpack/lib/action_controller.rb
index 7c10fcbb8a..ceb90f8cee 100644
--- a/actionpack/lib/action_controller.rb
+++ b/actionpack/lib/action_controller.rb
@@ -1,5 +1,7 @@
+require 'active_support/rails'
require 'abstract_controller'
require 'action_dispatch'
+require 'action_controller/metal/live'
module ActionController
extend ActiveSupport::Autoload
@@ -53,11 +55,9 @@ require 'action_view'
require 'action_controller/vendor/html-scanner'
# Common Active Support usage in Action Controller
-require 'active_support/concern'
require 'active_support/core_ext/class/attribute_accessors'
require 'active_support/core_ext/load_error'
require 'active_support/core_ext/module/attr_internal'
-require 'active_support/core_ext/module/delegation'
require 'active_support/core_ext/name_error'
require 'active_support/core_ext/uri'
require 'active_support/inflector'
diff --git a/actionpack/lib/action_controller/caching.rb b/actionpack/lib/action_controller/caching.rb
index 112573a38d..9118806059 100644
--- a/actionpack/lib/action_controller/caching.rb
+++ b/actionpack/lib/action_controller/caching.rb
@@ -55,6 +55,9 @@ module ActionController #:nodoc:
end
end
+ include RackDelegation
+ include AbstractController::Callbacks
+
include ConfigMethods
include Pages, Actions, Fragments
include Sweeping if defined?(ActiveRecord)
diff --git a/actionpack/lib/action_controller/caching/fragments.rb b/actionpack/lib/action_controller/caching/fragments.rb
index abeb49d16f..9c77b0ccf4 100644
--- a/actionpack/lib/action_controller/caching/fragments.rb
+++ b/actionpack/lib/action_controller/caching/fragments.rb
@@ -5,48 +5,18 @@ module ActionController #:nodoc:
# useful when certain elements of an action change frequently or
# depend on complicated state while other parts rarely change or
# can be shared amongst multiple parties. The caching is done using
- # the <tt>cache</tt> helper available in the Action View. A
- # template with fragment caching might look like:
+ # the <tt>cache</tt> helper available in the Action View. See
+ # ActionView::Helpers::CacheHelper for more information.
#
- # <b>Hello <%= @name %></b>
+ # While it's strongly recommended that you use key-based cache
+ # expiration (see links in CacheHelper for more information),
+ # it is also possible to manually expire caches. For example:
#
- # <% cache do %>
- # All the topics in the system:
- # <%= render :partial => "topic", :collection => Topic.all %>
- # <% end %>
- #
- # This cache will bind the name of the action that called it, so if
- # this code was part of the view for the topics/list action, you
- # would be able to invalidate it using:
- #
- # expire_fragment(:controller => "topics", :action => "list")
- #
- # This default behavior is limited if you need to cache multiple
- # fragments per action or if the action itself is cached using
- # <tt>caches_action</tt>. To remedy this, there is an option to
- # qualify the name of the cached fragment by using the
- # <tt>:action_suffix</tt> option:
- #
- # <% cache(:action => "list", :action_suffix => "all_topics") do %>
- #
- # That would result in a name such as
- # <tt>/topics/list/all_topics</tt>, avoiding conflicts with the
- # action cache and with any fragments that use a different suffix.
- # Note that the URL doesn't have to really exist or be callable
- # - the url_for system is just used to generate unique cache names
- # that we can refer to when we need to expire the cache.
- #
- # The expiration call for this example is:
- #
- # expire_fragment(:controller => "topics",
- # :action => "list",
- # :action_suffix => "all_topics")
+ # expire_fragment("name_of_cache")
module Fragments
# Given a key (as described in <tt>expire_fragment</tt>), returns
# a key suitable for use in reading, writing, or expiring a
- # cached fragment. If the key is a hash, the generated key is the
- # return value of url_for on that hash (without the protocol).
- # All keys are prefixed with <tt>views/</tt> and uses
+ # cached fragment. All keys are prefixed with <tt>views/</tt> and uses
# ActiveSupport::Cache.expand_cache_key for the expansion.
def fragment_cache_key(key)
ActiveSupport::Cache.expand_cache_key(key.is_a?(Hash) ? url_for(key).split("://").last : key, :views)
diff --git a/actionpack/lib/action_controller/caching/pages.rb b/actionpack/lib/action_controller/caching/pages.rb
index dd4eddbe9a..73b8cd383c 100644
--- a/actionpack/lib/action_controller/caching/pages.rb
+++ b/actionpack/lib/action_controller/caching/pages.rb
@@ -110,7 +110,7 @@ module ActionController #:nodoc:
gzip_level = options.fetch(:gzip, page_cache_compression)
gzip_level = case gzip_level
when Symbol
- Zlib.const_get(gzip_level.to_s.upcase)
+ Zlib.const_get(gzip_level.upcase)
when Fixnum
gzip_level
when false
diff --git a/actionpack/lib/action_controller/caching/sweeping.rb b/actionpack/lib/action_controller/caching/sweeping.rb
index cc1fa23935..73291ce083 100644
--- a/actionpack/lib/action_controller/caching/sweeping.rb
+++ b/actionpack/lib/action_controller/caching/sweeping.rb
@@ -68,8 +68,14 @@ module ActionController #:nodoc:
def after(controller)
self.controller = controller
callback(:after) if controller.perform_caching
- # Clean up, so that the controller can be collected after this request
- self.controller = nil
+ end
+
+ def around(controller)
+ before(controller)
+ yield
+ after(controller)
+ ensure
+ clean_up
end
protected
@@ -84,6 +90,11 @@ module ActionController #:nodoc:
end
private
+ def clean_up
+ # Clean up, so that the controller can be collected after this request
+ self.controller = nil
+ end
+
def callback(timing)
controller_callback_method_name = "#{timing}_#{controller.controller_name.underscore}"
action_callback_method_name = "#{controller_callback_method_name}_#{controller.action_name}"
diff --git a/actionpack/lib/action_controller/log_subscriber.rb b/actionpack/lib/action_controller/log_subscriber.rb
index 0fb419f941..a7c0e971e7 100644
--- a/actionpack/lib/action_controller/log_subscriber.rb
+++ b/actionpack/lib/action_controller/log_subscriber.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
module ActionController
class LogSubscriber < ActiveSupport::LogSubscriber
diff --git a/actionpack/lib/action_controller/metal.rb b/actionpack/lib/action_controller/metal.rb
index 92433ab462..b38f990efa 100644
--- a/actionpack/lib/action_controller/metal.rb
+++ b/actionpack/lib/action_controller/metal.rb
@@ -1,5 +1,3 @@
-require 'active_support/core_ext/class/attribute'
-require 'active_support/core_ext/object/blank'
require 'action_dispatch/middleware/stack'
module ActionController
@@ -187,7 +185,7 @@ module ActionController
end
def performed?
- !!response_body
+ response_body || (response && response.committed?)
end
def dispatch(name, request) #:nodoc:
diff --git a/actionpack/lib/action_controller/metal/data_streaming.rb b/actionpack/lib/action_controller/metal/data_streaming.rb
index 379ff97048..5422cb93c4 100644
--- a/actionpack/lib/action_controller/metal/data_streaming.rb
+++ b/actionpack/lib/action_controller/metal/data_streaming.rb
@@ -76,8 +76,8 @@ module ActionController #:nodoc:
end
# Avoid having to pass an open file handle as the response body.
- # Rack::Sendfile will usually intercepts the response and just uses
- # the path directly, so no reason to open the file.
+ # Rack::Sendfile will usually intercept the response and uses
+ # the path directly, so there is no reason to open the file.
class FileBody #:nodoc:
attr_reader :to_path
diff --git a/actionpack/lib/action_controller/metal/flash.rb b/actionpack/lib/action_controller/metal/flash.rb
index bd768b634e..b078beb675 100644
--- a/actionpack/lib/action_controller/metal/flash.rb
+++ b/actionpack/lib/action_controller/metal/flash.rb
@@ -3,19 +3,34 @@ module ActionController #:nodoc:
extend ActiveSupport::Concern
included do
- delegate :flash, :to => :request
- delegate :alert, :notice, :to => "request.flash"
- helper_method :alert, :notice
+ class_attribute :_flash_types, instance_accessor: false
+ self._flash_types = []
+
+ delegate :flash, to: :request
+ add_flash_types(:alert, :notice)
end
- protected
- def redirect_to(options = {}, response_status_and_flash = {}) #:doc:
- if alert = response_status_and_flash.delete(:alert)
- flash[:alert] = alert
+ module ClassMethods
+ def add_flash_types(*types)
+ types.each do |type|
+ next if _flash_types.include?(type)
+
+ define_method(type) do
+ request.flash[type]
+ end
+ helper_method type
+
+ _flash_types << type
end
+ end
+ end
- if notice = response_status_and_flash.delete(:notice)
- flash[:notice] = notice
+ protected
+ def redirect_to(options = {}, response_status_and_flash = {}) #:doc:
+ self.class._flash_types.each do |flash_type|
+ if type = response_status_and_flash.delete(flash_type)
+ flash[flash_type] = type
+ end
end
if other_flashes = response_status_and_flash.delete(:flash)
diff --git a/actionpack/lib/action_controller/metal/force_ssl.rb b/actionpack/lib/action_controller/metal/force_ssl.rb
index ac12cbb625..e905a3cf1d 100644
--- a/actionpack/lib/action_controller/metal/force_ssl.rb
+++ b/actionpack/lib/action_controller/metal/force_ssl.rb
@@ -32,7 +32,7 @@ module ActionController
# ==== Options
# * <tt>host</tt> - Redirect to a different host name
# * <tt>only</tt> - The callback should be run only for this action
- # * <tt>except<tt> - The callback should be run for all actions except this action
+ # * <tt>except</tt> - The callback should be run for all actions except this action
# * <tt>if</tt> - A symbol naming an instance method or a proc; the callback
# will be called only when it returns a true value.
# * <tt>unless</tt> - A symbol naming an instance method or a proc; the callback
@@ -40,15 +40,23 @@ module ActionController
def force_ssl(options = {})
host = options.delete(:host)
before_filter(options) do
- unless request.ssl?
- redirect_options = {:protocol => 'https://', :status => :moved_permanently}
- redirect_options.merge!(:host => host) if host
- redirect_options.merge!(:params => request.query_parameters)
- flash.keep if respond_to?(:flash)
- redirect_to redirect_options
- end
+ force_ssl_redirect(host)
end
end
end
+
+ # Redirect the existing request to use the HTTPS protocol.
+ #
+ # ==== Parameters
+ # * <tt>host</tt> - Redirect to a different host name
+ def force_ssl_redirect(host = nil)
+ unless request.ssl?
+ redirect_options = {:protocol => 'https://', :status => :moved_permanently}
+ redirect_options.merge!(:host => host) if host
+ redirect_options.merge!(:params => request.query_parameters)
+ flash.keep if respond_to?(:flash)
+ redirect_to redirect_options
+ end
+ end
end
end
diff --git a/actionpack/lib/action_controller/metal/head.rb b/actionpack/lib/action_controller/metal/head.rb
index 2fcd933d32..747e1273be 100644
--- a/actionpack/lib/action_controller/metal/head.rb
+++ b/actionpack/lib/action_controller/metal/head.rb
@@ -29,19 +29,19 @@ module ActionController
self.status = status
self.location = url_for(location) if location
- if include_content_headers?(self.status)
+ if include_content?(self.status)
self.content_type = content_type || (Mime[formats.first] if formats)
+ self.response_body = " "
else
headers.delete('Content-Type')
headers.delete('Content-Length')
+ self.response_body = ""
end
-
- self.response_body = " "
end
private
# :nodoc:
- def include_content_headers?(status)
+ def include_content?(status)
case status
when 100..199
false
diff --git a/actionpack/lib/action_controller/metal/helpers.rb b/actionpack/lib/action_controller/metal/helpers.rb
index 86d061e3b7..d2cbbd3330 100644
--- a/actionpack/lib/action_controller/metal/helpers.rb
+++ b/actionpack/lib/action_controller/metal/helpers.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/class/attribute'
module ActionController
# The \Rails framework provides a large number of helpers for working with assets, dates, forms,
@@ -95,9 +94,9 @@ module ActionController
helpers = []
Array(path).each do |_path|
extract = /^#{Regexp.quote(_path.to_s)}\/?(.*)_helper.rb$/
- helpers += Dir["#{_path}/**/*_helper.rb"].map { |file| file.sub(extract, '\1') }
+ names = Dir["#{_path}/**/*_helper.rb"].map { |file| file.sub(extract, '\1') }
+ helpers += names.sort
end
- helpers.sort!
helpers.uniq!
helpers
end
diff --git a/actionpack/lib/action_controller/metal/hide_actions.rb b/actionpack/lib/action_controller/metal/hide_actions.rb
index b55c4643be..420b22cf56 100644
--- a/actionpack/lib/action_controller/metal/hide_actions.rb
+++ b/actionpack/lib/action_controller/metal/hide_actions.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/class/attribute'
module ActionController
# Adds the ability to prevent public methods on a controller to be called as actions.
diff --git a/actionpack/lib/action_controller/metal/http_authentication.rb b/actionpack/lib/action_controller/metal/http_authentication.rb
index 57bb0e2a32..03b8d8db1a 100644
--- a/actionpack/lib/action_controller/metal/http_authentication.rb
+++ b/actionpack/lib/action_controller/metal/http_authentication.rb
@@ -1,5 +1,4 @@
require 'base64'
-require 'active_support/core_ext/object/blank'
module ActionController
# Makes it dead easy to do HTTP Basic, Digest and Token authentication.
@@ -194,7 +193,7 @@ module ActionController
return false unless password
method = request.env['rack.methodoverride.original_method'] || request.env['REQUEST_METHOD']
- uri = credentials[:uri][0,1] == '/' ? request.original_fullpath : request.original_url
+ uri = credentials[:uri]
[true, false].any? do |trailing_question_mark|
[true, false].any? do |password_is_ha1|
@@ -229,9 +228,9 @@ module ActionController
end
def decode_credentials(header)
- Hash[header.to_s.gsub(/^Digest\s+/,'').split(',').map do |pair|
+ HashWithIndifferentAccess[header.to_s.gsub(/^Digest\s+/,'').split(',').map do |pair|
key, value = pair.split('=', 2)
- [key.strip.to_sym, value.to_s.gsub(/^"|"$/,'').delete('\'')]
+ [key.strip, value.to_s.gsub(/^"|"$/,'').delete('\'')]
end]
end
@@ -372,7 +371,7 @@ module ActionController
# def test_access_granted_from_xml
# get(
# "/notes/1.xml", nil,
- # :authorization => ActionController::HttpAuthentication::Token.encode_credentials(users(:dhh).token)
+ # 'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Token.encode_credentials(users(:dhh).token)
# )
#
# assert_equal 200, status
@@ -401,16 +400,20 @@ module ActionController
end
end
- # If token Authorization header is present, call the login procedure with
- # the present token and options.
+ # If token Authorization header is present, call the login
+ # procedure with the present token and options.
#
- # controller - ActionController::Base instance for the current request.
- # login_procedure - Proc to call if a token is present. The Proc should
- # take 2 arguments:
- # authenticate(controller) { |token, options| ... }
+ # [controller]
+ # ActionController::Base instance for the current request.
#
- # Returns the return value of `&login_procedure` if a token is found.
- # Returns nil if no token is found.
+ # [login_procedure]
+ # Proc to call if a token is present. The Proc should take two arguments:
+ #
+ # authenticate(controller) { |token, options| ... }
+ #
+ # Returns the return value of <tt>login_procedure</tt> if a
+ # token is found. Returns <tt>nil</tt> if no token is found.
+
def authenticate(controller, &login_procedure)
token, options = token_and_options(controller.request)
unless token.blank?
@@ -432,10 +435,12 @@ module ActionController
values = Hash[$1.split(',').map do |value|
value.strip! # remove any spaces between commas and values
key, value = value.split(/\=\"?/) # split key=value pairs
- value.chomp!('"') # chomp trailing " in value
- value.gsub!(/\\\"/, '"') # unescape remaining quotes
- [key, value]
- end]
+ if value
+ value.chomp!('"') # chomp trailing " in value
+ value.gsub!(/\\\"/, '"') # unescape remaining quotes
+ [key, value]
+ end
+ end.compact]
[values.delete("token"), values.with_indifferent_access]
end
end
diff --git a/actionpack/lib/action_controller/metal/live.rb b/actionpack/lib/action_controller/metal/live.rb
new file mode 100644
index 0000000000..32e5afa335
--- /dev/null
+++ b/actionpack/lib/action_controller/metal/live.rb
@@ -0,0 +1,141 @@
+require 'action_dispatch/http/response'
+require 'delegate'
+
+module ActionController
+ # Mix this module in to your controller, and all actions in that controller
+ # will be able to stream data to the client as it's written.
+ #
+ # class MyController < ActionController::Base
+ # include ActionController::Live
+ #
+ # def stream
+ # response.headers['Content-Type'] = 'text/event-stream'
+ # 100.times {
+ # response.stream.write "hello world\n"
+ # sleep 1
+ # }
+ # response.stream.close
+ # end
+ # end
+ #
+ # There are a few caveats with this use. You *cannot* write headers after the
+ # response has been committed (Response#committed? will return truthy).
+ # Calling +write+ or +close+ on the response stream will cause the response
+ # object to be committed. Make sure all headers are set before calling write
+ # or close on your stream.
+ #
+ # You *must* call close on your stream when you're finished, otherwise the
+ # socket may be left open forever.
+ #
+ # The final caveat is that your actions are executed in a separate thread than
+ # the main thread. Make sure your actions are thread safe, and this shouldn't
+ # be a problem (don't share state across threads, etc).
+ module Live
+ class Buffer < ActionDispatch::Response::Buffer #:nodoc:
+ def initialize(response)
+ super(response, SizedQueue.new(10))
+ end
+
+ def write(string)
+ unless @response.committed?
+ @response.headers["Cache-Control"] = "no-cache"
+ @response.headers.delete "Content-Length"
+ end
+
+ super
+ end
+
+ def each
+ while str = @buf.pop
+ yield str
+ end
+ end
+
+ def close
+ super
+ @buf.push nil
+ end
+ end
+
+ class Response < ActionDispatch::Response #:nodoc: all
+ class Header < DelegateClass(Hash)
+ def initialize(response, header)
+ @response = response
+ super(header)
+ end
+
+ def []=(k,v)
+ if @response.committed?
+ raise ActionDispatch::IllegalStateError, 'header already sent'
+ end
+
+ super
+ end
+
+ def merge(other)
+ self.class.new @response, __getobj__.merge(other)
+ end
+
+ def to_hash
+ __getobj__.dup
+ end
+ end
+
+ def commit!
+ headers.freeze
+ super
+ end
+
+ private
+
+ def build_buffer(response, body)
+ buf = Live::Buffer.new response
+ body.each { |part| buf.write part }
+ buf
+ end
+
+ def merge_default_headers(original, default)
+ Header.new self, super
+ end
+ end
+
+ def process(name)
+ t1 = Thread.current
+ locals = t1.keys.map { |key| [key, t1[key]] }
+
+ # This processes the action in a child thread. It lets us return the
+ # response code and headers back up the rack stack, and still process
+ # the body in parallel with sending data to the client
+ Thread.new {
+ t2 = Thread.current
+ t2.abort_on_exception = true
+
+ # Since we're processing the view in a different thread, copy the
+ # thread locals from the main thread to the child thread. :'(
+ locals.each { |k,v| t2[k] = v }
+
+ begin
+ super(name)
+ ensure
+ @_response.commit!
+ end
+ }
+
+ @_response.await_commit
+ end
+
+ def response_body=(body)
+ super
+ response.stream.close if response
+ end
+
+ def set_response!(request)
+ if request.env["HTTP_VERSION"] == "HTTP/1.0"
+ super
+ else
+ @_response = Live::Response.new
+ @_response.request = request
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/metal/mime_responds.rb b/actionpack/lib/action_controller/metal/mime_responds.rb
index 0b800c3c62..18ae2c3bfc 100644
--- a/actionpack/lib/action_controller/metal/mime_responds.rb
+++ b/actionpack/lib/action_controller/metal/mime_responds.rb
@@ -1,6 +1,4 @@
require 'abstract_controller/collector'
-require 'active_support/core_ext/class/attribute'
-require 'active_support/core_ext/object/inclusion'
module ActionController #:nodoc:
module MimeResponds
@@ -182,7 +180,8 @@ module ActionController #:nodoc:
# end
# end
#
- # Be sure to check respond_with and respond_to documentation for more examples.
+ # Be sure to check the documentation of +respond_with+ and
+ # <tt>ActionController::MimeResponds.respond_to</tt> for more examples.
def respond_to(*mimes, &block)
raise ArgumentError, "respond_to takes either types or a block, never both" if mimes.any? && block_given?
@@ -342,9 +341,9 @@ module ActionController #:nodoc:
config = self.class.mimes_for_respond_to[mime]
if config[:except]
- !action.in?(config[:except])
+ !config[:except].include?(action)
elsif config[:only]
- action.in?(config[:only])
+ config[:only].include?(action)
else
true
end
diff --git a/actionpack/lib/action_controller/metal/params_wrapper.rb b/actionpack/lib/action_controller/metal/params_wrapper.rb
index aa67fa7f23..2736948ce0 100644
--- a/actionpack/lib/action_controller/metal/params_wrapper.rb
+++ b/actionpack/lib/action_controller/metal/params_wrapper.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/hash/slice'
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/module/anonymous'
diff --git a/actionpack/lib/action_controller/metal/rack_delegation.rb b/actionpack/lib/action_controller/metal/rack_delegation.rb
index 544b4989c7..bdf6e88699 100644
--- a/actionpack/lib/action_controller/metal/rack_delegation.rb
+++ b/actionpack/lib/action_controller/metal/rack_delegation.rb
@@ -8,9 +8,8 @@ module ActionController
delegate :headers, :status=, :location=, :content_type=,
:status, :location, :content_type, :to => "@_response"
- def dispatch(action, request, response = ActionDispatch::Response.new)
- @_response ||= response
- @_response.request ||= request
+ def dispatch(action, request)
+ set_response!(request)
super(action, request)
end
@@ -22,5 +21,12 @@ module ActionController
def reset_session
@_request.reset_session
end
+
+ private
+
+ def set_response!(request)
+ @_response = ActionDispatch::Response.new
+ @_response.request = request
+ end
end
end
diff --git a/actionpack/lib/action_controller/metal/renderers.rb b/actionpack/lib/action_controller/metal/renderers.rb
index 1927c8bdc7..78aeeef2bf 100644
--- a/actionpack/lib/action_controller/metal/renderers.rb
+++ b/actionpack/lib/action_controller/metal/renderers.rb
@@ -1,5 +1,3 @@
-require 'active_support/core_ext/class/attribute'
-require 'active_support/core_ext/object/blank'
require 'set'
module ActionController
diff --git a/actionpack/lib/action_controller/metal/request_forgery_protection.rb b/actionpack/lib/action_controller/metal/request_forgery_protection.rb
index 95b0e99ed5..d5f1cbc1a8 100644
--- a/actionpack/lib/action_controller/metal/request_forgery_protection.rb
+++ b/actionpack/lib/action_controller/metal/request_forgery_protection.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/class/attribute'
require 'action_controller/metal/exceptions'
module ActionController #:nodoc:
@@ -14,6 +13,20 @@ module ActionController #:nodoc:
# authentication scheme there anyway). Also, GET requests are not protected as these
# should be idempotent.
#
+ # It's important to remember that XML or JSON requests are also affected and if
+ # you're building an API you'll need something like:
+ #
+ # class ApplicationController < ActionController::Base
+ # protect_from_forgery
+ # skip_before_filter :verify_authenticity_token, :if => :json_request?
+ #
+ # protected
+ #
+ # def json_request?
+ # request.format.json?
+ # end
+ # end
+ #
# CSRF protection is turned on with the <tt>protect_from_forgery</tt> method,
# which checks the token and resets the session if it doesn't match what was expected.
# A call to this method is generated for new \Rails applications by default.
diff --git a/actionpack/lib/action_controller/metal/responder.rb b/actionpack/lib/action_controller/metal/responder.rb
index 83407846dc..d9c89a74f1 100644
--- a/actionpack/lib/action_controller/metal/responder.rb
+++ b/actionpack/lib/action_controller/metal/responder.rb
@@ -90,7 +90,7 @@ module ActionController #:nodoc:
#
# def create
# @project = Project.find(params[:project_id])
- # @task = @project.comments.build(params[:task])
+ # @task = @project.tasks.build(params[:task])
# flash[:notice] = 'Task was successfully created.' if @task.save
# respond_with(@project, @task, :status => 201)
# end
diff --git a/actionpack/lib/action_controller/metal/streaming.rb b/actionpack/lib/action_controller/metal/streaming.rb
index eeb37db2e7..9f3c997024 100644
--- a/actionpack/lib/action_controller/metal/streaming.rb
+++ b/actionpack/lib/action_controller/metal/streaming.rb
@@ -139,9 +139,6 @@ module ActionController #:nodoc:
# session or flash after the template starts rendering will not propagate
# to the client.
#
- # If you try to modify cookies, session or flash, an <tt>ActionDispatch::ClosedError</tt>
- # will be raised, showing those objects are closed for modification.
- #
# == Middlewares
#
# Middlewares that need to manipulate the body won't work with streaming.
diff --git a/actionpack/lib/action_controller/metal/testing.rb b/actionpack/lib/action_controller/metal/testing.rb
index d1813ee745..0377b8c4cf 100644
--- a/actionpack/lib/action_controller/metal/testing.rb
+++ b/actionpack/lib/action_controller/metal/testing.rb
@@ -4,30 +4,25 @@ module ActionController
include RackDelegation
- def recycle!
- @_url_options = nil
- end
-
-
- # TODO: Clean this up
- def process_with_new_base_test(request, response)
- @_request = request
- @_response = response
- @_response.request = request
- ret = process(request.parameters[:action])
- if cookies = @_request.env['action_dispatch.cookies']
- cookies.write(@_response)
- end
- @_response.prepare!
- ret
- end
-
# TODO : Rewrite tests using controller.headers= to use Rack env
def headers=(new_headers)
@_response ||= ActionDispatch::Response.new
@_response.headers.replace(new_headers)
end
+ # Behavior specific to functional tests
+ module Functional # :nodoc:
+ def set_response!(request)
+ end
+
+ def recycle!
+ @_url_options = nil
+ self.response_body = nil
+ self.formats = nil
+ self.params = nil
+ end
+ end
+
module ClassMethods
def before_filters
_process_action_callbacks.find_all{|x| x.kind == :before}.map{|x| x.name}
diff --git a/actionpack/lib/action_controller/metal/url_for.rb b/actionpack/lib/action_controller/metal/url_for.rb
index e28c05cc2d..0cdd17bc2e 100644
--- a/actionpack/lib/action_controller/metal/url_for.rb
+++ b/actionpack/lib/action_controller/metal/url_for.rb
@@ -27,12 +27,18 @@ module ActionController
:host => request.host,
:port => request.optional_port,
:protocol => request.protocol,
- :_path_segments => request.symbolized_path_parameters
+ :_recall => request.symbolized_path_parameters
).freeze
- if _routes.equal?(env["action_dispatch.routes"])
+ if (same_origin = _routes.equal?(env["action_dispatch.routes"])) ||
+ (script_name = env["ROUTES_#{_routes.object_id}_SCRIPT_NAME"]) ||
+ (original_script_name = env['SCRIPT_NAME'])
@_url_options.dup.tap do |options|
- options[:script_name] = request.script_name.dup
+ if original_script_name
+ options[:original_script_name] = original_script_name
+ else
+ options[:script_name] = same_origin ? request.script_name.dup : script_name
+ end
options.freeze
end
else
diff --git a/actionpack/lib/action_controller/model_naming.rb b/actionpack/lib/action_controller/model_naming.rb
new file mode 100644
index 0000000000..785221dc3d
--- /dev/null
+++ b/actionpack/lib/action_controller/model_naming.rb
@@ -0,0 +1,12 @@
+module ActionController
+ module ModelNaming
+ # Converts the given object to an ActiveModel compliant one.
+ def convert_to_model(object)
+ object.respond_to?(:to_model) ? object.to_model : object
+ end
+
+ def model_name_from_record_or_class(record_or_class)
+ (record_or_class.is_a?(Class) ? record_or_class : convert_to_model(record_or_class).class).model_name
+ end
+ end
+end
diff --git a/actionpack/lib/action_controller/record_identifier.rb b/actionpack/lib/action_controller/record_identifier.rb
index 16a5decc62..d3ac406618 100644
--- a/actionpack/lib/action_controller/record_identifier.rb
+++ b/actionpack/lib/action_controller/record_identifier.rb
@@ -1,4 +1,5 @@
require 'active_support/core_ext/module'
+require 'action_controller/model_naming'
module ActionController
# The record identifier encapsulates a number of naming conventions for dealing with records, like Active Records or
@@ -27,6 +28,8 @@ module ActionController
module RecordIdentifier
extend self
+ include ModelNaming
+
JOIN = '_'.freeze
NEW = 'new'.freeze
@@ -40,7 +43,7 @@ module ActionController
# dom_class(post, :edit) # => "edit_post"
# dom_class(Person, :edit) # => "edit_person"
def dom_class(record_or_class, prefix = nil)
- singular = ActiveModel::Naming.param_key(record_or_class)
+ singular = model_name_from_record_or_class(record_or_class).param_key
prefix ? "#{prefix}#{JOIN}#{singular}" : singular
end
@@ -73,8 +76,7 @@ module ActionController
# method that replaces all characters that are invalid inside DOM ids, with valid ones. You need to
# make sure yourself that your dom ids are valid, in case you overwrite this method.
def record_key_for_dom_id(record)
- record = record.to_model if record.respond_to?(:to_model)
- key = record.to_key
+ key = convert_to_model(record).to_key
key ? key.join('_') : key
end
end
diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb
index 028a8d3fba..bb693c6494 100644
--- a/actionpack/lib/action_controller/test_case.rb
+++ b/actionpack/lib/action_controller/test_case.rb
@@ -1,7 +1,5 @@
require 'rack/session/abstract/id'
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/object/to_query'
-require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/module/anonymous'
module ActionController
@@ -143,6 +141,9 @@ module ActionController
end
class TestRequest < ActionDispatch::TestRequest #:nodoc:
+ DEFAULT_ENV = ActionDispatch::TestRequest::DEFAULT_ENV.dup
+ DEFAULT_ENV.delete 'PATH_INFO'
+
def initialize(env = {})
super
@@ -150,10 +151,6 @@ module ActionController
self.session_options = TestSession::DEFAULT_OPTIONS.merge(:id => SecureRandom.hex(16))
end
- class Result < ::Array #:nodoc:
- def to_s() join '/' end
- end
-
def assign_parameters(routes, controller_path, action, parameters = {})
parameters = parameters.symbolize_keys.merge(:controller => controller_path, :action => action)
extra_keys = routes.extra_keys(parameters)
@@ -171,7 +168,7 @@ module ActionController
non_path_parameters[key] = value
else
if value.is_a?(Array)
- value = Result.new(value.map(&:to_param))
+ value = value.map(&:to_param)
else
value = value.to_param
end
@@ -211,18 +208,17 @@ module ActionController
cookie_jar.update(@set_cookies)
cookie_jar.recycle!
end
+
+ private
+
+ def default_env
+ DEFAULT_ENV
+ end
end
class TestResponse < ActionDispatch::TestResponse
def recycle!
- @status = 200
- @header = {}
- @writer = lambda { |x| @body << x }
- @block = nil
- @length = 0
- @body = []
- @charset = @content_type = nil
- @request = @template = nil
+ initialize
end
end
@@ -353,7 +349,7 @@ module ActionController
# Use AS::TestCase for the base class when describing a model
register_spec_type(self) do |desc|
- desc < ActionController::Base
+ Class === desc && desc < ActionController::Base
end
module Behavior
@@ -430,8 +426,13 @@ module ActionController
end
# Executes a request simulating HEAD HTTP method and set/volley the response
- def head(action, parameters = nil, session = nil, flash = nil)
- process(action, "HEAD", parameters, session, flash)
+ def head(action, *args)
+ process(action, "HEAD", *args)
+ end
+
+ # Executes a request simulating OPTIONS HTTP method and set/volley the response
+ def options(action, *args)
+ process(action, "OPTIONS", *args)
end
def xml_http_request(request_method, action, parameters = nil, session = nil, flash = nil)
@@ -450,7 +451,7 @@ module ActionController
Hash[hash_or_array_or_value.map{|key, value| [key, paramify_values(value)] }]
when Array
hash_or_array_or_value.map {|i| paramify_values(i)}
- when Rack::Test::UploadedFile
+ when Rack::Test::UploadedFile, ActionDispatch::Http::UploadedFile
hash_or_array_or_value
else
hash_or_array_or_value.to_param
@@ -471,13 +472,17 @@ module ActionController
# proper params, as is the case when engaging rack.
parameters = paramify_values(parameters) if html_format?(parameters)
+ @html_document = nil
+
+ unless @controller.respond_to?(:recycle!)
+ @controller.extend(Testing::Functional)
+ @controller.class.class_eval { include Testing }
+ end
+
@request.recycle!
@response.recycle!
- @controller.response_body = nil
- @controller.formats = nil
- @controller.params = nil
+ @controller.recycle!
- @html_document = nil
@request.env['REQUEST_METHOD'] = http_method
parameters ||= {}
@@ -490,32 +495,56 @@ module ActionController
@request.session.update(session) if session
@request.session["flash"] = @request.flash.update(flash || {})
- @controller.request = @request
+ @controller.request = @request
+ @controller.response = @response
+
build_request_uri(action, parameters)
- @controller.class.class_eval { include Testing }
- @controller.recycle!
- @controller.process_with_new_base_test(@request, @response)
+
+ name = @request.parameters[:action]
+
+ @controller.process(name)
+
+ if cookies = @request.env['action_dispatch.cookies']
+ cookies.write(@response)
+ end
+ @response.prepare!
+
@assigns = @controller.respond_to?(:view_assigns) ? @controller.view_assigns : {}
@request.session.delete('flash') if @request.session['flash'].blank?
@response
end
def setup_controller_request_and_response
- @request = TestRequest.new
- @response = TestResponse.new
+ @request = build_request
+ @response = build_response
+ @response.request = @request
+
+ @controller = nil unless defined? @controller
if klass = self.class.controller_class
- @controller ||= klass.new rescue nil
+ unless @controller
+ begin
+ @controller = klass.new
+ rescue
+ warn "could not construct controller #{klass}" if $VERBOSE
+ end
+ end
end
- @request.env.delete('PATH_INFO')
-
- if defined?(@controller) && @controller
+ if @controller
@controller.request = @request
@controller.params = {}
end
end
+ def build_request
+ TestRequest.new
+ end
+
+ def build_response
+ TestResponse.new
+ end
+
included do
include ActionController::TemplateAssertions
include ActionDispatch::Assertions
@@ -523,7 +552,7 @@ module ActionController
setup :setup_controller_request_and_response
end
- private
+ private
def check_required_ivars
# Sanity check for required instance variables so we can give an
# understandable error message.
@@ -552,7 +581,7 @@ module ActionController
:only_path => true,
:action => action,
:relative_url_root => nil,
- :_path_segments => @request.symbolized_path_parameters)
+ :_recall => @request.symbolized_path_parameters)
url, query_string = @routes.url_for(options).split("?", 2)
@@ -564,8 +593,7 @@ module ActionController
def html_format?(parameters)
return true unless parameters.is_a?(Hash)
- format = Mime[parameters[:format]]
- format.nil? || format.html?
+ Mime.fetch(parameters[:format]) { Mime['html'] }.html?
end
end
@@ -576,7 +604,7 @@ module ActionController
#
# The exception is stored in the exception accessor for further inspection.
module RaiseActionExceptions
- def self.included(base)
+ def self.included(base) #:nodoc:
unless base.method_defined?(:exception) && base.method_defined?(:exception=)
base.class_eval do
attr_accessor :exception
diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb b/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
index 6b269e7a31..6b4ececda2 100644
--- a/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
+++ b/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
@@ -1,6 +1,5 @@
require 'set'
require 'cgi'
-require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/class/attribute_accessors'
module HTML
diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb
index 1e4ac70f3d..b382997052 100644
--- a/actionpack/lib/action_dispatch.rb
+++ b/actionpack/lib/action_dispatch.rb
@@ -22,11 +22,10 @@
#++
require 'active_support'
-require 'active_support/dependencies/autoload'
+require 'active_support/rails'
require 'active_support/core_ext/module/attribute_accessors'
require 'action_pack'
-require 'active_model'
require 'rack'
module Rack
@@ -36,6 +35,9 @@ end
module ActionDispatch
extend ActiveSupport::Autoload
+ class IllegalStateError < StandardError
+ end
+
autoload_under 'http' do
autoload :Request
autoload :Response
diff --git a/actionpack/lib/action_dispatch/http/cache.rb b/actionpack/lib/action_dispatch/http/cache.rb
index 5ee4c044ea..a7f93b780e 100644
--- a/actionpack/lib/action_dispatch/http/cache.rb
+++ b/actionpack/lib/action_dispatch/http/cache.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
module ActionDispatch
module Http
@@ -84,17 +83,37 @@ module ActionDispatch
LAST_MODIFIED = "Last-Modified".freeze
ETAG = "ETag".freeze
CACHE_CONTROL = "Cache-Control".freeze
+ SPESHUL_KEYS = %w[extras no-cache max-age public must-revalidate]
- def prepare_cache_control!
- @cache_control = {}
- @etag = self[ETAG]
-
+ def cache_control_segments
if cache_control = self[CACHE_CONTROL]
- cache_control.split(/,\s*/).each do |segment|
- first, last = segment.split("=")
- @cache_control[first.to_sym] = last || true
+ cache_control.delete(' ').split(',')
+ else
+ []
+ end
+ end
+
+ def cache_control_headers
+ cache_control = {}
+
+ cache_control_segments.each do |segment|
+ directive, argument = segment.split('=', 2)
+
+ if SPESHUL_KEYS.include? directive
+ key = directive.tr('-', '_')
+ cache_control[key.to_sym] = argument || true
+ else
+ cache_control[:extras] ||= []
+ cache_control[:extras] << segment
end
end
+
+ cache_control
+ end
+
+ def prepare_cache_control!
+ @cache_control = cache_control_headers
+ @etag = self[ETAG]
end
def handle_conditional_get!
@@ -110,14 +129,24 @@ module ActionDispatch
MUST_REVALIDATE = "must-revalidate".freeze
def set_conditional_cache_control!
- return if self[CACHE_CONTROL].present?
+ control = {}
+ cc_headers = cache_control_headers
+ if extras = cc_headers.delete(:extras)
+ @cache_control[:extras] ||= []
+ @cache_control[:extras] += extras
+ @cache_control[:extras].uniq!
+ end
- control = @cache_control
+ control.merge! cc_headers
+ control.merge! @cache_control
if control.empty?
headers[CACHE_CONTROL] = DEFAULT_CACHE_CONTROL
elsif control[:no_cache]
headers[CACHE_CONTROL] = NO_CACHE
+ if control[:extras]
+ headers[CACHE_CONTROL] += ", #{control[:extras].join(', ')}"
+ end
else
extras = control[:extras]
max_age = control[:max_age]
diff --git a/actionpack/lib/action_dispatch/http/filter_parameters.rb b/actionpack/lib/action_dispatch/http/filter_parameters.rb
index 6413929be3..47cf41cfa3 100644
--- a/actionpack/lib/action_dispatch/http/filter_parameters.rb
+++ b/actionpack/lib/action_dispatch/http/filter_parameters.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/hash/keys'
require 'active_support/core_ext/object/duplicable'
diff --git a/actionpack/lib/action_dispatch/http/mime_negotiation.rb b/actionpack/lib/action_dispatch/http/mime_negotiation.rb
index e31f3b823d..0f98e84788 100644
--- a/actionpack/lib/action_dispatch/http/mime_negotiation.rb
+++ b/actionpack/lib/action_dispatch/http/mime_negotiation.rb
@@ -80,6 +80,27 @@ module ActionDispatch
@env["action_dispatch.request.formats"] = [Mime::Type.lookup_by_extension(parameters[:format])]
end
+ # Sets the \formats by string extensions. This differs from #format= by allowing you
+ # to set multiple, ordered formats, which is useful when you want to have a fallback.
+ #
+ # In this example, the :iphone format will be used if it's available, otherwise it'll fallback
+ # to the :html format.
+ #
+ # class ApplicationController < ActionController::Base
+ # before_filter :adjust_format_for_iphone_with_html_fallback
+ #
+ # private
+ # def adjust_format_for_iphone_with_html_fallback
+ # request.formats = [ :iphone, :html ] if request.env["HTTP_USER_AGENT"][/iPhone/]
+ # end
+ # end
+ def formats=(extensions)
+ parameters[:format] = extensions.first.to_s
+ @env["action_dispatch.request.formats"] = extensions.collect do |extension|
+ Mime::Type.lookup_by_extension(extension)
+ end
+ end
+
# Receives an array of mimes and return the first user sent mime that
# matches the order array.
#
diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb
index 0eaae80461..fd86966c50 100644
--- a/actionpack/lib/action_dispatch/http/mime_type.rb
+++ b/actionpack/lib/action_dispatch/http/mime_type.rb
@@ -1,6 +1,5 @@
require 'set'
require 'active_support/core_ext/class/attribute_accessors'
-require 'active_support/core_ext/object/blank'
module Mime
class Mimes < Array
@@ -29,6 +28,11 @@ module Mime
Type.lookup_by_extension(type.to_s)
end
+ def self.fetch(type)
+ return type if type.is_a?(Type)
+ EXTENSION_LOOKUP.fetch(type.to_s) { |k| yield k }
+ end
+
# Encapsulates the notion of a mime type. Can be used at render time, for example, with:
#
# class PostsController < ActionController::Base
@@ -53,6 +57,8 @@ module Mime
cattr_reader :browser_generated_types
attr_reader :symbol
+ @register_callbacks = []
+
# A simple helper class used in parsing the accept header
class AcceptItem #:nodoc:
attr_accessor :order, :name, :q
@@ -84,6 +90,10 @@ module Mime
TRAILING_STAR_REGEXP = /(text|application)\/\*/
PARAMETER_SEPARATOR_REGEXP = /;\s*\w+="?\w+"?/
+ def register_callback(&block)
+ @register_callbacks << block
+ end
+
def lookup(string)
LOOKUP[string]
end
@@ -99,12 +109,17 @@ module Mime
end
def register(string, symbol, mime_type_synonyms = [], extension_synonyms = [], skip_lookup = false)
- Mime.const_set(symbol.to_s.upcase, Type.new(string, symbol, mime_type_synonyms))
+ Mime.const_set(symbol.upcase, Type.new(string, symbol, mime_type_synonyms))
- SET << Mime.const_get(symbol.to_s.upcase)
+ new_mime = Mime.const_get(symbol.upcase)
+ SET << new_mime
([string] + mime_type_synonyms).each { |str| LOOKUP[str] = SET.last } unless skip_lookup
([symbol] + extension_synonyms).each { |ext| EXTENSION_LOOKUP[ext.to_s] = SET.last }
+
+ @register_callbacks.each do |callback|
+ callback.call(new_mime)
+ end
end
def parse(accept_header)
@@ -194,7 +209,7 @@ module Mime
#
# Mime::Type.unregister(:mobile)
def unregister(symbol)
- symbol = symbol.to_s.upcase
+ symbol = symbol.upcase
mime = Mime.const_get(symbol)
Mime.instance_eval { remove_const(symbol) }
diff --git a/actionpack/lib/action_dispatch/http/parameters.rb b/actionpack/lib/action_dispatch/http/parameters.rb
index bcfd0b0d00..9a7b5bc8c7 100644
--- a/actionpack/lib/action_dispatch/http/parameters.rb
+++ b/actionpack/lib/action_dispatch/http/parameters.rb
@@ -4,6 +4,11 @@ require 'active_support/core_ext/hash/indifferent_access'
module ActionDispatch
module Http
module Parameters
+ def initialize(env)
+ super
+ @symbolized_path_params = nil
+ end
+
# Returns both GET and POST \parameters in a single hash.
def parameters
@env["action_dispatch.request.parameters"] ||= begin
diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb
index aa5ba3e8a5..d24c7c7f3f 100644
--- a/actionpack/lib/action_dispatch/http/request.rb
+++ b/actionpack/lib/action_dispatch/http/request.rb
@@ -38,6 +38,17 @@ module ActionDispatch
METHOD
end
+ def initialize(env)
+ super
+ @method = nil
+ @request_method = nil
+ @remote_ip = nil
+ @original_fullpath = nil
+ @fullpath = nil
+ @ip = nil
+ @uuid = nil
+ end
+
def key?(key)
@env.key?(key)
end
@@ -119,9 +130,9 @@ module ActionDispatch
end
# Is this a HEAD request?
- # Equivalent to <tt>request.method_symbol == :head</tt>.
+ # Equivalent to <tt>request.request_method_symbol == :head</tt>.
def head?
- HTTP_METHOD_LOOKUP[method] == :head
+ HTTP_METHOD_LOOKUP[request_method] == :head
end
# Provides access to the request's HTTP headers, for example:
@@ -263,6 +274,27 @@ module ActionDispatch
LOCALHOST =~ remote_addr && LOCALHOST =~ remote_ip
end
+ protected
+
+ # Remove nils from the params hash
+ def deep_munge(hash)
+ hash.each_value do |v|
+ case v
+ when Array
+ v.grep(Hash) { |x| deep_munge(x) }
+ v.compact!
+ when Hash
+ deep_munge(v)
+ end
+ end
+
+ hash
+ end
+
+ def parse_query(qs)
+ deep_munge(super)
+ end
+
private
def check_method(name)
diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb
index cc46f9983c..11b7534ea4 100644
--- a/actionpack/lib/action_dispatch/http/response.rb
+++ b/actionpack/lib/action_dispatch/http/response.rb
@@ -1,7 +1,6 @@
require 'digest/md5'
-require 'active_support/core_ext/module/delegation'
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/class/attribute_accessors'
+require 'monitor'
module ActionDispatch # :nodoc:
# Represents an HTTP response generated by a controller action. Use it to
@@ -41,7 +40,7 @@ module ActionDispatch # :nodoc:
alias_method :headers, :header
delegate :[], :[]=, :to => :@header
- delegate :each, :to => :@body
+ delegate :each, :to => :@stream
# Sets the HTTP response's content MIME type. For example, in the controller
# you could write this:
@@ -59,15 +58,55 @@ module ActionDispatch # :nodoc:
LOCATION = "Location".freeze
cattr_accessor(:default_charset) { "utf-8" }
+ cattr_accessor(:default_headers)
include Rack::Response::Helpers
include ActionDispatch::Http::Cache::Response
+ include MonitorMixin
+
+ class Buffer # :nodoc:
+ def initialize(response, buf)
+ @response = response
+ @buf = buf
+ @closed = false
+ end
+
+ def write(string)
+ raise IOError, "closed stream" if closed?
+
+ @response.commit!
+ @buf.push string
+ end
+
+ def each(&block)
+ @buf.each(&block)
+ end
+
+ def close
+ @response.commit!
+ @closed = true
+ end
+
+ def closed?
+ @closed
+ end
+ end
+
+ attr_reader :stream
def initialize(status = 200, header = {}, body = [])
+ super()
+
+ header = merge_default_headers(header, self.class.default_headers)
+
self.body, self.header, self.status = body, header, status
@sending_file = false
- @blank = false
+ @blank = false
+ @cv = new_cond
+ @committed = false
+ @content_type = nil
+ @charset = nil
if content_type = self[CONTENT_TYPE]
type, charset = content_type.split(/;\s*charset=/)
@@ -80,6 +119,23 @@ module ActionDispatch # :nodoc:
yield self if block_given?
end
+ def await_commit
+ synchronize do
+ @cv.wait_until { @committed }
+ end
+ end
+
+ def commit!
+ synchronize do
+ @committed = true
+ @cv.broadcast
+ end
+ end
+
+ def committed?
+ @committed
+ end
+
def status=(status)
@status = Rack::Utils.status_code(status)
end
@@ -105,14 +161,14 @@ module ActionDispatch # :nodoc:
def respond_to?(method)
if method.to_sym == :to_path
- @body.respond_to?(:to_path)
+ stream.respond_to?(:to_path)
else
super
end
end
def to_path
- @body.to_path
+ stream.to_path
end
def body
@@ -126,11 +182,17 @@ module ActionDispatch # :nodoc:
def body=(body)
@blank = true if body == EMPTY
- @body = body.respond_to?(:each) ? body : [body]
+ if body.respond_to?(:to_path)
+ @stream = body
+ else
+ @stream = build_buffer self, munge_body_object(body)
+ end
end
def body_parts
- @body
+ parts = []
+ @stream.each { |x| parts << x }
+ parts
end
def set_cookie(key, value)
@@ -151,21 +213,11 @@ module ActionDispatch # :nodoc:
end
def close
- @body.close if @body.respond_to?(:close)
+ stream.close if stream.respond_to?(:close)
end
def to_a
- assign_default_content_type_and_charset!
- handle_conditional_get!
-
- @header[SET_COOKIE] = @header[SET_COOKIE].join("\n") if @header[SET_COOKIE].respond_to?(:join)
-
- if [204, 304].include?(@status)
- @header.delete CONTENT_TYPE
- [@status, @header, []]
- else
- [@status, @header, self]
- end
+ rack_response @status, @header.to_hash
end
alias prepare! to_a
alias to_ary to_a # For implicit splat on 1.9.2
@@ -189,7 +241,21 @@ module ActionDispatch # :nodoc:
private
- def assign_default_content_type_and_charset!
+ def merge_default_headers(original, default)
+ return original unless default.respond_to?(:merge)
+
+ default.merge(original)
+ end
+
+ def build_buffer(response, body)
+ Buffer.new response, body
+ end
+
+ def munge_body_object(body)
+ body.respond_to?(:each) ? body : [body]
+ end
+
+ def assign_default_content_type_and_charset!(headers)
return if headers[CONTENT_TYPE].present?
@content_type ||= Mime::HTML
@@ -200,5 +266,19 @@ module ActionDispatch # :nodoc:
headers[CONTENT_TYPE] = type
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 [204, 304].include?(@status)
+ header.delete CONTENT_TYPE
+ [status, header, []]
+ else
+ [status, header, self]
+ end
+ end
end
end
diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb
index 4266ec042e..8aa02ec482 100644
--- a/actionpack/lib/action_dispatch/http/url.rb
+++ b/actionpack/lib/action_dispatch/http/url.rb
@@ -87,6 +87,12 @@ module ActionDispatch
end
end
+ def initialize(env)
+ super
+ @protocol = nil
+ @port = nil
+ end
+
# Returns the complete URL used for this request.
def url
protocol + host_with_port + fullpath
diff --git a/actionpack/lib/action_dispatch/middleware/callbacks.rb b/actionpack/lib/action_dispatch/middleware/callbacks.rb
index 338b116940..852f1cf6f5 100644
--- a/actionpack/lib/action_dispatch/middleware/callbacks.rb
+++ b/actionpack/lib/action_dispatch/middleware/callbacks.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/module/delegation'
module ActionDispatch
# Provide callbacks to be executed before and after the request dispatch.
diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb
index 771f075275..ba5d332d49 100644
--- a/actionpack/lib/action_dispatch/middleware/cookies.rb
+++ b/actionpack/lib/action_dispatch/middleware/cookies.rb
@@ -1,5 +1,5 @@
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/hash/keys'
+require 'active_support/core_ext/module/attribute_accessors'
module ActionDispatch
class Request < Rack::Request
diff --git a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
index b903f98761..0f0589a844 100644
--- a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
+++ b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
@@ -1,5 +1,7 @@
require 'action_dispatch/http/request'
require 'action_dispatch/middleware/exception_wrapper'
+require 'action_dispatch/routing/inspector'
+
module ActionDispatch
# This middleware is responsible for logging exceptions and
@@ -7,8 +9,9 @@ module ActionDispatch
class DebugExceptions
RESCUES_TEMPLATE_PATH = File.join(File.dirname(__FILE__), 'templates')
- def initialize(app)
- @app = app
+ def initialize(app, routes_app = nil)
+ @app = app
+ @routes_app = routes_app
end
def call(env)
@@ -39,7 +42,8 @@ module ActionDispatch
:exception => wrapper.exception,
:application_trace => wrapper.application_trace,
:framework_trace => wrapper.framework_trace,
- :full_trace => wrapper.full_trace
+ :full_trace => wrapper.full_trace,
+ :routes => formatted_routes(exception)
)
file = "rescues/#{wrapper.rescue_template}"
@@ -78,5 +82,13 @@ module ActionDispatch
def stderr_logger
@stderr_logger ||= ActiveSupport::Logger.new($stderr)
end
+
+ def formatted_routes(exception)
+ return false unless @routes_app.respond_to?(:routes)
+ if exception.is_a?(ActionController::RoutingError) || exception.is_a?(ActionView::Template::Error)
+ inspector = ActionDispatch::Routing::RoutesInspector.new
+ inspector.format(@routes_app.routes.routes).join("\n")
+ end
+ end
end
end
diff --git a/actionpack/lib/action_dispatch/middleware/head.rb b/actionpack/lib/action_dispatch/middleware/head.rb
deleted file mode 100644
index f1906a3ab3..0000000000
--- a/actionpack/lib/action_dispatch/middleware/head.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-module ActionDispatch
- class Head
- def initialize(app)
- @app = app
- end
-
- def call(env)
- if env["REQUEST_METHOD"] == "HEAD"
- env["REQUEST_METHOD"] = "GET"
- env["rack.methodoverride.original_method"] = "HEAD"
- status, headers, _ = @app.call(env)
- [status, headers, []]
- else
- @app.call(env)
- end
- end
- end
-end
diff --git a/actionpack/lib/action_dispatch/middleware/public_exceptions.rb b/actionpack/lib/action_dispatch/middleware/public_exceptions.rb
index 85b8d178bf..53bedaa40a 100644
--- a/actionpack/lib/action_dispatch/middleware/public_exceptions.rb
+++ b/actionpack/lib/action_dispatch/middleware/public_exceptions.rb
@@ -1,5 +1,4 @@
module ActionDispatch
- # A simple Rack application that renders exceptions in the given public path.
class PublicExceptions
attr_accessor :public_path
@@ -8,23 +7,41 @@ module ActionDispatch
end
def call(env)
- status = env["PATH_INFO"][1..-1]
- locale_path = "#{public_path}/#{status}.#{I18n.locale}.html" if I18n.locale
- path = "#{public_path}/#{status}.html"
-
- if locale_path && File.exist?(locale_path)
- render(status, File.read(locale_path))
- elsif File.exist?(path)
- render(status, File.read(path))
+ exception = env["action_dispatch.exception"]
+ status = env["PATH_INFO"][1..-1]
+ request = ActionDispatch::Request.new(env)
+ content_type = request.formats.first
+ body = { :status => status, :error => exception.message }
+
+ render(status, content_type, body)
+ end
+
+ private
+
+ def render(status, content_type, body)
+ format = content_type && "to_#{content_type.to_sym}"
+ if format && body.respond_to?(format)
+ render_format(status, content_type, body.public_send(format))
else
- [404, { "X-Cascade" => "pass" }, []]
+ render_html(status)
end
end
- private
+ def render_format(status, content_type, body)
+ [status, {'Content-Type' => "#{content_type}; charset=#{ActionDispatch::Response.default_charset}",
+ 'Content-Length' => body.bytesize.to_s}, [body]]
+ end
+
+ def render_html(status)
+ found = false
+ path = "#{public_path}/#{status}.#{I18n.locale}.html" if I18n.locale
+ path = "#{public_path}/#{status}.html" unless path && (found = File.exist?(path))
- def render(status, body)
- [status, {'Content-Type' => "text/html; charset=#{Response.default_charset}", 'Content-Length' => body.bytesize.to_s}, [body]]
+ if found || File.exist?(path)
+ render_format(status, 'text/html', File.read(path))
+ else
+ [404, { "X-Cascade" => "pass" }, []]
+ end
end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/action_dispatch/middleware/request_id.rb b/actionpack/lib/action_dispatch/middleware/request_id.rb
index 6fff94707c..44290445d4 100644
--- a/actionpack/lib/action_dispatch/middleware/request_id.rb
+++ b/actionpack/lib/action_dispatch/middleware/request_id.rb
@@ -1,6 +1,5 @@
require 'securerandom'
require 'active_support/core_ext/string/access'
-require 'active_support/core_ext/object/blank'
module ActionDispatch
# Makes a unique request id available to the action_dispatch.request_id env variable (which is then accessible through
diff --git a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
index 64159fa8e7..7c12590c49 100644
--- a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
+++ b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
@@ -3,7 +3,6 @@ require 'rack/request'
require 'rack/session/abstract/id'
require 'action_dispatch/middleware/cookies'
require 'action_dispatch/request/session'
-require 'active_support/core_ext/object/blank'
module ActionDispatch
module Session
diff --git a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb
index 7efc094f98..9b159b2caf 100644
--- a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb
+++ b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb
@@ -1,5 +1,4 @@
require 'active_support/core_ext/hash/keys'
-require 'active_support/core_ext/object/blank'
require 'action_dispatch/middleware/session/abstract_store'
require 'rack/session/cookie'
diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.erb
index 177d383e94..8c594c1523 100644
--- a/actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.erb
+++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.erb
@@ -10,8 +10,14 @@
</ol>
</p>
<% end %>
+<%= render :template => "rescues/_trace" %>
+
+<h2>
+ Routes
+</h2>
+
<p>
- Try running <code>rake routes</code> for more information on available routes.
+ Routes match in priority from top to bottom
</p>
-<%= render :template => "rescues/_trace" %>
+<p><pre><%= @routes %></pre></p>
diff --git a/actionpack/lib/action_dispatch/railtie.rb b/actionpack/lib/action_dispatch/railtie.rb
index 62f906219c..5aad8dd23a 100644
--- a/actionpack/lib/action_dispatch/railtie.rb
+++ b/actionpack/lib/action_dispatch/railtie.rb
@@ -19,10 +19,17 @@ module ActionDispatch
:verbose => false
}
+ config.action_dispatch.default_headers = {
+ 'X-Frame-Options' => 'SAMEORIGIN',
+ 'X-XSS-Protection' => '1; mode=block',
+ 'X-Content-Type-Options' => 'nosniff'
+ }
+
initializer "action_dispatch.configure" do |app|
ActionDispatch::Http::URL.tld_length = app.config.action_dispatch.tld_length
ActionDispatch::Request.ignore_accept_header = app.config.action_dispatch.ignore_accept_header
ActionDispatch::Response.default_charset = app.config.action_dispatch.default_charset || app.config.encoding
+ ActionDispatch::Response.default_headers = app.config.action_dispatch.default_headers
ActionDispatch::ExceptionWrapper.rescue_responses.merge!(config.action_dispatch.rescue_responses)
ActionDispatch::ExceptionWrapper.rescue_templates.merge!(config.action_dispatch.rescue_templates)
diff --git a/actionpack/lib/action_dispatch/routing.rb b/actionpack/lib/action_dispatch/routing.rb
index 38a0270151..29090882a5 100644
--- a/actionpack/lib/action_dispatch/routing.rb
+++ b/actionpack/lib/action_dispatch/routing.rb
@@ -1,3 +1,4 @@
+# encoding: UTF-8
require 'active_support/core_ext/object/to_param'
require 'active_support/core_ext/regexp'
@@ -218,6 +219,12 @@ module ActionDispatch
#
# match "/stories" => redirect("/posts")
#
+ # == Unicode character routes
+ #
+ # You can specify unicode character routes in your router:
+ #
+ # match "こんにちは" => "welcome#index"
+ #
# == Routing to Rack Applications
#
# Instead of a String, like <tt>posts#index</tt>, which corresponds to the
diff --git a/actionpack/lib/action_dispatch/routing/inspector.rb b/actionpack/lib/action_dispatch/routing/inspector.rb
new file mode 100644
index 0000000000..bc7229b6a1
--- /dev/null
+++ b/actionpack/lib/action_dispatch/routing/inspector.rb
@@ -0,0 +1,121 @@
+require 'delegate'
+
+module ActionDispatch
+ module Routing
+ class RouteWrapper < SimpleDelegator
+ def endpoint
+ rack_app ? rack_app.inspect : "#{controller}##{action}"
+ end
+
+ def constraints
+ requirements.except(:controller, :action)
+ end
+
+ def rack_app(app = self.app)
+ @rack_app ||= begin
+ class_name = app.class.name.to_s
+ if class_name == "ActionDispatch::Routing::Mapper::Constraints"
+ rack_app(app.app)
+ elsif ActionDispatch::Routing::Redirect === app || class_name !~ /^ActionDispatch::Routing/
+ app
+ end
+ end
+ end
+
+ def verb
+ super.source.gsub(/[$^]/, '')
+ end
+
+ def path
+ super.spec.to_s
+ end
+
+ def name
+ super.to_s
+ end
+
+ def reqs
+ @reqs ||= begin
+ reqs = endpoint
+ reqs += " #{constraints.inspect}" unless constraints.empty?
+ reqs
+ end
+ end
+
+ def controller
+ requirements[:controller] || ':controller'
+ end
+
+ def action
+ requirements[:action] || ':action'
+ end
+
+ def internal?
+ path =~ %r{/rails/info.*|^#{Rails.application.config.assets.prefix}}
+ end
+
+ def engine?
+ rack_app && rack_app.respond_to?(:routes)
+ end
+ end
+
+ ##
+ # This class is just used for displaying route information when someone
+ # executes `rake routes`. People should not use this class.
+ class RoutesInspector # :nodoc:
+ def initialize
+ @engines = Hash.new
+ end
+
+ def format(all_routes, filter = nil)
+ if filter
+ all_routes = all_routes.select{ |route| route.defaults[:controller] == filter }
+ end
+
+ routes = collect_routes(all_routes)
+
+ formatted_routes(routes) +
+ formatted_routes_for_engines
+ end
+
+ def collect_routes(routes)
+ routes = routes.collect do |route|
+ RouteWrapper.new(route)
+ end.reject do |route|
+ route.internal?
+ end.collect do |route|
+ collect_engine_routes(route)
+
+ {:name => route.name, :verb => route.verb, :path => route.path, :reqs => route.reqs }
+ end
+ end
+
+ def collect_engine_routes(route)
+ name = route.endpoint
+ return unless route.engine?
+ return if @engines[name]
+
+ routes = route.rack_app.routes
+ if routes.is_a?(ActionDispatch::Routing::RouteSet)
+ @engines[name] = collect_routes(routes.routes)
+ end
+ end
+
+ def formatted_routes_for_engines
+ @engines.map do |name, routes|
+ ["\nRoutes for #{name}:"] + formatted_routes(routes)
+ end.flatten
+ end
+
+ def formatted_routes(routes)
+ name_width = routes.map{ |r| r[:name].length }.max
+ verb_width = routes.map{ |r| r[:verb].length }.max
+ path_width = routes.map{ |r| r[:path].length }.max
+
+ routes.map do |r|
+ "#{r[:name].rjust(name_width)} #{r[:verb].ljust(verb_width)} #{r[:path].ljust(path_width)} #{r[:reqs]}"
+ end
+ end
+ end
+ end
+end
diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb
index e43e897783..f64cff8394 100644
--- a/actionpack/lib/action_dispatch/routing/mapper.rb
+++ b/actionpack/lib/action_dispatch/routing/mapper.rb
@@ -1,7 +1,6 @@
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/hash/reverse_merge'
require 'active_support/core_ext/hash/slice'
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/enumerable'
require 'active_support/inflector'
require 'action_dispatch/routing/redirection'
@@ -262,7 +261,7 @@ module ActionDispatch
# for root cases, where the latter is the correct one.
def self.normalize_path(path)
path = Journey::Router::Utils.normalize_path(path)
- path.gsub!(%r{/(\(+)/?}, '\1/') unless path =~ %r{^/\(+[^/]+\)$}
+ path.gsub!(%r{/(\(+)/?}, '\1/') unless path =~ %r{^/\(+[^)]+\)$}
path
end
@@ -404,6 +403,10 @@ module ActionDispatch
#
# # Matches any request starting with 'path'
# match 'path' => 'c#a', :anchor => false
+ #
+ # [:format]
+ # Allows you to specify the default value for optional +format+
+ # segment or disable it by supplying +false+.
def match(path, options=nil)
end
@@ -430,6 +433,10 @@ module ActionDispatch
if options
path = options.delete(:at)
else
+ unless Hash === app
+ raise ArgumentError, "must be called with mount point"
+ end
+
options = app
app, path = options.find { |k, v| k.respond_to?(:call) }
options.delete(app) if app
@@ -437,9 +444,10 @@ module ActionDispatch
raise "A rack application must be specified" unless path
- options[:as] ||= app_name(app)
+ options[:as] ||= app_name(app)
+ options[:via] ||= :all
- match(path, options.merge(:to => app, :anchor => false, :format => false, :via => :all))
+ match(path, options.merge(:to => app, :anchor => false, :format => false))
define_generate_prefix(app, options[:as])
self
@@ -902,7 +910,7 @@ module ActionDispatch
# CANONICAL_ACTIONS holds all actions that does not need a prefix or
# a path appended since they fit properly in their scope level.
VALID_ON_OPTIONS = [:new, :collection, :member]
- RESOURCE_OPTIONS = [:as, :controller, :path, :only, :except, :param]
+ RESOURCE_OPTIONS = [:as, :controller, :path, :only, :except, :param, :concerns]
CANONICAL_ACTIONS = %w(index create new show update destroy)
class Resource #:nodoc:
@@ -913,7 +921,7 @@ module ActionDispatch
@path = (options[:path] || @name).to_s
@controller = (options[:controller] || @name).to_s
@as = options[:as]
- @param = options[:param] || :id
+ @param = (options[:param] || :id).to_sym
@options = options
end
@@ -961,12 +969,18 @@ module ActionDispatch
"#{path}/:#{param}"
end
+ alias :shallow_scope :member_scope
+
def new_scope(new_path)
"#{path}/#{new_path}"
end
+ def nested_param
+ :"#{singular}_#{param}"
+ end
+
def nested_scope
- "#{path}/:#{singular}_#{param}"
+ "#{path}/:#{nested_param}"
end
end
@@ -1033,6 +1047,8 @@ module ActionDispatch
resource_scope(:resource, SingletonResource.new(resources.pop, options)) do
yield if block_given?
+ concerns(options[:concerns]) if options[:concerns]
+
collection do
post :create
end if parent_resource.actions.include?(:create)
@@ -1176,6 +1192,10 @@ module ActionDispatch
# sekret_comment PATCH/PUT /comments/:id(.:format)
# sekret_comment DELETE /comments/:id(.:format)
#
+ # [:format]
+ # Allows you to specify the default value for optional +format+
+ # segment or disable it by supplying +false+.
+ #
# === Examples
#
# # routes call <tt>Admin::PostsController</tt>
@@ -1193,6 +1213,8 @@ module ActionDispatch
resource_scope(:resources, Resource.new(resources.pop, options)) do
yield if block_given?
+ concerns(options[:concerns]) if options[:concerns]
+
collection do
get :index if parent_resource.actions.include?(:index)
post :create if parent_resource.actions.include?(:create)
@@ -1316,22 +1338,6 @@ module ActionDispatch
parent_resource.instance_of?(Resource) && @scope[:shallow]
end
- def draw(name)
- path = @draw_paths.find do |_path|
- File.exists? "#{_path}/#{name}.rb"
- end
-
- unless path
- msg = "Your router tried to #draw the external file #{name}.rb,\n" \
- "but the file was not found in:\n\n"
- msg += @draw_paths.map { |_path| " * #{_path}" }.join("\n")
- raise ArgumentError, msg
- end
-
- route_path = "#{path}/#{name}.rb"
- instance_eval(File.read(route_path), route_path.to_s)
- end
-
# match 'path' => 'controller#action'
# match 'path', to: 'controller#action'
# match 'path', 'otherpath', on: :member, via: :get
@@ -1387,7 +1393,7 @@ module ActionDispatch
options[:as] = name_for_action(options[:as], action)
end
- mapping = Mapping.new(@set, @scope, path, options)
+ mapping = Mapping.new(@set, @scope, URI.parser.escape(path), options)
app, conditions, requirements, defaults, as, anchor = mapping.to_route
@set.add_route(app, conditions, requirements, defaults, as, anchor)
end
@@ -1493,18 +1499,18 @@ module ActionDispatch
def nested_options #:nodoc:
options = { :as => parent_resource.member_name }
options[:constraints] = {
- :"#{parent_resource.singular}_id" => id_constraint
- } if id_constraint?
+ parent_resource.nested_param => param_constraint
+ } if param_constraint?
options
end
- def id_constraint? #:nodoc:
- @scope[:constraints] && @scope[:constraints][:id].is_a?(Regexp)
+ def param_constraint? #:nodoc:
+ @scope[:constraints] && @scope[:constraints][parent_resource.param].is_a?(Regexp)
end
- def id_constraint #:nodoc:
- @scope[:constraints][:id]
+ def param_constraint #:nodoc:
+ @scope[:constraints][parent_resource.param]
end
def canonical_action?(action, flag) #:nodoc:
@@ -1517,7 +1523,7 @@ module ActionDispatch
def path_for_action(action, path) #:nodoc:
prefix = shallow_scoping? ?
- "#{@scope[:shallow_path]}/#{parent_resource.path}/:id" : @scope[:path]
+ "#{@scope[:shallow_path]}/#{parent_resource.shallow_scope}" : @scope[:path]
if canonical_action?(action, path.blank?)
prefix.to_s
@@ -1579,16 +1585,71 @@ module ActionDispatch
end
end
+ # Routing Concerns allows you to declare common routes that can be reused
+ # inside others resources and routes.
+ #
+ # concern :commentable do
+ # resources :comments
+ # end
+ #
+ # concern :image_attachable do
+ # resources :images, only: :index
+ # end
+ #
+ # These concerns are used in Resources routing:
+ #
+ # resources :messages, concerns: [:commentable, :image_attachable]
+ #
+ # or in a scope or namespace:
+ #
+ # namespace :posts do
+ # concerns :commentable
+ # end
+ module Concerns
+ # Define a routing concern using a name.
+ #
+ # concern :commentable do
+ # resources :comments
+ # end
+ #
+ # Any routing helpers can be used inside a concern.
+ def concern(name, &block)
+ @concerns[name] = block
+ end
+
+ # Use the named concerns
+ #
+ # resources :posts do
+ # concerns :commentable
+ # end
+ #
+ # concerns also work in any routes helper that you want to use:
+ #
+ # namespace :posts do
+ # concerns :commentable
+ # end
+ def concerns(*names)
+ names.flatten.each do |name|
+ if concern = @concerns[name]
+ instance_eval(&concern)
+ else
+ raise ArgumentError, "No concern named #{name} was found!"
+ end
+ end
+ end
+ end
+
def initialize(set) #:nodoc:
@set = set
- @draw_paths = set.draw_paths
@scope = { :path_names => @set.resources_path_names }
+ @concerns = {}
end
include Base
include HttpHelpers
include Redirection
include Scoping
+ include Concerns
include Resources
end
end
diff --git a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
index 8fde667108..3d7b8878b8 100644
--- a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
+++ b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
@@ -1,3 +1,5 @@
+require 'action_controller/model_naming'
+
module ActionDispatch
module Routing
# Polymorphic URL helpers are methods for smart resolution to a named route call when
@@ -53,6 +55,8 @@ module ActionDispatch
# form_for([blog, @post]) # => "/blog/posts/1"
#
module PolymorphicRoutes
+ include ActionController::ModelNaming
+
# Constructs a call to a named RESTful route for the given record and returns the
# resulting URL string. For example:
#
@@ -95,7 +99,7 @@ module ActionDispatch
end
record = extract_record(record_or_hash_or_array)
- record = record.to_model if record.respond_to?(:to_model)
+ record = convert_to_model(record)
args = Array === record_or_hash_or_array ?
record_or_hash_or_array.dup :
@@ -122,6 +126,8 @@ module ActionDispatch
args.last.kind_of?(Hash) ? args.last.merge!(url_options) : args << url_options
end
+ args.collect! { |a| convert_to_model(a) }
+
(proxy || self).send(named_route, *args)
end
@@ -163,7 +169,7 @@ module ActionDispatch
if parent.is_a?(Symbol) || parent.is_a?(String)
parent
else
- ActiveModel::Naming.singular_route_key(parent)
+ model_name_from_record_or_class(parent).singular_route_key
end
end
else
@@ -175,9 +181,9 @@ module ActionDispatch
route << record
elsif record
if inflection == :singular
- route << ActiveModel::Naming.singular_route_key(record)
+ route << model_name_from_record_or_class(record).singular_route_key
else
- route << ActiveModel::Naming.route_key(record)
+ route << model_name_from_record_or_class(record).route_key
end
else
raise ArgumentError, "Nil location provided. Can't build URI."
diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb
index 7872f4007e..32d267d1d6 100644
--- a/actionpack/lib/action_dispatch/routing/route_set.rb
+++ b/actionpack/lib/action_dispatch/routing/route_set.rb
@@ -1,6 +1,5 @@
require 'journey'
require 'forwardable'
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/object/to_query'
require 'active_support/core_ext/hash/slice'
require 'active_support/core_ext/module/remove_method'
@@ -162,19 +161,12 @@ module ActionDispatch
end
private
- def url_helper_name(name, only_path)
- if only_path
- :"#{name}_path"
- else
- :"#{name}_url"
- end
- end
def define_named_route_methods(name, route)
- [true, false].each do |only_path|
- hash = route.defaults.merge(:use_route => name, :only_path => only_path)
- define_url_helper route, name, hash
- end
+ define_url_helper route, :"#{name}_path",
+ route.defaults.merge(:use_route => name, :only_path => true)
+ define_url_helper route, :"#{name}_url",
+ route.defaults.merge(:use_route => name, :only_path => false)
end
# Create a url helper allowing ordered parameters to be associated
@@ -191,11 +183,9 @@ module ActionDispatch
# foo_url(bar, baz, bang, :sort_by => 'baz')
#
def define_url_helper(route, name, options)
- selector = url_helper_name(name, options[:only_path])
-
@module.module_eval <<-END_EVAL, __FILE__, __LINE__ + 1
- remove_possible_method :#{selector}
- def #{selector}(*args)
+ remove_possible_method :#{name}
+ def #{name}(*args)
if #{optimize_helper?(route)} && args.size == #{route.required_parts.size} && !args.last.is_a?(Hash) && optimize_routes_generation?
options = #{options.inspect}
options.merge!(url_options) if respond_to?(:url_options)
@@ -207,7 +197,7 @@ module ActionDispatch
end
END_EVAL
- helpers << selector
+ helpers << name
end
# Clause check about when we need to generate an optimized helper.
@@ -236,8 +226,7 @@ module ActionDispatch
attr_accessor :formatter, :set, :named_routes, :default_scope, :router
attr_accessor :disable_clear_and_finalize, :resources_path_names
- attr_accessor :default_url_options, :request_class, :valid_conditions
- attr_accessor :draw_paths
+ attr_accessor :default_url_options, :request_class
alias :routes :set
@@ -249,18 +238,7 @@ module ActionDispatch
self.named_routes = NamedRouteCollection.new
self.resources_path_names = self.class.default_resources_path_names.dup
self.default_url_options = {}
- self.draw_paths = []
-
self.request_class = request_class
- @valid_conditions = {}
-
- request_class.public_instance_methods.each { |m|
- @valid_conditions[m.to_sym] = true
- }
- @valid_conditions[:controller] = true
- @valid_conditions[:action] = true
-
- self.valid_conditions.delete(:id)
@append = []
@prepend = []
@@ -339,7 +317,7 @@ module ActionDispatch
end
end
- MountedHelpers.class_eval <<-RUBY
+ MountedHelpers.class_eval(<<-RUBY, __FILE__, __LINE__ + 1)
def #{name}
@#{name} ||= _#{name}
end
@@ -391,7 +369,7 @@ module ActionDispatch
raise ArgumentError, "Invalid route name: '#{name}'" unless name.blank? || name.to_s.match(/^[_a-z]\w*$/i)
path = build_path(conditions.delete(:path_info), requirements, SEPARATORS, anchor)
- conditions = build_conditions(conditions, valid_conditions, path.names.map { |x| x.to_sym })
+ conditions = build_conditions(conditions, path.names.map { |x| x.to_sym })
route = @set.add_route(app, path, conditions, defaults, name)
named_routes[name] = route if name && !named_routes[name]
@@ -428,21 +406,22 @@ module ActionDispatch
end
private :build_path
- def build_conditions(current_conditions, req_predicates, path_values)
+ def build_conditions(current_conditions, path_values)
conditions = current_conditions.dup
- verbs = conditions[:request_method] || []
-
# Rack-Mount requires that :request_method be a regular expression.
# :request_method represents the HTTP verb that matches this route.
#
# Here we munge values before they get sent on to rack-mount.
+ verbs = conditions[:request_method] || []
unless verbs.empty?
conditions[:request_method] = %r[^#{verbs.join('|')}$]
end
- conditions.delete_if { |k,v| !(req_predicates.include?(k) || path_values.include?(k)) }
- conditions
+ conditions.keep_if do |k, _|
+ k == :action || k == :controller ||
+ @request_class.public_method_defined?(k) || path_values.include?(k)
+ end
end
private :build_conditions
@@ -483,9 +462,7 @@ module ActionDispatch
def use_recall_for(key)
if @recall[key] && (!@options.key?(key) || @options[key] == @recall[key])
- if named_route_exists?
- @options[key] = @recall.delete(key) if segment_keys.include?(key)
- else
+ if !named_route_exists? || segment_keys.include?(key)
@options[key] = @recall.delete(key)
end
end
@@ -595,7 +572,8 @@ module ActionDispatch
end
RESERVED_OPTIONS = [:host, :protocol, :port, :subdomain, :domain, :tld_length,
- :trailing_slash, :anchor, :params, :only_path, :script_name]
+ :trailing_slash, :anchor, :params, :only_path, :script_name,
+ :original_script_name]
def mounted?
false
@@ -614,13 +592,19 @@ module ActionDispatch
options = default_url_options.merge(options || {})
user, password = extract_authentication(options)
- path_segments = options.delete(:_path_segments)
- script_name = options.delete(:script_name).presence || _generate_prefix(options)
+ recall = options.delete(:_recall)
+
+ original_script_name = options.delete(:original_script_name).presence
+ script_name = options.delete(:script_name).presence || _generate_prefix(options)
+
+ if script_name && original_script_name
+ script_name = original_script_name + script_name
+ end
path_options = options.except(*RESERVED_OPTIONS)
path_options = yield(path_options) if block_given?
- path, params = generate(path_options, path_segments || {})
+ path, params = generate(path_options, recall || {})
params.merge!(options[:params] || {})
ActionDispatch::Http::URL.url_for(options.merge!({
diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb
index fd3bed7e8f..f4c708ea33 100644
--- a/actionpack/lib/action_dispatch/routing/url_for.rb
+++ b/actionpack/lib/action_dispatch/routing/url_for.rb
@@ -102,7 +102,7 @@ module ActionDispatch
super
end
- # Hook overriden in controller to add request information
+ # Hook overridden in controller to add request information
# with `default_url_options`. Application logic should not
# go into url_options.
def url_options
diff --git a/actionpack/lib/action_dispatch/testing/assertions/response.rb b/actionpack/lib/action_dispatch/testing/assertions/response.rb
index b4c8f839ac..b15e0446de 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/response.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/response.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/inclusion'
module ActionDispatch
module Assertions
diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb
index 41fa3a4b95..9de545b3c5 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb
@@ -127,16 +127,13 @@ module ActionDispatch
# with a new RouteSet instance.
#
# The new instance is yielded to the passed block. Typically the block
- # will create some routes using <tt>map.draw { map.connect ... }</tt>:
+ # will create some routes using <tt>set.draw { match ... }</tt>:
#
# with_routing do |set|
- # set.draw do |map|
- # map.connect ':controller/:action/:id'
- # assert_equal(
- # ['/content/10/show', {}],
- # map.generate(:controller => 'content', :id => 10, :action => 'show')
- # end
+ # set.draw do
+ # resources :users
# end
+ # assert_equal "/users", users_path
# end
#
def with_routing
diff --git a/actionpack/lib/action_dispatch/testing/assertions/selector.rb b/actionpack/lib/action_dispatch/testing/assertions/selector.rb
index 5f9c3bbf48..d19d116a1f 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/selector.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/selector.rb
@@ -1,5 +1,4 @@
require 'action_controller/vendor/html-scanner'
-require 'active_support/core_ext/object/inclusion'
#--
# Copyright (c) 2006 Assaf Arkin (http://labnotes.org)
diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb
index 3fdc6688c2..ab584abf68 100644
--- a/actionpack/lib/action_dispatch/testing/integration.rb
+++ b/actionpack/lib/action_dispatch/testing/integration.rb
@@ -1,7 +1,6 @@
require 'stringio'
require 'uri'
require 'active_support/core_ext/kernel/singleton_class'
-require 'active_support/core_ext/object/inclusion'
require 'active_support/core_ext/object/try'
require 'rack/test'
@@ -193,8 +192,11 @@ module ActionDispatch
# If the app is a Rails app, make url_helpers available on the session
# This makes app.url_for and app.foo_path available in the console
- if app.respond_to?(:routes) && app.routes.respond_to?(:url_helpers)
- singleton_class.class_eval { include app.routes.url_helpers }
+ if app.respond_to?(:routes)
+ singleton_class.class_eval do
+ include app.routes.url_helpers if app.routes.respond_to?(:url_helpers)
+ include app.routes.mounted_helpers if app.routes.respond_to?(:mounted_helpers)
+ end
end
reset!
@@ -343,7 +345,7 @@ module ActionDispatch
define_method(method) do |*args|
reset! unless integration_session
# reset the html_document variable, but only for new get/post calls
- @html_document = nil unless method.in?(["cookies", "assigns"])
+ @html_document = nil unless method == 'cookies' || method == 'assigns'
integration_session.__send__(method, *args).tap do
copy_session_variables!
end
diff --git a/actionpack/lib/action_dispatch/testing/test_request.rb b/actionpack/lib/action_dispatch/testing/test_request.rb
index a86b510719..c63778f870 100644
--- a/actionpack/lib/action_dispatch/testing/test_request.rb
+++ b/actionpack/lib/action_dispatch/testing/test_request.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/hash/indifferent_access'
require 'rack/utils'
@@ -12,7 +11,7 @@ module ActionDispatch
def initialize(env = {})
env = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application
- super(DEFAULT_ENV.merge(env))
+ super(default_env.merge(env))
self.host = 'test.host'
self.remote_addr = '0.0.0.0'
@@ -69,5 +68,11 @@ module ActionDispatch
def cookies
@cookies ||= {}.with_indifferent_access
end
+
+ private
+
+ def default_env
+ DEFAULT_ENV
+ end
end
end
diff --git a/actionpack/lib/action_view.rb b/actionpack/lib/action_view.rb
index 3823f87027..4bd72c5520 100644
--- a/actionpack/lib/action_view.rb
+++ b/actionpack/lib/action_view.rb
@@ -22,6 +22,7 @@
#++
require 'active_support'
+require 'active_support/rails'
require 'action_pack'
module ActionView
@@ -36,7 +37,7 @@ module ActionView
autoload :LookupContext
autoload :PathSet
autoload :Template
- autoload :TestCase
+
autoload_under "renderer" do
autoload :Renderer
@@ -73,6 +74,8 @@ module ActionView
end
end
+ autoload :TestCase
+
ENCODING_FLAG = '#.*coding[:=]\s*(\S+)[ \t]*'
end
diff --git a/actionpack/lib/action_view/asset_paths.rb b/actionpack/lib/action_view/asset_paths.rb
index 4ce41d51f1..81880d17ea 100644
--- a/actionpack/lib/action_view/asset_paths.rb
+++ b/actionpack/lib/action_view/asset_paths.rb
@@ -35,7 +35,13 @@ module ActionView
# Return the filesystem path for the source
def compute_source_path(source, dir, ext)
source = rewrite_extension(source, dir, ext) if ext
- File.join(config.assets_dir, dir, source)
+
+ sources = []
+ sources << config.assets_dir
+ sources << dir unless source[0] == ?/
+ sources << source
+
+ File.join(sources)
end
def is_uri?(path)
diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb
index f98648d930..749332eca7 100644
--- a/actionpack/lib/action_view/base.rb
+++ b/actionpack/lib/action_view/base.rb
@@ -1,6 +1,4 @@
require 'active_support/core_ext/module/attr_internal'
-require 'active_support/core_ext/module/delegation'
-require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/class/attribute_accessors'
require 'active_support/ordered_options'
require 'action_view/log_subscriber'
@@ -148,7 +146,6 @@ module ActionView #:nodoc:
cattr_accessor :prefix_partial_path_with_controller_namespace
@@prefix_partial_path_with_controller_namespace = true
- class_attribute :helpers
class_attribute :_routes
class_attribute :logger
@@ -166,22 +163,6 @@ module ActionView #:nodoc:
def xss_safe? #:nodoc:
true
end
-
- # This method receives routes and helpers from the controller
- # and return a subclass ready to be used as view context.
- def prepare(routes, helpers) #:nodoc:
- Class.new(self) do
- if routes
- include routes.url_helpers
- include routes.mounted_helpers
- end
-
- if helpers
- include helpers
- self.helpers = helpers
- end
- end
- end
end
attr_accessor :view_renderer
diff --git a/actionpack/lib/action_view/context.rb b/actionpack/lib/action_view/context.rb
index 245849d706..ee263df484 100644
--- a/actionpack/lib/action_view/context.rb
+++ b/actionpack/lib/action_view/context.rb
@@ -26,11 +26,11 @@ module ActionView
# Encapsulates the interaction with the view flow so it
# returns the correct buffer on +yield+. This is usually
- # overwriten by helpers to add more behavior.
+ # overwritten by helpers to add more behavior.
# :api: plugin
def _layout_for(name=nil)
name ||= :layout
view_flow.get(name).html_safe
end
end
-end \ No newline at end of file
+end
diff --git a/actionpack/lib/action_view/helpers/active_model_helper.rb b/actionpack/lib/action_view/helpers/active_model_helper.rb
index e27111012d..901f433c70 100644
--- a/actionpack/lib/action_view/helpers/active_model_helper.rb
+++ b/actionpack/lib/action_view/helpers/active_model_helper.rb
@@ -1,6 +1,5 @@
require 'active_support/core_ext/class/attribute_accessors'
require 'active_support/core_ext/enumerable'
-require 'active_support/core_ext/object/blank'
module ActionView
# = Active Model Helpers
diff --git a/actionpack/lib/action_view/helpers/asset_tag_helper.rb b/actionpack/lib/action_view/helpers/asset_tag_helper.rb
index 02c1250c76..ceb56824fa 100644
--- a/actionpack/lib/action_view/helpers/asset_tag_helper.rb
+++ b/actionpack/lib/action_view/helpers/asset_tag_helper.rb
@@ -95,7 +95,7 @@ module ActionView
# have SSL certificates for each of the asset hosts this technique allows you
# to avoid warnings in the client about mixed media.
#
- # ActionController::Base.asset_host = Proc.new { |source, request|
+ # config.action_controller.asset_host = Proc.new { |source, request|
# if request.ssl?
# "#{request.protocol}#{request.host_with_port}"
# else
@@ -209,18 +209,18 @@ module ActionView
# * <tt>:title</tt> - Specify the title of the link, defaults to the +type+
#
# ==== Examples
- # auto_discovery_link_tag # =>
- # <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/action" />
- # auto_discovery_link_tag(:atom) # =>
- # <link rel="alternate" type="application/atom+xml" title="ATOM" href="http://www.currenthost.com/controller/action" />
- # auto_discovery_link_tag(:rss, {:action => "feed"}) # =>
- # <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/feed" />
- # auto_discovery_link_tag(:rss, {:action => "feed"}, {:title => "My RSS"}) # =>
- # <link rel="alternate" type="application/rss+xml" title="My RSS" href="http://www.currenthost.com/controller/feed" />
- # auto_discovery_link_tag(:rss, {:controller => "news", :action => "feed"}) # =>
- # <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/news/feed" />
- # auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {:title => "Example RSS"}) # =>
- # <link rel="alternate" type="application/rss+xml" title="Example RSS" href="http://www.example.com/feed" />
+ # auto_discovery_link_tag
+ # # => <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/action" />
+ # auto_discovery_link_tag(:atom)
+ # # => <link rel="alternate" type="application/atom+xml" title="ATOM" href="http://www.currenthost.com/controller/action" />
+ # auto_discovery_link_tag(:rss, {:action => "feed"})
+ # # => <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/controller/feed" />
+ # auto_discovery_link_tag(:rss, {:action => "feed"}, {:title => "My RSS"})
+ # # => <link rel="alternate" type="application/rss+xml" title="My RSS" href="http://www.currenthost.com/controller/feed" />
+ # auto_discovery_link_tag(:rss, {:controller => "news", :action => "feed"})
+ # # => <link rel="alternate" type="application/rss+xml" title="RSS" href="http://www.currenthost.com/news/feed" />
+ # auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {:title => "Example RSS"})
+ # # => <link rel="alternate" type="application/rss+xml" title="Example RSS" href="http://www.example.com/feed" />
def auto_discovery_link_tag(type = :rss, url_options = {}, tag_options = {})
tag(
"link",
@@ -360,18 +360,18 @@ module ActionView
# width="30" and height="45". <tt>:size</tt> will be ignored if the
# value is not in the correct format.
#
- # image_tag("icon") # =>
- # <img src="/assets/icon" alt="Icon" />
- # image_tag("icon.png") # =>
- # <img src="/assets/icon.png" alt="Icon" />
- # image_tag("icon.png", :size => "16x10", :alt => "Edit Entry") # =>
- # <img src="/assets/icon.png" width="16" height="10" alt="Edit Entry" />
- # image_tag("/icons/icon.gif", :size => "16x16") # =>
- # <img src="/icons/icon.gif" width="16" height="16" alt="Icon" />
- # image_tag("/icons/icon.gif", :height => '32', :width => '32') # =>
- # <img alt="Icon" height="32" src="/icons/icon.gif" width="32" />
- # image_tag("/icons/icon.gif", :class => "menu_icon") # =>
- # <img alt="Icon" class="menu_icon" src="/icons/icon.gif" />
+ # image_tag("icon")
+ # # => <img src="/assets/icon" alt="Icon" />
+ # image_tag("icon.png")
+ # # => <img src="/assets/icon.png" alt="Icon" />
+ # image_tag("icon.png", :size => "16x10", :alt => "Edit Entry")
+ # # => <img src="/assets/icon.png" width="16" height="10" alt="Edit Entry" />
+ # image_tag("/icons/icon.gif", :size => "16x16")
+ # # => <img src="/icons/icon.gif" width="16" height="16" alt="Icon" />
+ # image_tag("/icons/icon.gif", :height => '32', :width => '32')
+ # # => <img alt="Icon" height="32" src="/icons/icon.gif" width="32" />
+ # image_tag("/icons/icon.gif", :class => "menu_icon")
+ # # => <img alt="Icon" class="menu_icon" src="/icons/icon.gif" />
def image_tag(source, options={})
options = options.symbolize_keys
@@ -408,24 +408,24 @@ module ActionView
# width="30" and height="45". <tt>:size</tt> will be ignored if the
# value is not in the correct format.
#
- # video_tag("trailer") # =>
- # <video src="/videos/trailer" />
- # video_tag("trailer.ogg") # =>
- # <video src="/videos/trailer.ogg" />
- # video_tag("trailer.ogg", :controls => true, :autobuffer => true) # =>
- # <video autobuffer="autobuffer" controls="controls" src="/videos/trailer.ogg" />
- # video_tag("trailer.m4v", :size => "16x10", :poster => "screenshot.png") # =>
- # <video src="/videos/trailer.m4v" width="16" height="10" poster="/assets/screenshot.png" />
- # video_tag("/trailers/hd.avi", :size => "16x16") # =>
- # <video src="/trailers/hd.avi" width="16" height="16" />
- # video_tag("/trailers/hd.avi", :height => '32', :width => '32') # =>
- # <video height="32" src="/trailers/hd.avi" width="32" />
- # video_tag("trailer.ogg", "trailer.flv") # =>
- # <video><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
- # video_tag(["trailer.ogg", "trailer.flv"]) # =>
- # <video><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
- # video_tag(["trailer.ogg", "trailer.flv"], :size => "160x120") # =>
- # <video height="120" width="160"><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
+ # video_tag("trailer")
+ # # => <video src="/videos/trailer" />
+ # video_tag("trailer.ogg")
+ # # => <video src="/videos/trailer.ogg" />
+ # video_tag("trailer.ogg", :controls => true, :autobuffer => true)
+ # # => <video autobuffer="autobuffer" controls="controls" src="/videos/trailer.ogg" />
+ # video_tag("trailer.m4v", :size => "16x10", :poster => "screenshot.png")
+ # # => <video src="/videos/trailer.m4v" width="16" height="10" poster="/assets/screenshot.png" />
+ # video_tag("/trailers/hd.avi", :size => "16x16")
+ # # => <video src="/trailers/hd.avi" width="16" height="16" />
+ # video_tag("/trailers/hd.avi", :height => '32', :width => '32')
+ # # => <video height="32" src="/trailers/hd.avi" width="32" />
+ # video_tag("trailer.ogg", "trailer.flv")
+ # # => <video><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
+ # video_tag(["trailer.ogg", "trailer.flv"])
+ # # => <video><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
+ # video_tag(["trailer.ogg", "trailer.flv"], :size => "160x120")
+ # # => <video height="120" width="160"><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
def video_tag(*sources)
multiple_sources_tag('video', sources) do |options|
options[:poster] = path_to_image(options[:poster]) if options[:poster]
diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb
index 05d5f1870a..e42e49fb04 100644
--- a/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb
+++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/string/inflections'
require 'active_support/core_ext/file'
require 'action_view/helpers/tag_helper'
@@ -7,7 +6,7 @@ module ActionView
module Helpers
module AssetTagHelper
- class AssetIncludeTag
+ class AssetIncludeTag #:nodoc:
include TagHelper
attr_reader :config, :asset_paths
diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb
index 4292d29f60..139f4d19ab 100644
--- a/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb
+++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb
@@ -1,4 +1,3 @@
-require 'active_support/concern'
require 'active_support/core_ext/file'
require 'action_view/helpers/asset_tag_helpers/asset_include_tag'
@@ -6,7 +5,7 @@ module ActionView
module Helpers
module AssetTagHelper
- class JavascriptIncludeTag < AssetIncludeTag
+ class JavascriptIncludeTag < AssetIncludeTag #:nodoc:
def asset_name
'javascript'
end
@@ -27,7 +26,8 @@ module ActionView
def expand_sources(sources, recursive = false)
if sources.include?(:all)
- all_asset_files = (collect_asset_files(custom_dir, ('**' if recursive), "*.#{extension}") - ['application']) << 'application'
+ all_asset_files = (collect_asset_files(custom_dir, ('**' if recursive), "*.#{extension}") - ['application'])
+ add_application_js(all_asset_files, sources)
((determine_source(:defaults, expansions).dup & all_asset_files) + all_asset_files).uniq
else
expanded_sources = sources.inject([]) do |list, source|
@@ -40,7 +40,7 @@ module ActionView
end
def add_application_js(expanded_sources, sources)
- if sources.include?(:defaults) && File.exist?(File.join(custom_dir, "application.#{extension}"))
+ if (sources.include?(:defaults) || sources.include?(:all)) && File.exist?(File.join(custom_dir, "application.#{extension}"))
expanded_sources.delete('application')
expanded_sources << "application"
end
@@ -107,8 +107,8 @@ module ActionView
#
# config.action_view.javascript_expansions[:defaults] = %w(foo.js bar.js)
#
- # When using <tt>:defaults</tt>, if an <tt>application.js</tt> file exists in
- # <tt>public/javascripts</tt> it will be included as well at the end.
+ # When using <tt>:defaults</tt> or <tt>:all</tt>, if an <tt>application.js</tt> file exists
+ # in <tt>public/javascripts</tt> it will be included as well at the end.
#
# You can modify the HTML attributes of the script tag by passing a hash as the
# last argument.
@@ -134,14 +134,16 @@ module ActionView
# # <script src="/javascripts/rails.js?1284139606"></script>
# # <script src="/javascripts/application.js?1284139606"></script>
#
+ # Note: The application.js file is only referenced if it exists
+ #
# You can also include all JavaScripts in the +javascripts+ directory using <tt>:all</tt> as the source:
#
# javascript_include_tag :all
# # => <script src="/javascripts/jquery.js?1284139606"></script>
# # <script src="/javascripts/rails.js?1284139606"></script>
- # # <script src="/javascripts/application.js?1284139606"></script>
# # <script src="/javascripts/shop.js?1284139606"></script>
# # <script src="/javascripts/checkout.js?1284139606"></script>
+ # # <script src="/javascripts/application.js?1284139606"></script>
#
# Note that your defaults of choice will be included first, so they will be available to all subsequently
# included files.
@@ -162,9 +164,9 @@ module ActionView
# javascript_include_tag :all, :cache => true
# # => <script src="/javascripts/jquery.js?1284139606"></script>
# # <script src="/javascripts/rails.js?1284139606"></script>
- # # <script src="/javascripts/application.js?1284139606"></script>
# # <script src="/javascripts/shop.js?1284139606"></script>
# # <script src="/javascripts/checkout.js?1284139606"></script>
+ # # <script src="/javascripts/application.js?1284139606"></script>
#
# # assuming config.perform_caching is true
# javascript_include_tag :all, :cache => true
diff --git a/actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb
index 57b0627225..e3a86a8889 100644
--- a/actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb
+++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb
@@ -1,4 +1,3 @@
-require 'active_support/concern'
require 'active_support/core_ext/file'
require 'action_view/helpers/asset_tag_helpers/asset_include_tag'
@@ -6,7 +5,7 @@ module ActionView
module Helpers
module AssetTagHelper
- class StylesheetIncludeTag < AssetIncludeTag
+ class StylesheetIncludeTag < AssetIncludeTag #:nodoc:
def asset_name
'stylesheet'
end
@@ -53,7 +52,7 @@ module ActionView
# If the +source+ filename has no extension, <tt>.css</tt> will be appended (except for explicit URIs).
# Full paths from the document root will be passed through.
# Used internally by +stylesheet_link_tag+ to build the stylesheet path.
- #
+ #
# stylesheet_path "style" # => /stylesheets/style.css
# stylesheet_path "dir/style.css" # => /stylesheets/dir/style.css
# stylesheet_path "/dir/style.css" # => /dir/style.css
diff --git a/actionpack/lib/action_view/helpers/cache_helper.rb b/actionpack/lib/action_view/helpers/cache_helper.rb
index 33799d7d71..39518268df 100644
--- a/actionpack/lib/action_view/helpers/cache_helper.rb
+++ b/actionpack/lib/action_view/helpers/cache_helper.rb
@@ -8,28 +8,28 @@ module ActionView
# fragments, and so on. This method takes a block that contains
# the content you wish to cache.
#
- # See ActionController::Caching::Fragments for usage instructions.
+ # The best way to use this is by doing key-based cache expiration
+ # on top of a cache store like Memcached that'll automatically
+ # kick out old entries. For more on key-based expiration, see:
+ # http://37signals.com/svn/posts/3113-how-key-based-cache-expiration-works
#
- # If you want to cache a navigation menu, you can do following:
+ # When using this method, you list the cache dependencies as part of
+ # the name of the cache, like so:
#
- # <% cache do %>
- # <%= render :partial => "menu" %>
+ # <% cache [ "v1", project ] do %>
+ # <b>All the topics on this project</b>
+ # <%= render project.topics %>
# <% end %>
#
- # You can also cache static content:
+ # This approach will assume that when a new topic is added, you'll touch
+ # the project. The cache key generated from this call will be something like:
#
- # <% cache do %>
- # <p>Hello users! Welcome to our website!</p>
- # <% end %>
- #
- # Static content with embedded ruby content can be cached as
- # well:
+ # views/v1/projects/123-20120806214154
+ # ^class ^id ^updated_at
#
- # <% cache do %>
- # Topics:
- # <%= render :partial => "topics", :collection => @topic_list %>
- # <i>Topics listed alphabetically</i>
- # <% end %>
+ # If you update the rendering of topics, you just bump the version to v2.
+ # Otherwise the cache is automatically bumped whenever the project updated_at
+ # is touched.
def cache(name = {}, options = nil, &block)
if controller.perform_caching
safe_concat(fragment_for(name, options, &block))
diff --git a/actionpack/lib/action_view/helpers/capture_helper.rb b/actionpack/lib/action_view/helpers/capture_helper.rb
index 397738dd98..c98101a195 100644
--- a/actionpack/lib/action_view/helpers/capture_helper.rb
+++ b/actionpack/lib/action_view/helpers/capture_helper.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/string/output_safety'
module ActionView
@@ -134,7 +133,7 @@ module ActionView
#
# <%# Add some other content, or use a different template: %>
#
- # <% content_for :navigation, true do %>
+ # <% content_for :navigation, flush: true do %>
# <li><%= link_to 'Login', :action => 'login' %></li>
# <% end %>
#
@@ -148,14 +147,14 @@ module ActionView
#
# WARNING: content_for is ignored in caches. So you shouldn't use it
# for elements that will be fragment cached.
- def content_for(name, content = nil, flush = false, &block)
+ def content_for(name, content = nil, options = {}, &block)
if content || block_given?
if block_given?
- flush = content if content
+ options = content if content
content = capture(&block)
end
if content
- flush ? @view_flow.set(name, content) : @view_flow.append(name, content)
+ options[:flush] ? @view_flow.set(name, content) : @view_flow.append(name, content)
end
nil
else
@@ -213,7 +212,7 @@ module ActionView
# Add the output buffer to the response body and start a new one.
def flush_output_buffer #:nodoc:
if output_buffer && !output_buffer.empty?
- response.body_parts << output_buffer
+ response.stream.write output_buffer
self.output_buffer = output_buffer.respond_to?(:clone_empty) ? output_buffer.clone_empty : output_buffer[0, 0]
nil
end
diff --git a/actionpack/lib/action_view/helpers/controller_helper.rb b/actionpack/lib/action_view/helpers/controller_helper.rb
index 1a583e62ae..74ef25f7c1 100644
--- a/actionpack/lib/action_view/helpers/controller_helper.rb
+++ b/actionpack/lib/action_view/helpers/controller_helper.rb
@@ -10,14 +10,16 @@ module ActionView
delegate :request_forgery_protection_token, :params, :session, :cookies, :response, :headers,
:flash, :action_name, :controller_name, :controller_path, :to => :controller
- delegate :logger, :to => :controller, :allow_nil => true
-
def assign_controller(controller)
if @_controller = controller
@_request = controller.request if controller.respond_to?(:request)
@_config = controller.config.inheritable_copy if controller.respond_to?(:config)
end
end
+
+ def logger
+ controller.logger if controller.respond_to?(:logger)
+ end
end
end
end
diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb
index 659aacf6d7..dea2aa69dd 100644
--- a/actionpack/lib/action_view/helpers/date_helper.rb
+++ b/actionpack/lib/action_view/helpers/date_helper.rb
@@ -427,6 +427,9 @@ module ActionView
# # Generate a time select field with hours in the AM/PM format
# select_time(my_time, :ampm => true)
#
+ # # Generates a time select field with hours that range from 2 to 14
+ # select_time(my_time, :start_hour => 2, :end_hour => 14)
+ #
# # Generates a time select with a custom prompt. Use <tt>:prompt</tt> to true for generic prompts.
# select_time(my_time, :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'})
# select_time(my_time, :prompt => {:hour => true}) # generic prompt for hours
@@ -504,6 +507,9 @@ module ActionView
#
# # Generate a select field for hours in the AM/PM format
# select_hour(my_time, :ampm => true)
+ #
+ # # Generates a select field that includes options for hours from 2 to 14.
+ # select_hour(my_time, :start_hour => 2, :end_hour => 14)
def select_hour(datetime, options = {}, html_options = {})
DateTimeSelector.new(datetime, options, html_options).select_hour
end
@@ -734,7 +740,11 @@ module ActionView
if @options[:use_hidden] || @options[:discard_hour]
build_hidden(:hour, hour)
else
- build_options_and_select(:hour, hour, :end => 23, :ampm => @options[:ampm])
+ options = {}
+ options[:ampm] = @options[:ampm] || false
+ options[:start] = @options[:start_hour] || 0
+ options[:end] = @options[:end_hour] || 23
+ build_options_and_select(:hour, hour, options)
end
end
diff --git a/actionpack/lib/action_view/helpers/debug_helper.rb b/actionpack/lib/action_view/helpers/debug_helper.rb
index 878a8734a4..d8b92c5cab 100644
--- a/actionpack/lib/action_view/helpers/debug_helper.rb
+++ b/actionpack/lib/action_view/helpers/debug_helper.rb
@@ -4,6 +4,9 @@ module ActionView
# Provides a set of methods for making it easier to debug Rails objects.
module Helpers
module DebugHelper
+
+ include TagHelper
+
# Returns a YAML representation of +object+ wrapped with <pre> and </pre>.
# If the object cannot be converted to YAML using +to_yaml+, +inspect+ will be called instead.
# Useful for inspecting an object at the time of rendering.
@@ -26,10 +29,11 @@ module ActionView
def debug(object)
begin
Marshal::dump(object)
- "<pre class='debug_dump'>#{h(object.to_yaml).gsub(" ", "&nbsp; ")}</pre>".html_safe
+ object = ERB::Util.html_escape(object.to_yaml).gsub(" ", "&nbsp; ").html_safe
+ content_tag(:pre, object, :class => "debug_dump")
rescue Exception # errors from Marshal or YAML
# Object couldn't be dumped, perhaps because of singleton methods -- this is the fallback
- "<code class='debug_dump'>#{h(object.inspect)}</code>".html_safe
+ content_tag(:code, object.to_yaml, :class => "debug_dump")
end
end
end
diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb
index ac150882b1..b79577bcd3 100644
--- a/actionpack/lib/action_view/helpers/form_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_helper.rb
@@ -4,14 +4,12 @@ require 'action_view/helpers/tag_helper'
require 'action_view/helpers/form_tag_helper'
require 'action_view/helpers/active_model_helper'
require 'action_view/helpers/tags'
-require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/class/attribute_accessors'
require 'active_support/core_ext/hash/slice'
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/string/output_safety'
require 'active_support/core_ext/array/extract_options'
-require 'active_support/deprecation'
require 'active_support/core_ext/string/inflections'
+require 'action_controller/model_naming'
module ActionView
# = Action View Form Helpers
@@ -117,11 +115,7 @@ module ActionView
include FormTagHelper
include UrlHelper
-
- # Converts the given object to an ActiveModel compliant one.
- def convert_to_model(object)
- object.respond_to?(:to_model) ? object.to_model : object
- end
+ include ActionController::ModelNaming
# Creates a form that allows the user to create or update the attributes
# of a specific model object.
@@ -329,6 +323,24 @@ module ActionView
# ...
# </form>
#
+ # === Setting HTML options
+ #
+ # You can set data attributes directly by passing in a data hash, but all other HTML options must be wrapped in
+ # the HTML key. Example:
+ #
+ # <%= form_for(@post, data: { behavior: "autosave" }, html: { name: "go" }) do |f| %>
+ # ...
+ # <% end %>
+ #
+ # The HTML generated for this would be:
+ #
+ # <form action='http://www.example.com' method='post' data-behavior='autosave' name='go'>
+ # <div style='margin:0;padding:0;display:inline'>
+ # <input name='_method' type='hidden' value='put' />
+ # </div>
+ # ...
+ # </form>
+ #
# === Removing hidden model id's
#
# The form_for method automatically includes the model id as a hidden field in the form.
@@ -411,10 +423,12 @@ module ActionView
object = nil
else
object = record.is_a?(Array) ? record.last : record
- object_name = options[:as] || ActiveModel::Naming.param_key(object)
+ raise ArgumentError, "First argument in form cannot contain nil or be empty" if object.blank?
+ object_name = options[:as] || model_name_from_record_or_class(object).param_key
apply_form_for_options!(record, object, options)
end
+ options[:html][:data] = options.delete(:data) if options.has_key?(:data)
options[:html][:remote] = options.delete(:remote) if options.has_key?(:remote)
options[:html][:method] = options.delete(:method) if options.has_key?(:method)
options[:html][:authenticity_token] = options.delete(:authenticity_token)
@@ -706,15 +720,15 @@ module ActionView
# label(:post, :title)
# # => <label for="post_title">Title</label>
#
- # You can localize your labels based on model and attribute names.
- # For example you can define the following in your locale (e.g. en.yml)
+ # You can localize your labels based on model and attribute names.
+ # For example you can define the following in your locale (e.g. en.yml)
#
# helpers:
# label:
# post:
# body: "Write your entire text here"
#
- # Which then will result in
+ # Which then will result in
#
# label(:post, :body)
# # => <label for="post_body">Write your entire text here</label>
@@ -979,6 +993,7 @@ module ActionView
def telephone_field(object_name, method, options = {})
Tags::TelField.new(object_name, method, self, options).render
end
+ # aliases telephone_field
alias phone_field telephone_field
# Returns a text_field of type "date".
@@ -1127,7 +1142,7 @@ module ActionView
object_name = record_name
else
object = record_name
- object_name = ActiveModel::Naming.param_key(object)
+ object_name = model_name_from_record_or_class(object).param_key
end
builder = options[:builder] || default_form_builder
@@ -1141,9 +1156,11 @@ module ActionView
end
class FormBuilder
+ include ActionController::ModelNaming
+
# The methods which wrap a form helper call.
class_attribute :field_helpers
- self.field_helpers = FormHelper.instance_methods - [:form_for, :convert_to_model]
+ self.field_helpers = FormHelper.instance_methods - [:form_for, :convert_to_model, :model_name_from_record_or_class]
attr_accessor :object_name, :object, :options
@@ -1213,7 +1230,7 @@ module ActionView
end
else
record_object = record_name.is_a?(Array) ? record_name.last : record_name
- record_name = ActiveModel::Naming.param_key(record_object)
+ record_name = model_name_from_record_or_class(record_object).param_key
end
index = if options.has_key?(:index)
@@ -1311,10 +1328,21 @@ module ActionView
# post:
# create: "Add %{model}"
#
- def button(value=nil, options={})
+ # ==== Examples
+ # button("Create a post")
+ # # => <button name='button' type='submit'>Create post</button>
+ #
+ # button do
+ # content_tag(:strong, 'Ask me!')
+ # end
+ # # => <button name='button' type='submit'>
+ # # <strong>Ask me!</strong>
+ # # </button>
+ #
+ def button(value = nil, options = {}, &block)
value, options = nil, value if value.is_a?(Hash)
value ||= submit_default_value
- @template.button_tag(value, options)
+ @template.button_tag(value, options, &block)
end
def emitted_hidden_id?
@@ -1384,10 +1412,6 @@ module ActionView
@nested_child_index[name] ||= -1
@nested_child_index[name] += 1
end
-
- def convert_to_model(object)
- object.respond_to?(:to_model) ? object.to_model : object
- end
end
end
diff --git a/actionpack/lib/action_view/helpers/form_options_helper.rb b/actionpack/lib/action_view/helpers/form_options_helper.rb
index eef426703d..e4f4ebc7ff 100644
--- a/actionpack/lib/action_view/helpers/form_options_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_options_helper.rb
@@ -1,7 +1,6 @@
require 'cgi'
require 'erb'
require 'action_view/helpers/form_helper'
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/string/output_safety'
module ActionView
@@ -353,7 +352,7 @@ module ActionView
html_attributes[:disabled] = 'disabled' if disabled && option_value_selected?(value, disabled)
html_attributes[:value] = value
- content_tag(:option, text, html_attributes)
+ content_tag_string(:option, text, html_attributes)
end.join("\n").html_safe
end
@@ -709,9 +708,11 @@ module ActionView
private
def option_html_attributes(element)
- return {} unless Array === element
-
- Hash[element.select { |e| Hash === e }.reduce({}, :merge).map { |k, v| [k, ERB::Util.html_escape(v.to_s)] }]
+ if Array === element
+ element.select { |e| Hash === e }.reduce({}, :merge!)
+ else
+ {}
+ end
end
def option_text_and_value(option)
diff --git a/actionpack/lib/action_view/helpers/form_tag_helper.rb b/actionpack/lib/action_view/helpers/form_tag_helper.rb
index 1a0019a48c..ace457df2e 100644
--- a/actionpack/lib/action_view/helpers/form_tag_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_tag_helper.rb
@@ -1,13 +1,12 @@
require 'cgi'
require 'action_view/helpers/tag_helper'
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/string/output_safety'
require 'active_support/core_ext/module/attribute_accessors'
module ActionView
# = Action View Form Tag Helpers
module Helpers
- # Provides a number of methods for creating form tags that doesn't rely on an Active Record object assigned to the template like
+ # Provides a number of methods for creating form tags that don't rely on an Active Record object assigned to the template like
# FormHelper does. Instead, you provide the names and values manually.
#
# NOTE: The HTML options <tt>disabled</tt>, <tt>readonly</tt>, and <tt>multiple</tt> can all be treated as booleans. So specifying
@@ -119,6 +118,7 @@ module ActionView
# # => <select disabled="disabled" id="destination" name="destination"><option>NYC</option>
# # <option>Paris</option><option>Rome</option></select>
def select_tag(name, option_tags = nil, options = {})
+ option_tags ||= ""
html_name = (options[:multiple] == true && !name.to_s.ends_with?("[]")) ? "#{name}[]" : name
if options.delete(:include_blank)
@@ -382,11 +382,18 @@ module ActionView
# Creates a submit button with the text <tt>value</tt> as the caption.
#
# ==== Options
+ # * <tt>:data</tt> - This option can be used to add custom data attributes.
+ # * <tt>:disabled</tt> - If true, the user will not be able to use this input.
+ # * Any other key creates standard HTML options for the tag.
+ #
+ # ==== Data attributes
+ #
# * <tt>:confirm => 'question?'</tt> - If present the unobtrusive JavaScript
# drivers will provide a prompt with the question specified. If the user accepts,
# the form is processed normally, otherwise no action is taken.
- # * <tt>:disabled</tt> - If true, the user will not be able to use this input.
- # * Any other key creates standard HTML options for the tag.
+ # * <tt>:disable_with</tt> - Value of this parameter will be used as the value for a
+ # disabled version of the submit button when the form is submitted. This feature is
+ # provided by the unobtrusive JavaScript driver.
#
# ==== Examples
# submit_tag
@@ -407,13 +414,21 @@ module ActionView
# submit_tag "Edit", :class => "edit_button"
# # => <input class="edit_button" name="commit" type="submit" value="Edit" />
#
- # submit_tag "Save", :confirm => "Are you sure?"
+ # submit_tag "Save", :data => { :confirm => "Are you sure?" }
# # => <input name='commit' type='submit' value='Save' data-confirm="Are you sure?" />
#
def submit_tag(value = "Save changes", options = {})
options = options.stringify_keys
+ if disable_with = options.delete("disable_with")
+ ActiveSupport::Deprecation.warn ":disable_with option is deprecated and will be removed from Rails 4.1. Use ':data => { :disable_with => \'Text\' }' instead"
+
+ options["data-disable-with"] = disable_with
+ end
+
if confirm = options.delete("confirm")
+ ActiveSupport::Deprecation.warn ":confirm option is deprecated and will be removed from Rails 4.1. Use ':data => { :confirm => \'Text\' }' instead'"
+
options["data-confirm"] = confirm
end
@@ -428,13 +443,21 @@ module ActionView
# so this helper will also accept a block.
#
# ==== Options
+ # * <tt>:data</tt> - This option can be used to add custom data attributes.
+ # * <tt>:disabled</tt> - If true, the user will not be able to
+ # use this input.
+ # * Any other key creates standard HTML options for the tag.
+ #
+ # ==== Data attributes
+ #
# * <tt>:confirm => 'question?'</tt> - If present, the
# unobtrusive JavaScript drivers will provide a prompt with
# the question specified. If the user accepts, the form is
# processed normally, otherwise no action is taken.
- # * <tt>:disabled</tt> - If true, the user will not be able to
- # use this input.
- # * Any other key creates standard HTML options for the tag.
+ # * <tt>:disable_with</tt> - Value of this parameter will be
+ # used as the value for a disabled version of the submit
+ # button when the form is submitted. This feature is provided
+ # by the unobtrusive JavaScript driver.
#
# ==== Examples
# button_tag
@@ -447,12 +470,23 @@ module ActionView
# # <strong>Ask me!</strong>
# # </button>
#
+ # button_tag "Checkout", :data => { disable_with => "Please wait..." }
+ # # => <button data-disable-with="Please wait..." name="button" type="submit">Checkout</button>
+ #
def button_tag(content_or_options = nil, options = nil, &block)
options = content_or_options if block_given? && content_or_options.is_a?(Hash)
options ||= {}
options = options.stringify_keys
+ if disable_with = options.delete("disable_with")
+ ActiveSupport::Deprecation.warn ":disable_with option is deprecated and will be removed from Rails 4.1. Use ':data => { :disable_with => \'Text\' }' instead"
+
+ options["data-disable-with"] = disable_with
+ end
+
if confirm = options.delete("confirm")
+ ActiveSupport::Deprecation.warn ":confirm option is deprecated and will be removed from Rails 4.1. Use ':data => { :confirm => \'Text\' }' instead'"
+
options["data-confirm"] = confirm
end
@@ -466,11 +500,15 @@ module ActionView
# <tt>source</tt> is passed to AssetTagHelper#path_to_image
#
# ==== Options
+ # * <tt>:data</tt> - This option can be used to add custom data attributes.
+ # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
+ # * Any other key creates standard HTML options for the tag.
+ #
+ # ==== Data attributes
+ #
# * <tt>:confirm => 'question?'</tt> - This will add a JavaScript confirm
# prompt with the question specified. If the user accepts, the form is
# processed normally, otherwise no action is taken.
- # * <tt>:disabled</tt> - If set to true, the user will not be able to use this input.
- # * Any other key creates standard HTML options for the tag.
#
# ==== Examples
# image_submit_tag("login.png")
@@ -485,12 +523,14 @@ module ActionView
# image_submit_tag("agree.png", :disabled => true, :class => "agree_disagree_button")
# # => <input class="agree_disagree_button" disabled="disabled" src="/images/agree.png" type="image" />
#
- # image_submit_tag("save.png", :confirm => "Are you sure?")
+ # image_submit_tag("save.png", :data => { :confirm => "Are you sure?" })
# # => <input src="/images/save.png" data-confirm="Are you sure?" type="image" />
def image_submit_tag(source, options = {})
options = options.stringify_keys
if confirm = options.delete("confirm")
+ ActiveSupport::Deprecation.warn ":confirm option is deprecated and will be removed from Rails 4.1. Use ':data => { :confirm => \'Text\' }' instead'"
+
options["data-confirm"] = confirm
end
diff --git a/actionpack/lib/action_view/helpers/javascript_helper.rb b/actionpack/lib/action_view/helpers/javascript_helper.rb
index cc20518b93..9f8cd8caaa 100644
--- a/actionpack/lib/action_view/helpers/javascript_helper.rb
+++ b/actionpack/lib/action_view/helpers/javascript_helper.rb
@@ -67,6 +67,46 @@ module ActionView
def javascript_cdata_section(content) #:nodoc:
"\n//#{cdata_section("\n#{content}\n//")}\n".html_safe
end
+
+ # Returns a button whose +onclick+ handler triggers the passed JavaScript.
+ #
+ # The helper receives a name, JavaScript code, and an optional hash of HTML options. The
+ # name is used as button label and the JavaScript code goes into its +onclick+ attribute.
+ # If +html_options+ has an <tt>:onclick</tt>, that one is put before +function+.
+ #
+ # button_to_function "Greeting", "alert('Hello world!')", :class => "ok"
+ # # => <input class="ok" onclick="alert('Hello world!');" type="button" value="Greeting" />
+ #
+ def button_to_function(name, function=nil, html_options={})
+ message = "button_to_function is deprecated and will be removed from Rails 4.1. Use Unobtrusive JavaScript instead."
+ ActiveSupport::Deprecation.warn message
+
+ onclick = "#{"#{html_options[:onclick]}; " if html_options[:onclick]}#{function};"
+
+ tag(:input, html_options.merge(:type => 'button', :value => name, :onclick => onclick))
+ end
+
+ # Returns a link whose +onclick+ handler triggers the passed JavaScript.
+ #
+ # The helper receives a name, JavaScript code, and an optional hash of HTML options. The
+ # name is used as the link text and the JavaScript code goes into the +onclick+ attribute.
+ # If +html_options+ has an <tt>:onclick</tt>, that one is put before +function+. Once all
+ # the JavaScript is set, the helper appends "; return false;".
+ #
+ # The +href+ attribute of the tag is set to "#" unless +html_options+ has one.
+ #
+ # link_to_function "Greeting", "alert('Hello world!')", :class => "nav_link"
+ # # => <a class="nav_link" href="#" onclick="alert('Hello world!'); return false;">Greeting</a>
+ #
+ def link_to_function(name, function, html_options={})
+ message = "link_to_function is deprecated and will be removed from Rails 4.1. Use Unobtrusive JavaScript instead."
+ ActiveSupport::Deprecation.warn message
+
+ onclick = "#{"#{html_options[:onclick]}; " if html_options[:onclick]}#{function}; return false;"
+ href = html_options[:href] || '#'
+
+ content_tag(:a, name, html_options.merge(:href => href, :onclick => onclick))
+ end
end
end
end
diff --git a/actionpack/lib/action_view/helpers/number_helper.rb b/actionpack/lib/action_view/helpers/number_helper.rb
index dfc26acfad..9720e90429 100644
--- a/actionpack/lib/action_view/helpers/number_helper.rb
+++ b/actionpack/lib/action_view/helpers/number_helper.rb
@@ -1,8 +1,8 @@
# encoding: utf-8
-require 'active_support/core_ext/big_decimal/conversions'
-require 'active_support/core_ext/object/blank'
+require 'active_support/core_ext/hash/keys'
require 'active_support/core_ext/string/output_safety'
+require 'active_support/number_helper'
module ActionView
# = Action View Number Helpers
@@ -16,9 +16,6 @@ module ActionView
# unchanged if can't be converted into a valid number.
module NumberHelper
- DEFAULT_CURRENCY_VALUES = { :format => "%u%n", :negative_format => "-%u%n", :unit => "$", :separator => ".", :delimiter => ",",
- :precision => 2, :significant => false, :strip_insignificant_zeros => false }
-
# Raised when argument +number+ param given to the helpers is invalid and
# the option :raise is set to +true+.
class InvalidNumberError < StandardError
@@ -62,26 +59,8 @@ module ActionView
return unless number
options = options.symbolize_keys
- parse_float(number, true) if options[:raise]
-
- number = number.to_s.strip
- area_code = options[:area_code]
- delimiter = options[:delimiter] || "-"
- extension = options[:extension]
- country_code = options[:country_code]
-
- if area_code
- number.gsub!(/(\d{1,3})(\d{3})(\d{4}$)/,"(\\1) \\2#{delimiter}\\3")
- else
- number.gsub!(/(\d{0,3})(\d{3})(\d{4})$/,"\\1#{delimiter}\\2#{delimiter}\\3")
- number.slice!(0, 1) if number.start_with?(delimiter) && !delimiter.blank?
- end
-
- str = ''
- str << "+#{country_code}#{delimiter}" unless country_code.blank?
- str << number
- str << " x #{extension}" unless extension.blank?
- ERB::Util.html_escape(str)
+ parse_float(number, true) if options.delete(:raise)
+ ERB::Util.html_escape(ActiveSupport::NumberHelper.number_to_phone(number, options))
end
# Formats a +number+ into a currency string (e.g., $13.65). You
@@ -128,34 +107,11 @@ module ActionView
# # => 1234567890,50 &pound;
def number_to_currency(number, options = {})
return unless number
- options = options.symbolize_keys
+ options = escape_unsafe_delimiters_and_separators(options.symbolize_keys)
- currency = translations_for('currency', options[:locale])
- currency[:negative_format] ||= "-" + currency[:format] if currency[:format]
-
- defaults = DEFAULT_CURRENCY_VALUES.merge(defaults_translations(options[:locale])).merge!(currency)
- defaults[:negative_format] = "-" + options[:format] if options[:format]
- options = defaults.merge!(options)
-
- unit = options.delete(:unit)
- format = options.delete(:format)
-
- if number.to_f < 0
- format = options.delete(:negative_format)
- number = number.respond_to?("abs") ? number.abs : number.sub(/^-/, '')
- end
-
- begin
- value = number_with_precision(number, options.merge(:raise => true))
- format.gsub('%n', value).gsub('%u', unit).html_safe
- rescue InvalidNumberError => e
- if options[:raise]
- raise
- else
- formatted_number = format.gsub('%n', e.number).gsub('%u', unit)
- e.number.to_s.html_safe? ? formatted_number.html_safe : formatted_number
- end
- end
+ wrap_with_output_safety_handling(number, options.delete(:raise)) {
+ ActiveSupport::NumberHelper.number_to_currency(number, options)
+ }
end
# Formats a +number+ as a percentage string (e.g., 65%). You can
@@ -196,24 +152,11 @@ module ActionView
# number_to_percentage("98a", :raise => true) # => InvalidNumberError
def number_to_percentage(number, options = {})
return unless number
- options = options.symbolize_keys
+ options = escape_unsafe_delimiters_and_separators(options.symbolize_keys)
- defaults = format_translations('percentage', options[:locale])
- options = defaults.merge!(options)
-
- format = options[:format] || "%n%"
-
- begin
- value = number_with_precision(number, options.merge(:raise => true))
- format.gsub(/%n/, value).html_safe
- rescue InvalidNumberError => e
- if options[:raise]
- raise
- else
- formatted_number = format.gsub(/%n/, e.number)
- e.number.to_s.html_safe? ? formatted_number.html_safe : formatted_number
- end
- end
+ wrap_with_output_safety_handling(number, options.delete(:raise)) {
+ ActiveSupport::NumberHelper.number_to_percentage(number, options)
+ }
end
# Formats a +number+ with grouped thousands using +delimiter+
@@ -246,15 +189,11 @@ module ActionView
#
# number_with_delimiter("112a", :raise => true) # => raise InvalidNumberError
def number_with_delimiter(number, options = {})
- options = options.symbolize_keys
+ options = escape_unsafe_delimiters_and_separators(options.symbolize_keys)
- parse_float(number, options[:raise]) or return number
-
- options = defaults_translations(options[:locale]).merge(options)
-
- parts = number.to_s.to_str.split('.')
- parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{options[:delimiter]}")
- safe_join(parts, options[:separator])
+ wrap_with_output_safety_handling(number, options.delete(:raise)) {
+ ActiveSupport::NumberHelper.number_to_delimited(number, options)
+ }
end
# Formats a +number+ with the specified level of
@@ -299,41 +238,13 @@ module ActionView
# number_with_precision(1111.2345, :precision => 2, :separator => ',', :delimiter => '.')
# # => 1.111,23
def number_with_precision(number, options = {})
- options = options.symbolize_keys
+ options = escape_unsafe_delimiters_and_separators(options.symbolize_keys)
- number = (parse_float(number, options[:raise]) or return number)
-
- defaults = format_translations('precision', options[:locale])
- options = defaults.merge!(options)
-
- precision = options.delete :precision
- significant = options.delete :significant
- strip_insignificant_zeros = options.delete :strip_insignificant_zeros
-
- if significant and precision > 0
- if number == 0
- digits, rounded_number = 1, 0
- else
- digits = (Math.log10(number.abs) + 1).floor
- rounded_number = (BigDecimal.new(number.to_s) / BigDecimal.new((10 ** (digits - precision)).to_f.to_s)).round.to_f * 10 ** (digits - precision)
- digits = (Math.log10(rounded_number.abs) + 1).floor # After rounding, the number of digits may have changed
- end
- precision -= digits
- precision = precision > 0 ? precision : 0 #don't let it be negative
- else
- rounded_number = BigDecimal.new(number.to_s).round(precision).to_f
- rounded_number = rounded_number.zero? ? rounded_number.abs : rounded_number #prevent showing negative zeros
- end
- formatted_number = number_with_delimiter("%01.#{precision}f" % rounded_number, options)
- if strip_insignificant_zeros
- escaped_separator = Regexp.escape(options[:separator])
- formatted_number.sub(/(#{escaped_separator})(\d*[1-9])?0+\z/, '\1\2').sub(/#{escaped_separator}\z/, '').html_safe
- else
- formatted_number
- end
+ wrap_with_output_safety_handling(number, options.delete(:raise)) {
+ ActiveSupport::NumberHelper.number_to_rounded(number, options)
+ }
end
- STORAGE_UNITS = [:byte, :kb, :mb, :gb, :tb].freeze
# Formats the bytes in +number+ into a more understandable
# representation (e.g., giving it 1500 yields 1.5 KB). This
@@ -383,40 +294,13 @@ module ActionView
# number_to_human_size(1234567890123, :precision => 5) # => "1.1229 TB"
# number_to_human_size(524288000, :precision => 5) # => "500 MB"
def number_to_human_size(number, options = {})
- options = options.symbolize_keys
-
- number = (parse_float(number, options[:raise]) or return number)
-
- defaults = format_translations('human', options[:locale])
- options = defaults.merge!(options)
-
- #for backwards compatibility with those that didn't add strip_insignificant_zeros to their locale files
- options[:strip_insignificant_zeros] = true if not options.key?(:strip_insignificant_zeros)
-
- storage_units_format = I18n.translate(:'number.human.storage_units.format', :locale => options[:locale], :raise => true)
+ options = escape_unsafe_delimiters_and_separators(options.symbolize_keys)
- base = options[:prefix] == :si ? 1000 : 1024
-
- if number.to_i < base
- unit = I18n.translate(:'number.human.storage_units.units.byte', :locale => options[:locale], :count => number.to_i, :raise => true)
- storage_units_format.gsub(/%n/, number.to_i.to_s).gsub(/%u/, unit).html_safe
- else
- max_exp = STORAGE_UNITS.size - 1
- exponent = (Math.log(number) / Math.log(base)).to_i # Convert to base
- exponent = max_exp if exponent > max_exp # we need this to avoid overflow for the highest unit
- number /= base ** exponent
-
- unit_key = STORAGE_UNITS[exponent]
- unit = I18n.translate(:"number.human.storage_units.units.#{unit_key}", :locale => options[:locale], :count => number, :raise => true)
-
- formatted_number = number_with_precision(number, options)
- storage_units_format.gsub(/%n/, formatted_number).gsub(/%u/, unit).html_safe
- end
+ wrap_with_output_safety_handling(number, options.delete(:raise)) {
+ ActiveSupport::NumberHelper.number_to_human_size(number, options)
+ }
end
- DECIMAL_UNITS = {0 => :unit, 1 => :ten, 2 => :hundred, 3 => :thousand, 6 => :million, 9 => :billion, 12 => :trillion, 15 => :quadrillion,
- -1 => :deci, -2 => :centi, -3 => :mili, -6 => :micro, -9 => :nano, -12 => :pico, -15 => :femto}.freeze
-
# Pretty prints (formats and approximates) a number in a way it
# is more readable by humans (eg.: 1200000000 becomes "1.2
# Billion"). This is useful for numbers that can get very large
@@ -516,60 +400,36 @@ module ActionView
# number_to_human(0.34, :units => :distance) # => "34 centimeters"
#
def number_to_human(number, options = {})
- options = options.symbolize_keys
+ options = escape_unsafe_delimiters_and_separators(options.symbolize_keys)
- number = (parse_float(number, options[:raise]) or return number)
+ wrap_with_output_safety_handling(number, options.delete(:raise)) {
+ ActiveSupport::NumberHelper.number_to_human(number, options)
+ }
+ end
- defaults = format_translations('human', options[:locale])
- options = defaults.merge!(options)
+ private
- #for backwards compatibility with those that didn't add strip_insignificant_zeros to their locale files
- options[:strip_insignificant_zeros] = true if not options.key?(:strip_insignificant_zeros)
+ def escape_unsafe_delimiters_and_separators(options)
+ options[:separator] = ERB::Util.html_escape(options[:separator]) if options[:separator] && !options[:separator].html_safe?
+ options[:delimiter] = ERB::Util.html_escape(options[:delimiter]) if options[:delimiter] && !options[:delimiter].html_safe?
+ options
+ end
- inverted_du = DECIMAL_UNITS.invert
+ def wrap_with_output_safety_handling(number, raise_on_invalid, &block)
+ valid_float = valid_float?(number)
+ raise InvalidNumberError, number if raise_on_invalid && !valid_float
- units = options.delete :units
- unit_exponents = case units
- when Hash
- units
- when String, Symbol
- I18n.translate(:"#{units}", :locale => options[:locale], :raise => true)
- when nil
- I18n.translate(:"number.human.decimal_units.units", :locale => options[:locale], :raise => true)
- else
- raise ArgumentError, ":units must be a Hash or String translation scope."
- end.keys.map{|e_name| inverted_du[e_name] }.sort_by{|e| -e}
+ formatted_number = yield
- number_exponent = number != 0 ? Math.log10(number.abs).floor : 0
- display_exponent = unit_exponents.find{ |e| number_exponent >= e } || 0
- number /= 10 ** display_exponent
-
- unit = case units
- when Hash
- units[DECIMAL_UNITS[display_exponent]]
- when String, Symbol
- I18n.translate(:"#{units}.#{DECIMAL_UNITS[display_exponent]}", :locale => options[:locale], :count => number.to_i)
+ if valid_float || number.html_safe?
+ formatted_number.html_safe
else
- I18n.translate(:"number.human.decimal_units.units.#{DECIMAL_UNITS[display_exponent]}", :locale => options[:locale], :count => number.to_i)
+ formatted_number
end
-
- decimal_format = options[:format] || I18n.translate(:'number.human.decimal_units.format', :locale => options[:locale], :default => "%n %u")
- formatted_number = number_with_precision(number, options)
- decimal_format.gsub(/%n/, formatted_number).gsub(/%u/, unit).strip.html_safe
- end
-
- private
-
- def format_translations(namespace, locale)
- defaults_translations(locale).merge(translations_for(namespace, locale))
- end
-
- def defaults_translations(locale)
- I18n.translate(:'number.format', :locale => locale, :default => {})
end
- def translations_for(namespace, locale)
- I18n.translate(:"number.#{namespace}.format", :locale => locale, :default => {})
+ def valid_float?(number)
+ !parse_float(number, false).nil?
end
def parse_float(number, raise_error)
diff --git a/actionpack/lib/action_view/helpers/sanitize_helper.rb b/actionpack/lib/action_view/helpers/sanitize_helper.rb
index a727b910e5..aaf0e0344a 100644
--- a/actionpack/lib/action_view/helpers/sanitize_helper.rb
+++ b/actionpack/lib/action_view/helpers/sanitize_helper.rb
@@ -78,7 +78,7 @@ module ActionView
# strip_tags("<div id='top-bar'>Welcome to my website!</div>")
# # => Welcome to my website!
def strip_tags(html)
- self.class.full_sanitizer.sanitize(html).try(:html_safe)
+ self.class.full_sanitizer.sanitize(html)
end
# Strips all link tags from +text+ leaving just the link text.
diff --git a/actionpack/lib/action_view/helpers/tag_helper.rb b/actionpack/lib/action_view/helpers/tag_helper.rb
index 9572f1c192..3327c69d61 100644
--- a/actionpack/lib/action_view/helpers/tag_helper.rb
+++ b/actionpack/lib/action_view/helpers/tag_helper.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/string/output_safety'
require 'set'
diff --git a/actionpack/lib/action_view/helpers/tags/base.rb b/actionpack/lib/action_view/helpers/tags/base.rb
index e077cd5b3c..192f5eebaa 100644
--- a/actionpack/lib/action_view/helpers/tags/base.rb
+++ b/actionpack/lib/action_view/helpers/tags/base.rb
@@ -137,10 +137,10 @@ module ActionView
def add_options(option_tags, options, value = nil)
if options[:include_blank]
- option_tags = content_tag('option', options[:include_blank].kind_of?(String) ? options[:include_blank] : nil, :value => '') + "\n" + option_tags
+ option_tags = content_tag_string('option', options[:include_blank].kind_of?(String) ? options[:include_blank] : nil, :value => '') + "\n" + option_tags
end
if value.blank? && options[:prompt]
- option_tags = content_tag('option', prompt_text(options[:prompt]), :value => '') + "\n" + option_tags
+ option_tags = content_tag_string('option', prompt_text(options[:prompt]), :value => '') + "\n" + option_tags
end
option_tags
end
diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb
index 8cd7cf0052..0f599d5f41 100644
--- a/actionpack/lib/action_view/helpers/text_helper.rb
+++ b/actionpack/lib/action_view/helpers/text_helper.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/string/filters'
require 'active_support/core_ext/array/extract_options'
@@ -62,9 +61,11 @@ module ActionView
#
# Pass a <tt>:separator</tt> to truncate +text+ at a natural break.
#
- # The result is not marked as HTML-safe, so will be subject to the default escaping when
- # used in views, unless wrapped by <tt>raw()</tt>. Care should be taken if +text+ contains HTML tags
- # or entities, because truncation may produce invalid HTML (such as unbalanced or incomplete tags).
+ # Pass a block if you want to show extra content when the text is truncated.
+ #
+ # The result is marked as HTML-safe, but it is escaped by default, unless <tt>:escape</tt> is
+ # +false+. Care should be taken if +text+ contains HTML tags or entities, because truncation
+ # may produce invalid HTML (such as unbalanced or incomplete tags).
#
# truncate("Once upon a time in a world far far away")
# # => "Once upon a time in a world..."
@@ -80,8 +81,18 @@ module ActionView
#
# truncate("<p>Once upon a time in a world far far away</p>")
# # => "<p>Once upon a time in a wo..."
- def truncate(text, options = {})
- text.truncate(options.fetch(:length, 30), options) if text
+ #
+ # truncate("Once upon a time in a world far far away") { link_to "Continue", "#" }
+ # # => "Once upon a time in a wo...<a href="#">Continue</a>"
+ def truncate(text, options = {}, &block)
+ if text
+ length = options.fetch(:length, 30)
+
+ content = text.truncate(length, options)
+ content = options[:escape] == false ? content.html_safe : ERB::Util.html_escape(content)
+ content << capture(&block) if block_given? && text.length > length
+ content
+ end
end
# Highlights one or more +phrases+ everywhere in +text+ by inserting it into
@@ -102,7 +113,7 @@ module ActionView
# # => You searched for: <a href="search?q=rails">rails</a>
def highlight(text, phrases, options = {})
highlighter = options.fetch(:highlighter, '<mark>\1</mark>')
-
+
text = sanitize(text) if options.fetch(:sanitize, true)
if text.blank? || phrases.blank?
text
@@ -165,12 +176,12 @@ module ActionView
# pluralize(0, 'person')
# # => 0 people
def pluralize(count, singular, plural = nil)
- word = if (count == 1 || count =~ /^1(\.0+)?$/)
- singular
+ word = if (count == 1 || count =~ /^1(\.0+)?$/)
+ singular
else
plural || singular.pluralize
end
-
+
"#{count || 0} #{word}"
end
@@ -215,7 +226,7 @@ module ActionView
#
# simple_format(my_text)
# # => "<p>Here is some basic text...\n<br />...with a line break.</p>"
- #
+ #
# simple_format(my_text, {}, :wrapper_tag => "div")
# # => "<div>Here is some basic text...\n<br />...with a line break.</div>"
#
@@ -231,7 +242,7 @@ module ActionView
# # => "<p><span>I'm allowed!</span> It's true.</p>"
def simple_format(text, html_options = {}, options = {})
wrapper_tag = options.fetch(:wrapper_tag, :p)
-
+
text = sanitize(text) if options.fetch(:sanitize, true)
paragraphs = split_paragraphs(text)
diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb
index 7e69547dab..fe3240fdc1 100644
--- a/actionpack/lib/action_view/helpers/url_helper.rb
+++ b/actionpack/lib/action_view/helpers/url_helper.rb
@@ -23,7 +23,7 @@ module ActionView
include ActionDispatch::Routing::UrlFor
include TagHelper
- # We need to override url_optoins, _routes_context
+ # We need to override url_options, _routes_context
# and optimize_routes_generation? to consider the controller.
def url_options #:nodoc:
@@ -60,11 +60,15 @@ module ActionView
#
# ==== Relying on named routes
#
- # Passing a record (like an Active Record) instead of a Hash as the options parameter will
+ # Passing a record (like an Active Record) instead of a hash as the options parameter will
# trigger the named route for that record. The lookup will happen on the name of the class. So passing a
# Workshop object will attempt to use the +workshop_path+ route. If you have a nested route, such as
# +admin_workshop_path+ you'll have to call that explicitly (it's impossible for +url_for+ to guess that route).
#
+ # ==== Implicit Controller Namespacing
+ #
+ # Controllers passed in using the +:controller+ option will retain their namespace unless it is an absolute one.
+ #
# ==== Examples
# <%= url_for(:action => 'index') %>
# # => /blog/
@@ -102,6 +106,14 @@ module ActionView
# <%= url_for(:back) %>
# # if request.env["HTTP_REFERER"] is not set or is blank
# # => javascript:history.back()
+ #
+ # <%= url_for(:action => 'index', :controller => 'users') %>
+ # # Assuming an "admin" namespace
+ # # => /admin/users
+ #
+ # <%= url_for(:action => 'index', :controller => '/users') %>
+ # # Specify absolute path with beginning slash
+ # # => /users
def url_for(options = nil)
case options
when String
@@ -132,8 +144,7 @@ module ActionView
# # posts_path
#
# link_to(body, url_options = {}, html_options = {})
- # # url_options, except :confirm or :method,
- # # is passed to url_for
+ # # url_options, except :method, is passed to url_for
#
# link_to(options = {}, html_options = {}) do
# # name
@@ -144,9 +155,7 @@ module ActionView
# end
#
# ==== Options
- # * <tt>:confirm => 'question?'</tt> - This will allow the unobtrusive JavaScript
- # driver to prompt with the question specified. If the user accepts, the link is
- # processed normally, otherwise no action is taken.
+ # * <tt>:data</tt> - This option can be used to add custom data attributes.
# * <tt>:method => symbol of HTTP verb</tt> - This modifier will dynamically
# create an HTML form and immediately submit the form for processing using
# the HTTP verb specified. Useful for having links perform a POST operation
@@ -163,6 +172,16 @@ module ActionView
# completion of the Ajax request and performing JavaScript operations once
# they're complete
#
+ # ==== Data attributes
+ #
+ # * <tt>:confirm => 'question?'</tt> - This will allow the unobtrusive JavaScript
+ # driver to prompt with the question specified. If the user accepts, the link is
+ # processed normally, otherwise no action is taken.
+ # * <tt>:disable_with</tt> - Value of this parameter will be
+ # used as the value for a disabled version of the submit
+ # button when the form is submitted. This feature is provided
+ # by the unobtrusive JavaScript driver.
+ #
# ==== Examples
# Because it relies on +url_for+, +link_to+ supports both older-style controller/action/id arguments
# and newer RESTful routes. Current Rails style favors RESTful routes whenever possible, so base
@@ -226,32 +245,24 @@ module ActionView
# link_to "Nonsense search", searches_path(:foo => "bar", :baz => "quux")
# # => <a href="/searches?foo=bar&amp;baz=quux">Nonsense search</a>
#
- # The two options specific to +link_to+ (<tt>:confirm</tt> and <tt>:method</tt>) are used as follows:
+ # The only option specific to +link_to+ (<tt>:method</tt>) is used as follows:
#
- # link_to "Visit Other Site", "http://www.rubyonrails.org/", :confirm => "Are you sure?"
- # # => <a href="http://www.rubyonrails.org/" data-confirm="Are you sure?"">Visit Other Site</a>
+ # link_to("Destroy", "http://www.example.com", :method => :delete)
+ # # => <a href='http://www.example.com' rel="nofollow" data-method="delete">Destroy</a>
#
- # link_to("Destroy", "http://www.example.com", :method => :delete, :confirm => "Are you sure?")
- # # => <a href='http://www.example.com' rel="nofollow" data-method="delete" data-confirm="Are you sure?">Destroy</a>
- def link_to(*args, &block)
- if block_given?
- options = args.first || {}
- html_options = args.second
- link_to(capture(&block), options, html_options)
- else
- name = args[0]
- options = args[1] || {}
- html_options = args[2]
-
- html_options = convert_options_to_data_attributes(options, html_options)
- url = url_for(options)
+ # You can also use custom data attributes using the <tt>:data</tt> option:
+ #
+ # link_to "Visit Other Site", "http://www.rubyonrails.org/", :data => { :confirm => "Are you sure?" }
+ # # => <a href="http://www.rubyonrails.org/" data-confirm="Are you sure?"">Visit Other Site</a>
+ def link_to(name = nil, options = nil, html_options = nil, &block)
+ html_options, options = options, name if block_given?
+ options ||= {}
+ url = url_for(options)
- href = html_options['href']
- tag_options = tag_options(html_options)
+ html_options = convert_options_to_data_attributes(options, html_options)
+ html_options['href'] ||= url
- href_attr = "href=\"#{ERB::Util.html_escape(url)}\"" unless href
- "<a #{href_attr}#{tag_options}>#{ERB::Util.html_escape(name || url)}</a>".html_safe
- end
+ content_tag(:a, name || url, html_options, &block)
end
# Generates a form containing a single button that submits to the URL created
@@ -265,10 +276,9 @@ module ActionView
# to allow styling of the form itself and its children. This can be changed
# using the <tt>:form_class</tt> modifier within +html_options+. You can control
# the form submission and input element behavior using +html_options+.
- # This method accepts the <tt>:method</tt> and <tt>:confirm</tt> modifiers
- # described in the +link_to+ documentation. If no <tt>:method</tt> modifier
- # is given, it will default to performing a POST operation. You can also
- # disable the button by passing <tt>:disabled => true</tt> in +html_options+.
+ # This method accepts the <tt>:method</tt> modifier described in the +link_to+ documentation.
+ # If no <tt>:method</tt> modifier is given, it will default to performing a POST operation.
+ # You can also disable the button by passing <tt>:disabled => true</tt> in +html_options+.
# If you are using RESTful routes, you can pass the <tt>:method</tt>
# to change the HTTP verb used to submit the form.
#
@@ -279,21 +289,39 @@ module ActionView
# * <tt>:method</tt> - Symbol of HTTP verb. Supported verbs are <tt>:post</tt>, <tt>:get</tt>,
# <tt>:delete</tt>, <tt>:patch</tt>, and <tt>:put</tt>. By default it will be <tt>:post</tt>.
# * <tt>:disabled</tt> - If set to true, it will generate a disabled button.
- # * <tt>:confirm</tt> - This will use the unobtrusive JavaScript driver to
- # prompt with the question specified. If the user accepts, the link is
- # processed normally, otherwise no action is taken.
+ # * <tt>:data</tt> - This option can be used to add custom data attributes.
# * <tt>:remote</tt> - If set to true, will allow the Unobtrusive JavaScript drivers to control the
# submit behavior. By default this behavior is an ajax submit.
# * <tt>:form</tt> - This hash will be form attributes
# * <tt>:form_class</tt> - This controls the class of the form within which the submit button will
# be placed
#
+ # ==== Data attributes
+ #
+ # * <tt>:confirm</tt> - This will use the unobtrusive JavaScript driver to
+ # prompt with the question specified. If the user accepts, the link is
+ # processed normally, otherwise no action is taken.
+ # * <tt>:disable_with</tt> - Value of this parameter will be
+ # used as the value for a disabled version of the submit
+ # button when the form is submitted. This feature is provided
+ # by the unobtrusive JavaScript driver.
+ #
# ==== Examples
# <%= button_to "New", :action => "new" %>
# # => "<form method="post" action="/controller/new" class="button_to">
# # <div><input value="New" type="submit" /></div>
# # </form>"
#
+ # <%= button_to [:make_happy, @user] do %>
+ # Make happy <strong><%= @user.name %></strong>
+ # <% end %>
+ # # => "<form method="post" action="/users/1/make_happy" class="button_to">
+ # # <div>
+ # # <button type="submit">
+ # # Make happy <strong><%= @user.name %></strong>
+ # # </button>
+ # # </div>
+ # # </form>"
#
# <%= button_to "New", :action => "new", :form_class => "new-thing" %>
# # => "<form method="post" action="/controller/new" class="new-thing">
@@ -311,7 +339,7 @@ module ActionView
#
#
# <%= button_to "Delete Image", { :action => "delete", :id => @image.id },
- # :confirm => "Are you sure?", :method => :delete %>
+ # :method => :delete, :data => { :confirm => "Are you sure?" } %>
# # => "<form method="post" action="/images/delete/1" class="button_to">
# # <div>
# # <input type="hidden" name="_method" value="delete" />
@@ -321,17 +349,21 @@ module ActionView
# # </form>"
#
#
- # <%= button_to('Destroy', 'http://www.example.com', :confirm => 'Are you sure?',
- # :method => "delete", :remote => true) %>
+ # <%= button_to('Destroy', 'http://www.example.com',
+ # :method => "delete", :remote => true, :data => { :confirm' => 'Are you sure?', :disable_with => 'loading...' }) %>
# # => "<form class='button_to' method='post' action='http://www.example.com' data-remote='true'>
# # <div>
# # <input name='_method' value='delete' type='hidden' />
- # # <input value='Destroy' type='submit' data-confirm='Are you sure?' />
+ # # <input value='Destroy' type='submit' data-disable-with='loading...' data-confirm='Are you sure?' />
# # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/>
# # </div>
# # </form>"
# #
- def button_to(name, options = {}, html_options = {})
+ def button_to(name = nil, options = nil, html_options = nil, &block)
+ html_options, options = options, name if block_given?
+ options ||= {}
+ html_options ||= {}
+
html_options = html_options.stringify_keys
convert_boolean_attributes!(html_options, %w(disabled))
@@ -350,9 +382,16 @@ module ActionView
request_token_tag = form_method == 'post' ? token_tag : ''
html_options = convert_options_to_data_attributes(options, html_options)
- html_options.merge!("type" => "submit", "value" => name || url)
+ html_options['type'] = 'submit'
+
+ button = if block_given?
+ content_tag('button', html_options, &block)
+ else
+ html_options['value'] = name || url
+ tag('input', html_options)
+ end
- inner_tags = method_tag.safe_concat tag('input', html_options).safe_concat request_token_tag
+ inner_tags = method_tag.safe_concat(button).safe_concat(request_token_tag)
content_tag('form', content_tag('div', inner_tags), form_options)
end
@@ -616,12 +655,24 @@ module ActionView
html_options = html_options.stringify_keys
html_options['data-remote'] = 'true' if link_to_remote_options?(options) || link_to_remote_options?(html_options)
+ disable_with = html_options.delete("disable_with")
confirm = html_options.delete('confirm')
method = html_options.delete('method')
- html_options["data-confirm"] = confirm if confirm
+ if confirm
+ ActiveSupport::Deprecation.warn ":confirm option is deprecated and will be removed from Rails 4.1. Use ':data => { :confirm => \'Text\' }' instead"
+
+ html_options["data-confirm"] = confirm
+ end
+
add_method_to_attributes!(html_options, method) if method
+ if disable_with
+ ActiveSupport::Deprecation.warn ":disable_with option is deprecated and will be removed from Rails 4.1. Use ':data => { :disable_with => \'Text\' }' instead"
+
+ html_options["data-disable-with"] = disable_with
+ end
+
html_options
else
link_to_remote_options?(options) ? {'data-remote' => 'true'} : {}
diff --git a/actionpack/lib/action_view/locale/en.yml b/actionpack/lib/action_view/locale/en.yml
index 8e9db634fb..8a56f147b8 100644
--- a/actionpack/lib/action_view/locale/en.yml
+++ b/actionpack/lib/action_view/locale/en.yml
@@ -1,102 +1,4 @@
"en":
- number:
- # Used in number_with_delimiter()
- # These are also the defaults for 'currency', 'percentage', 'precision', and 'human'
- format:
- # Sets the separator between the units, for more precision (e.g. 1.0 / 2.0 == 0.5)
- separator: "."
- # Delimits thousands (e.g. 1,000,000 is a million) (always in groups of three)
- delimiter: ","
- # Number of decimals, behind the separator (the number 1 with a precision of 2 gives: 1.00)
- precision: 3
- # If set to true, precision will mean the number of significant digits instead
- # of the number of decimal digits (1234 with precision 2 becomes 1200, 1.23543 becomes 1.2)
- significant: false
- # If set, the zeros after the decimal separator will always be stripped (eg.: 1.200 will be 1.2)
- strip_insignificant_zeros: false
-
- # Used in number_to_currency()
- currency:
- format:
- # Where is the currency sign? %u is the currency unit, %n the number (default: $5.00)
- format: "%u%n"
- unit: "$"
- # These five are to override number.format and are optional
- separator: "."
- delimiter: ","
- precision: 2
- significant: false
- strip_insignificant_zeros: false
-
- # Used in number_to_percentage()
- percentage:
- format:
- # These five are to override number.format and are optional
- # separator:
- delimiter: ""
- # precision:
- # significant: false
- # strip_insignificant_zeros: false
- format: "%n%"
-
- # Used in number_to_precision()
- precision:
- format:
- # These five are to override number.format and are optional
- # separator:
- delimiter: ""
- # precision:
- # significant: false
- # strip_insignificant_zeros: false
-
- # Used in number_to_human_size() and number_to_human()
- human:
- format:
- # These five are to override number.format and are optional
- # separator:
- delimiter: ""
- precision: 3
- significant: true
- strip_insignificant_zeros: true
- # Used in number_to_human_size()
- storage_units:
- # Storage units output formatting.
- # %u is the storage unit, %n is the number (default: 2 MB)
- format: "%n %u"
- units:
- byte:
- one: "Byte"
- other: "Bytes"
- kb: "KB"
- mb: "MB"
- gb: "GB"
- tb: "TB"
- # Used in number_to_human()
- decimal_units:
- format: "%n %u"
- # Decimal units output formatting
- # By default we will only quantify some of the exponents
- # but the commented ones might be defined or overridden
- # by the user.
- units:
- # femto: Quadrillionth
- # pico: Trillionth
- # nano: Billionth
- # micro: Millionth
- # mili: Thousandth
- # centi: Hundredth
- # deci: Tenth
- unit: ""
- # ten:
- # one: Ten
- # other: Tens
- # hundred: Hundred
- thousand: Thousand
- million: Million
- billion: Billion
- trillion: Trillion
- quadrillion: Quadrillion
-
# Used in distance_of_time_in_words(), distance_of_time_in_words_to_now(), time_ago_in_words()
datetime:
distance_in_words:
diff --git a/actionpack/lib/action_view/lookup_context.rb b/actionpack/lib/action_view/lookup_context.rb
index b7945a23be..f0ea92b018 100644
--- a/actionpack/lib/action_view/lookup_context.rb
+++ b/actionpack/lib/action_view/lookup_context.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/module/remove_method'
module ActionView
@@ -24,7 +23,7 @@ module ActionView
Accessors.send :define_method, :"default_#{name}", &block
Accessors.module_eval <<-METHOD, __FILE__, __LINE__ + 1
def #{name}
- @details[:#{name}]
+ @details.fetch(:#{name}, [])
end
def #{name}=(value)
@@ -96,7 +95,7 @@ module ActionView
# Helpers related to template lookup using the lookup context information.
module ViewPaths
- attr_reader :view_paths
+ attr_reader :view_paths, :html_fallback_for_js
# Whenever setting view paths, makes a copy so we can manipulate then in
# instance objects as we wish.
@@ -184,7 +183,10 @@ module ActionView
def formats=(values)
if values
values.concat(default_formats) if values.delete "*/*"
- values << :html if values == [:js]
+ if values == [:js]
+ values << :html
+ @html_fallback_for_js = true
+ end
end
super(values)
end
diff --git a/actionpack/lib/action_view/renderer/abstract_renderer.rb b/actionpack/lib/action_view/renderer/abstract_renderer.rb
index 72616b7463..6fb8cbb46c 100644
--- a/actionpack/lib/action_view/renderer/abstract_renderer.rb
+++ b/actionpack/lib/action_view/renderer/abstract_renderer.rb
@@ -1,7 +1,6 @@
module ActionView
class AbstractRenderer #:nodoc:
- delegate :find_template, :template_exists?, :with_fallbacks, :update_details,
- :with_layout_format, :formats, :to => :@lookup_context
+ delegate :find_template, :template_exists?, :with_fallbacks, :with_layout_format, :formats, :to => :@lookup_context
def initialize(lookup_context)
@lookup_context = lookup_context
@@ -23,5 +22,11 @@ module ActionView
def instrument(name, options={})
ActiveSupport::Notifications.instrument("render_#{name}.action_view", options){ yield }
end
+
+ def prepend_formats(formats)
+ formats = Array(formats)
+ return if formats.empty? || @lookup_context.html_fallback_for_js
+ @lookup_context.formats = formats | @lookup_context.formats
+ end
end
end
diff --git a/actionpack/lib/action_view/renderer/partial_renderer.rb b/actionpack/lib/action_view/renderer/partial_renderer.rb
index 9100545718..edefeac184 100644
--- a/actionpack/lib/action_view/renderer/partial_renderer.rb
+++ b/actionpack/lib/action_view/renderer/partial_renderer.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
module ActionView
# = Action View Partials
@@ -320,6 +319,8 @@ module ActionView
@block = block
@details = extract_details(options)
+ prepend_formats(options[:formats])
+
if String === partial
@object = options[:object]
@path = partial
@@ -335,17 +336,16 @@ module ActionView
end
end
+ if as = options[:as]
+ raise_invalid_identifier(as) unless as.to_s =~ /\A[a-z_]\w*\z/
+ as = as.to_sym
+ end
+
if @path
- @variable, @variable_counter = retrieve_variable(@path)
+ @variable, @variable_counter = retrieve_variable(@path, as)
@template_keys = retrieve_template_keys
else
- paths.map! { |path| retrieve_variable(path).unshift(path) }
- end
-
- if String === partial && @variable.to_s !~ /^[a-z_][a-zA-Z_0-9]*$/
- raise ArgumentError.new("The partial name (#{partial}) is not a valid Ruby identifier; " +
- "make sure your partial name starts with a lowercase letter or underscore, " +
- "and is followed by any combination of letters, numbers and underscores.")
+ paths.map! { |path| retrieve_variable(path, as).unshift(path) }
end
self
@@ -454,10 +454,22 @@ module ActionView
keys
end
- def retrieve_variable(path)
- variable = @options.fetch(:as) { path[%r'_?(\w+)(\.\w+)*$', 1] }.try(:to_sym)
+ def retrieve_variable(path, as)
+ variable = as || begin
+ base = path[-1] == "/" ? "" : File.basename(path)
+ raise_invalid_identifier(path) unless base =~ /\A_?([a-z]\w*)(\.\w+)*\z/
+ $1.to_sym
+ end
variable_counter = :"#{variable}_counter" if @collection
[variable, variable_counter]
end
+
+ IDENTIFIER_ERROR_MESSAGE = "The partial name (%s) is not a valid Ruby identifier; " +
+ "make sure your partial name starts with a lowercase letter or underscore, " +
+ "and is followed by any combination of letters, numbers and underscores."
+
+ def raise_invalid_identifier(path)
+ raise ArgumentError.new(IDENTIFIER_ERROR_MESSAGE % (path))
+ end
end
end
diff --git a/actionpack/lib/action_view/renderer/template_renderer.rb b/actionpack/lib/action_view/renderer/template_renderer.rb
index ae923de24e..156ad4e547 100644
--- a/actionpack/lib/action_view/renderer/template_renderer.rb
+++ b/actionpack/lib/action_view/renderer/template_renderer.rb
@@ -8,9 +8,10 @@ module ActionView
template = determine_template(options)
context = @lookup_context
+ prepend_formats(template.formats)
+
unless context.rendered_format
- context.formats = template.formats unless template.formats.empty?
- context.rendered_format = context.formats.first
+ context.rendered_format = template.formats.first || formats.last
end
render_template(template, options[:layout], options[:locals])
@@ -18,10 +19,10 @@ module ActionView
# Determine the template to be rendered using the given options.
def determine_template(options) #:nodoc:
- keys = options[:locals].try(:keys) || []
+ keys = options.fetch(:locals, {}).keys
if options.key?(:text)
- Template::Text.new(options[:text], formats.try(:first))
+ Template::Text.new(options[:text], formats.first)
elsif options.key?(:file)
with_fallbacks { find_template(options[:file], nil, false, keys, @details) }
elsif options.key?(:inline)
@@ -35,7 +36,7 @@ module ActionView
end
end
- # Renders the given template. An string representing the layout can be
+ # Renders the given template. A string representing the layout can be
# supplied as well.
def render_template(template, layout_name = nil, locals = {}) #:nodoc:
view, locals = @view, locals || {}
diff --git a/actionpack/lib/action_view/template.rb b/actionpack/lib/action_view/template.rb
index cd79468502..a04eac1d3f 100644
--- a/actionpack/lib/action_view/template.rb
+++ b/actionpack/lib/action_view/template.rb
@@ -1,4 +1,3 @@
-require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/object/try'
require 'active_support/core_ext/kernel/singleton_class'
require 'thread'
diff --git a/actionpack/lib/action_view/template/error.rb b/actionpack/lib/action_view/template/error.rb
index d8258f7b11..f2bef4bded 100644
--- a/actionpack/lib/action_view/template/error.rb
+++ b/actionpack/lib/action_view/template/error.rb
@@ -84,13 +84,13 @@ module ActionView
start_on_line = [ num - SOURCE_CODE_RADIUS - 1, 0 ].max
end_on_line = [ num + SOURCE_CODE_RADIUS - 1, source_code.length].min
- indent = ' ' * indentation
+ indent = end_on_line.to_s.size + indentation
line_counter = start_on_line
return unless source_code = source_code[start_on_line..end_on_line]
source_code.sum do |line|
line_counter += 1
- "#{indent}#{line_counter}: #{line}\n"
+ "%#{indent}s: %s\n" % [line_counter, line]
end
end
diff --git a/actionpack/lib/action_view/template/handlers/erb.rb b/actionpack/lib/action_view/template/handlers/erb.rb
index 19b9112afd..aa8eac7846 100644
--- a/actionpack/lib/action_view/template/handlers/erb.rb
+++ b/actionpack/lib/action_view/template/handlers/erb.rb
@@ -1,5 +1,4 @@
require 'action_dispatch/http/mime_type'
-require 'active_support/core_ext/class/attribute'
require 'erubis'
module ActionView
diff --git a/actionpack/lib/action_view/template/resolver.rb b/actionpack/lib/action_view/template/resolver.rb
index fa2038f78d..2bb656fac9 100644
--- a/actionpack/lib/action_view/template/resolver.rb
+++ b/actionpack/lib/action_view/template/resolver.rb
@@ -2,12 +2,14 @@ require "pathname"
require "active_support/core_ext/class"
require "active_support/core_ext/class/attribute_accessors"
require "action_view/template"
+require "thread"
+require "mutex_m"
module ActionView
# = Action View Resolver
class Resolver
# Keeps all information about view path and builds virtual path.
- class Path < String
+ class Path
attr_reader :name, :prefix, :partial, :virtual
alias_method :partial?, :partial
@@ -19,8 +21,77 @@ module ActionView
end
def initialize(name, prefix, partial, virtual)
- @name, @prefix, @partial = name, prefix, partial
- super(virtual)
+ @name = name
+ @prefix = prefix
+ @partial = partial
+ @virtual = virtual
+ end
+
+ def to_str
+ @virtual
+ end
+ alias :to_s :to_str
+ end
+
+ # Threadsafe template cache
+ class Cache #:nodoc:
+ class CacheEntry
+ include Mutex_m
+
+ attr_accessor :templates
+ end
+
+ def initialize
+ @data = Hash.new { |h1,k1| h1[k1] = Hash.new { |h2,k2|
+ h2[k2] = Hash.new { |h3,k3| h3[k3] = Hash.new { |h4,k4| h4[k4] = {} } } } }
+ @mutex = Mutex.new
+ end
+
+ # Cache the templates returned by the block
+ def cache(key, name, prefix, partial, locals)
+ cache_entry = nil
+
+ # first obtain a lock on the main data structure to create the cache entry
+ @mutex.synchronize do
+ cache_entry = @data[key][name][prefix][partial][locals] ||= CacheEntry.new
+ end
+
+ # then to avoid a long lasting global lock, obtain a more granular lock
+ # on the CacheEntry itself
+ cache_entry.synchronize do
+ if Resolver.caching?
+ cache_entry.templates ||= yield
+ else
+ fresh_templates = yield
+
+ if templates_have_changed?(cache_entry.templates, fresh_templates)
+ cache_entry.templates = fresh_templates
+ else
+ cache_entry.templates ||= []
+ end
+ end
+ end
+ end
+
+ def clear
+ @mutex.synchronize do
+ @data.clear
+ end
+ end
+
+ private
+
+ def templates_have_changed?(cached_templates, fresh_templates)
+ # if either the old or new template list is empty, we don't need to (and can't)
+ # compare modification times, and instead just check whether the lists are different
+ if cached_templates.blank? || fresh_templates.blank?
+ return fresh_templates.blank? != cached_templates.blank?
+ end
+
+ cached_templates_max_updated_at = cached_templates.map(&:updated_at).max
+
+ # if a template has changed, it will be now be newer than all the cached templates
+ fresh_templates.any? { |t| t.updated_at > cached_templates_max_updated_at }
end
end
@@ -32,12 +103,11 @@ module ActionView
end
def initialize
- @cached = Hash.new { |h1,k1| h1[k1] = Hash.new { |h2,k2|
- h2[k2] = Hash.new { |h3,k3| h3[k3] = Hash.new { |h4,k4| h4[k4] = {} } } } }
+ @cache = Cache.new
end
def clear_cache
- @cached.clear
+ @cache.clear
end
# Normalizes the arguments and passes it on to find_template.
@@ -65,27 +135,18 @@ module ActionView
# Handles templates caching. If a key is given and caching is on
# always check the cache before hitting the resolver. Otherwise,
- # it always hits the resolver but check if the resolver is fresher
- # before returning it.
+ # it always hits the resolver but if the key is present, check if the
+ # resolver is fresher before returning it.
def cached(key, path_info, details, locals) #:nodoc:
name, prefix, partial = path_info
locals = locals.map { |x| x.to_s }.sort!
- if key && caching?
- @cached[key][name][prefix][partial][locals] ||= decorate(yield, path_info, details, locals)
- else
- fresh = decorate(yield, path_info, details, locals)
- return fresh unless key
-
- scope = @cached[key][name][prefix][partial]
- cache = scope[locals]
- mtime = cache && cache.map(&:updated_at).max
-
- if !mtime || fresh.empty? || fresh.any? { |t| t.updated_at > mtime }
- scope[locals] = fresh
- else
- cache
+ if key
+ @cache.cache(key, name, prefix, partial, locals) do
+ decorate(yield, path_info, details, locals)
end
+ else
+ decorate(yield, path_info, details, locals)
end
end
diff --git a/actionpack/lib/action_view/template/text.rb b/actionpack/lib/action_view/template/text.rb
index 4261c3b5e2..3af76dfcdb 100644
--- a/actionpack/lib/action_view/template/text.rb
+++ b/actionpack/lib/action_view/template/text.rb
@@ -1,11 +1,11 @@
module ActionView #:nodoc:
# = Action View Text Template
class Template
- class Text < String #:nodoc:
+ class Text #:nodoc:
attr_accessor :mime_type
def initialize(string, mime_type = nil)
- super(string.to_s)
+ @string = string.to_s
@mime_type = Mime[mime_type] || mime_type if mime_type
@mime_type ||= Mime::TEXT
end
@@ -18,8 +18,12 @@ module ActionView #:nodoc:
'text template'
end
+ def to_str
+ @string
+ end
+
def render(*args)
- to_s
+ to_str
end
def formats
diff --git a/actionpack/lib/action_view/test_case.rb b/actionpack/lib/action_view/test_case.rb
index fece499c94..55f79bf761 100644
--- a/actionpack/lib/action_view/test_case.rb
+++ b/actionpack/lib/action_view/test_case.rb
@@ -1,5 +1,3 @@
-require 'active_support/core_ext/object/blank'
-require 'active_support/core_ext/module/delegation'
require 'active_support/core_ext/module/remove_method'
require 'action_controller'
require 'action_controller/test_case'
@@ -229,7 +227,8 @@ module ActionView
def method_missing(selector, *args)
if @controller.respond_to?(:_routes) &&
- @controller._routes.named_routes.helpers.include?(selector)
+ ( @controller._routes.named_routes.helpers.include?(selector) ||
+ @controller._routes.mounted_helpers.method_defined?(selector) )
@controller.__send__(selector, *args)
else
super