diff options
Diffstat (limited to 'actionpack/lib')
181 files changed, 5128 insertions, 3146 deletions
diff --git a/actionpack/lib/abstract_controller.rb b/actionpack/lib/abstract_controller.rb index cc5878c88e..867a7954e0 100644 --- a/actionpack/lib/abstract_controller.rb +++ b/actionpack/lib/abstract_controller.rb @@ -1,13 +1,6 @@ -activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__) -$:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path) - require 'action_pack' -require 'active_support/concern' -require 'active_support/ruby/shim' -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/asset_paths.rb b/actionpack/lib/abstract_controller/asset_paths.rb index dd5f9a1942..822254b1a4 100644 --- a/actionpack/lib/abstract_controller/asset_paths.rb +++ b/actionpack/lib/abstract_controller/asset_paths.rb @@ -1,5 +1,5 @@ module AbstractController - module AssetPaths + module AssetPaths #:nodoc: extend ActiveSupport::Concern included do diff --git a/actionpack/lib/abstract_controller/base.rb b/actionpack/lib/abstract_controller/base.rb index fd6a46fbec..9c3960961b 100644 --- a/actionpack/lib/abstract_controller/base.rb +++ b/actionpack/lib/abstract_controller/base.rb @@ -1,11 +1,15 @@ require 'erubis' +require 'set' require 'active_support/configurable' require 'active_support/descendants_tracker' require 'active_support/core_ext/module/anonymous' module AbstractController - class Error < StandardError; end - class ActionNotFound < StandardError; end + class Error < StandardError #:nodoc: + end + + class ActionNotFound < StandardError #:nodoc: + end # <tt>AbstractController::Base</tt> is a low-level API. Nobody should be # using it directly, and subclasses (like ActionController::Base) are @@ -42,12 +46,12 @@ module AbstractController controller.public_instance_methods(true) end - # The list of hidden actions to an empty array. Defaults to an - # empty array. This can be modified by other modules or subclasses + # The list of hidden actions. Defaults to an empty array. + # This can be modified by other modules or subclasses # to specify particular actions as hidden. # # ==== Returns - # * <tt>array</tt> - An array of method names that should not be considered actions. + # * <tt>Array</tt> - An array of method names that should not be considered actions. def hidden_actions [] end @@ -59,7 +63,7 @@ module AbstractController # itself. Finally, #hidden_actions are removed. # # ==== Returns - # * <tt>array</tt> - A list of all methods that should be considered actions. + # * <tt>Set</tt> - A set of all methods that should be considered actions. def action_methods @action_methods ||= begin # All public instance methods of this class, including ancestors @@ -72,7 +76,7 @@ module AbstractController hidden_actions.to_a # Clear out AS callback method pollution - methods.reject { |method| method =~ /_one_time_conditions/ } + Set.new(methods.reject { |method| method =~ /_one_time_conditions/ }) end end @@ -85,14 +89,15 @@ module AbstractController # Returns the full controller name, underscored, without the ending Controller. # For instance, MyApp::MyPostsController would return "my_app/my_posts" for - # controller_name. + # controller_path. # # ==== Returns - # * <tt>string</tt> + # * <tt>String</tt> def controller_path @controller_path ||= name.sub(/Controller$/, '').underscore unless anonymous? end + # Refresh the cached action_methods when a new action_method is added. def method_added(name) super clear_action_methods! @@ -126,6 +131,7 @@ module AbstractController self.class.controller_path end + # Delegates to the class' #action_methods def action_methods self.class.action_methods end @@ -135,8 +141,14 @@ module AbstractController # # Notice that <tt>action_methods.include?("foo")</tt> may return # false and <tt>available_action?("foo")</tt> returns true because - # available action consider actions that are also available + # this method considers actions that are also available # through other means, for example, implicit render ones. + # + # ==== Parameters + # * <tt>action_name</tt> - The name of an action to be tested + # + # ==== Returns + # * <tt>TrueClass</tt>, <tt>FalseClass</tt> def available_action?(action_name) method_for_action(action_name).present? end diff --git a/actionpack/lib/abstract_controller/callbacks.rb b/actionpack/lib/abstract_controller/callbacks.rb index 44c9ea34ba..5705ab590c 100644 --- a/actionpack/lib/abstract_controller/callbacks.rb +++ b/actionpack/lib/abstract_controller/callbacks.rb @@ -14,7 +14,7 @@ module AbstractController # Override AbstractController::Base's process_action to run the # process_action callbacks around the normal behavior. def process_action(*args) - run_callbacks(:process_action, action_name) do + run_callbacks(:process_action) do super end end @@ -46,7 +46,7 @@ module AbstractController # callbacks. Note that skipping uses Ruby equality, so it's # impossible to skip a callback defined using an anonymous proc # using #skip_filter - def skip_filter(*names, &blk) + def skip_filter(*names) skip_before_filter(*names) skip_after_filter(*names) skip_around_filter(*names) @@ -64,7 +64,7 @@ module AbstractController # ==== Block Parameters # * <tt>name</tt> - The callback to be added # * <tt>options</tt> - A hash of options to be used when adding the callback - def _insert_callbacks(callbacks, block) + def _insert_callbacks(callbacks, block = nil) options = callbacks.last.is_a?(Hash) ? callbacks.pop : {} _normalize_callback_options(options) callbacks.push(block) if block @@ -90,7 +90,7 @@ module AbstractController ## # :method: skip_before_filter # - # :call-seq: skip_before_filter(names, block) + # :call-seq: skip_before_filter(names) # # Skip a before filter. See _insert_callbacks for parameter details. @@ -118,7 +118,7 @@ module AbstractController ## # :method: skip_after_filter # - # :call-seq: skip_after_filter(names, block) + # :call-seq: skip_after_filter(names) # # Skip an after filter. See _insert_callbacks for parameter details. @@ -146,7 +146,7 @@ module AbstractController ## # :method: skip_around_filter # - # :call-seq: skip_around_filter(names, block) + # :call-seq: skip_around_filter(names) # # Skip an around filter. See _insert_callbacks for parameter details. @@ -163,11 +163,11 @@ module AbstractController class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1 # Append a before, after or around filter. See _insert_callbacks # for details on the allowed parameters. - def #{filter}_filter(*names, &blk) # def before_filter(*names, &blk) - _insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options| - set_callback(:process_action, :#{filter}, name, options) # set_callback(:process_action, :before, name, options) - end # end - end # end + def #{filter}_filter(*names, &blk) # def before_filter(*names, &blk) + _insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options| + set_callback(:process_action, :#{filter}, name, options) # set_callback(:process_action, :before, name, options) + end # end + end # end # Prepend a before, after or around filter. See _insert_callbacks # for details on the allowed parameters. @@ -179,11 +179,11 @@ module AbstractController # Skip a before, after or around filter. See _insert_callbacks # for details on the allowed parameters. - def skip_#{filter}_filter(*names, &blk) # def skip_before_filter(*names, &blk) - _insert_callbacks(names, blk) do |name, options| # _insert_callbacks(names, blk) do |name, options| - skip_callback(:process_action, :#{filter}, name, options) # skip_callback(:process_action, :before, name, options) - end # end - end # end + def skip_#{filter}_filter(*names) # def skip_before_filter(*names) + _insert_callbacks(names) do |name, options| # _insert_callbacks(names) do |name, options| + skip_callback(:process_action, :#{filter}, name, options) # skip_callback(:process_action, :before, name, options) + end # end + end # end # *_filter is the same as append_*_filter alias_method :append_#{filter}_filter, :#{filter}_filter # alias_method :append_before_filter, :before_filter 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 77cc4c07d9..d3929b685c 100644 --- a/actionpack/lib/abstract_controller/helpers.rb +++ b/actionpack/lib/abstract_controller/helpers.rb @@ -32,9 +32,9 @@ module AbstractController # @current_user ||= User.find_by_id(session[:user]) # end # - # def logged_in? - # current_user != nil - # end + # def logged_in? + # current_user != nil + # end # end # # In a view: @@ -49,9 +49,9 @@ module AbstractController meths.each do |meth| _helpers.class_eval <<-ruby_eval, __FILE__, __LINE__ + 1 - def #{meth}(*args, &blk) - controller.send(%(#{meth}), *args, &blk) - end + def #{meth}(*args, &blk) # def current_user(*args, &blk) + controller.send(%(#{meth}), *args, &blk) # controller.send(:current_user, *args, &blk) + end # end ruby_eval end end @@ -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/layouts.rb b/actionpack/lib/abstract_controller/layouts.rb index 6a6387632c..c1b3994035 100644 --- a/actionpack/lib/abstract_controller/layouts.rb +++ b/actionpack/lib/abstract_controller/layouts.rb @@ -89,7 +89,7 @@ module AbstractController # class TillController < BankController # layout false # - # In these examples, we have three implicit lookup scenrios: + # In these examples, we have three implicit lookup scenarios: # * The BankController uses the "bank" layout. # * The ExchangeController uses the "exchange" layout. # * The CurrencyController inherits the layout from BankController. @@ -120,6 +120,7 @@ module AbstractController # def writers_and_readers # logged_in? ? "writer_layout" : "reader_layout" # end + # end # # Now when a new request for the index action is processed, the layout will vary depending on whether the person accessing # is logged in or not. @@ -127,7 +128,14 @@ module AbstractController # If you want to use an inline method, such as a proc, do something like this: # # class WeblogController < ActionController::Base - # layout proc{ |controller| controller.logged_in? ? "writer_layout" : "reader_layout" } + # layout proc { |controller| controller.logged_in? ? "writer_layout" : "reader_layout" } + # end + # + # If an argument isn't given to the proc, it's evaluated in the context of + # the current controller anyway. + # + # class WeblogController < ActionController::Base + # layout proc { logged_in? ? "writer_layout" : "reader_layout" } # end # # Of course, the most common way of specifying a layout is still just as a plain template name: @@ -136,8 +144,8 @@ module AbstractController # layout "weblog_standard" # end # - # If no directory is specified for the template name, the template will by default be looked for in <tt>app/views/layouts/</tt>. - # Otherwise, it will be looked up relative to the template root. + # The template will be looked always in <tt>app/views/layouts/</tt> folder. But you can point + # <tt>layouts</tt> folder direct also. <tt>layout "layouts/demo"</tt> is the same as <tt>layout "demo"</tt>. # # Setting the layout to nil forces it to be looked up in the filesystem and fallbacks to the parent behavior if none exists. # Setting it to nil is useful to re-enable template lookup overriding a previous configuration set in the parent: @@ -195,8 +203,7 @@ module AbstractController include Rendering included do - class_attribute :_layout, :_layout_conditions, - :instance_reader => false, :instance_writer => false + class_attribute :_layout, :_layout_conditions, :instance_accessor => false self._layout = nil self._layout_conditions = {} _write_layout_method @@ -238,10 +245,10 @@ module AbstractController # # If the specified layout is a: # String:: the String is the template name - # Symbol:: call the method specified by the symbol, which will return - # the template name + # Symbol:: call the method specified by the symbol, which will return the template name # false:: There is no layout # true:: raise an ArgumentError + # nil:: Force default layout behavior with inheritance # # ==== Parameters # * <tt>layout</tt> - The layout to use. @@ -280,6 +287,10 @@ module AbstractController <<-RUBY lookup_context.find_all("#{_implied_layout_name}", #{prefixes.inspect}).first || super RUBY + else + <<-RUBY + super + RUBY end layout_definition = case _layout @@ -295,12 +306,12 @@ module AbstractController end RUBY when Proc - define_method :_layout_from_proc, &_layout - "_layout_from_proc(self)" + define_method :_layout_from_proc, &_layout + _layout.arity == 0 ? "_layout_from_proc" : "_layout_from_proc(self)" when false nil when true - raise ArgumentError, "Layouts must be specified as a String, Symbol, false, or nil" + raise ArgumentError, "Layouts must be specified as a String, Symbol, Proc, false, or nil" when nil name_clause end @@ -322,7 +333,7 @@ module AbstractController super if _include_layout?(options) - layout = options.key?(:layout) ? options.delete(:layout) : :default + layout = options.delete(:layout) { :default } options[:layout] = _layout_for_option(layout) end end @@ -360,7 +371,7 @@ module AbstractController when false, nil then nil else raise ArgumentError, - "String, true, or false, expected for `layout'; you passed #{name.inspect}" + "String, Proc, :default, true, or false, expected for `layout'; you passed #{name.inspect}" end end diff --git a/actionpack/lib/abstract_controller/logger.rb b/actionpack/lib/abstract_controller/logger.rb index a4e31cd2e5..c31ea6c5b5 100644 --- a/actionpack/lib/abstract_controller/logger.rb +++ b/actionpack/lib/abstract_controller/logger.rb @@ -1,7 +1,7 @@ require "active_support/benchmarkable" module AbstractController - module Logger + module Logger #:nodoc: extend ActiveSupport::Concern included do diff --git a/actionpack/lib/abstract_controller/rendering.rb b/actionpack/lib/abstract_controller/rendering.rb index ddc93464cd..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 @@ -105,6 +115,7 @@ module AbstractController # Find and renders a template based on the options given. # :api: private def _render_template(options) #:nodoc: + lookup_context.rendered_format = nil if options[:formats] view_renderer.render(view_context, options) 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/abstract_controller/url_for.rb b/actionpack/lib/abstract_controller/url_for.rb index e4261068d8..4a95e1f276 100644 --- a/actionpack/lib/abstract_controller/url_for.rb +++ b/actionpack/lib/abstract_controller/url_for.rb @@ -1,10 +1,10 @@ -# Includes +url_for+ into the host class (e.g. an abstract controller or mailer). The class -# has to provide a +RouteSet+ by implementing the <tt>_routes</tt> methods. Otherwise, an -# exception will be raised. -# -# Note that this module is completely decoupled from HTTP - the only requirement is a valid -# <tt>_routes</tt> implementation. module AbstractController + # Includes +url_for+ into the host class (e.g. an abstract controller or mailer). The class + # has to provide a +RouteSet+ by implementing the <tt>_routes</tt> methods. Otherwise, an + # exception will be raised. + # + # Note that this module is completely decoupled from HTTP - the only requirement is a valid + # <tt>_routes</tt> implementation. module UrlFor extend ActiveSupport::Concern include ActionDispatch::Routing::UrlFor diff --git a/actionpack/lib/action_controller.rb b/actionpack/lib/action_controller.rb index a0c54dbd84..8c1f548e47 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 @@ -31,7 +33,6 @@ module ActionController autoload :RequestForgeryProtection autoload :Rescue autoload :Responder - autoload :SessionManagement autoload :Streaming autoload :Testing autoload :UrlFor @@ -47,18 +48,26 @@ module ActionController eager_autoload do autoload :RecordIdentifier end + + def self.eager_load! + super + ActionController::Caching.eager_load! + HTML.eager_load! + end end # All of these simply register additional autoloads require 'action_view' -require 'action_controller/vendor/html-scanner' +require 'action_view/vendor/html-scanner' + +ActiveSupport.on_load(:action_view) do + ActionView::RoutingUrlFor.send(:include, ActionDispatch::Routing::UrlFor) +end # 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/base.rb b/actionpack/lib/action_controller/base.rb index 3b82231b15..f829f5e8a2 100644 --- a/actionpack/lib/action_controller/base.rb +++ b/actionpack/lib/action_controller/base.rb @@ -88,15 +88,6 @@ module ActionController # # Do not put secret information in cookie-based sessions! # - # Other options for session storage: - # - # * ActiveRecord::SessionStore - Sessions are stored in your database, which works better than PStore with multiple app servers and, - # unlike CookieStore, hides your session contents from the user. To use ActiveRecord::SessionStore, set - # - # MyApplication::Application.config.session_store :active_record_store - # - # in your <tt>config/initializers/session_store.rb</tt> and run <tt>script/rails g session_migration</tt>. - # # == Responses # # Each action results in a response, which holds the headers and document to be sent to the user's browser. The actual response @@ -171,6 +162,16 @@ module ActionController class Base < Metal abstract! + # Shortcut helper that returns all the ActionController::Base modules except the ones passed in the argument: + # + # class MetalController + # ActionController::Base.without_modules(:ParamsWrapper, :Streaming).each do |left| + # include left + # end + # end + # + # This gives better control over what you want to exclude and makes it easier + # to create a bare controller class, instead of listing the modules required manually. def self.without_modules(*modules) modules = modules.map do |m| m.is_a?(Symbol) ? ActionController.const_get(m) : m @@ -192,7 +193,6 @@ module ActionController Renderers::All, ConditionalGet, RackDelegation, - SessionManagement, Caching, MimeResponds, ImplicitRender, diff --git a/actionpack/lib/action_controller/caching.rb b/actionpack/lib/action_controller/caching.rb index 112573a38d..be29099fbe 100644 --- a/actionpack/lib/action_controller/caching.rb +++ b/actionpack/lib/action_controller/caching.rb @@ -48,13 +48,15 @@ module ActionController #:nodoc: config.cache_store = ActiveSupport::Cache.lookup_store(store) end - private - - def cache_configured? - perform_caching && cache_store - end + private + def cache_configured? + perform_caching && cache_store + end end + include RackDelegation + include AbstractController::Callbacks + include ConfigMethods include Pages, Actions, Fragments include Sweeping if defined?(ActiveRecord) @@ -70,14 +72,14 @@ module ActionController #:nodoc: request.get? && response.status == 200 end - protected - # Convenience accessor - def cache(key, options = {}, &block) - if cache_configured? - cache_store.fetch(ActiveSupport::Cache.expand_cache_key(key, :controller), options, &block) - else - yield + protected + # Convenience accessor + def cache(key, options = {}, &block) + if cache_configured? + cache_store.fetch(ActiveSupport::Cache.expand_cache_key(key, :controller), options, &block) + else + yield + end end - end end end diff --git a/actionpack/lib/action_controller/caching/actions.rb b/actionpack/lib/action_controller/caching/actions.rb index bd3b0b5df3..0238135bc1 100644 --- a/actionpack/lib/action_controller/caching/actions.rb +++ b/actionpack/lib/action_controller/caching/actions.rb @@ -40,14 +40,14 @@ module ActionController #:nodoc: # # You can modify the default action cache path by passing a # <tt>:cache_path</tt> option. This will be passed directly to - # <tt>ActionCachePath.path_for</tt>. This is handy for actions with + # <tt>ActionCachePath.new</tt>. This is handy for actions with # multiple possible routes that should be cached differently. If a # block is given, it is called with the current controller instance. # # And you can also use <tt>:if</tt> (or <tt>:unless</tt>) to pass a # proc that specifies when the action should be cached. # - # As of Rails 3.0, you can also pass <tt>:expires_in</tt> with a time + # As of Rails 3.0, you can also pass <tt>:expires_in</tt> with a time # interval (in seconds) to schedule expiration of the cached item. # # The following example depicts some of the points made above: @@ -103,8 +103,10 @@ module ActionController #:nodoc: end def _save_fragment(name, options) - content = response_body - content = content.join if content.is_a?(Array) + content = "" + response_body.each do |parts| + content << parts + end if caching_allowed? write_fragment(name, content, options) @@ -131,6 +133,8 @@ module ActionController #:nodoc: end def filter(controller) + cache_layout = @cache_layout.respond_to?(:call) ? @cache_layout.call(controller) : @cache_layout + path_options = if @cache_path.respond_to?(:call) controller.instance_exec(controller, &@cache_path) else @@ -142,13 +146,13 @@ module ActionController #:nodoc: body = controller.read_fragment(cache_path.path, @store_options) unless body - controller.action_has_layout = false unless @cache_layout + controller.action_has_layout = false unless cache_layout yield controller.action_has_layout = true body = controller._save_fragment(cache_path.path, @store_options) end - body = controller.render_to_string(:text => body, :layout => true) unless @cache_layout + body = controller.render_to_string(:text => body, :layout => true) unless cache_layout controller.response_body = body controller.content_type = Mime[cache_path.extension || :html] @@ -168,14 +172,15 @@ module ActionController #:nodoc: options.reverse_merge!(:format => @extension) if options.is_a?(Hash) end - path = controller.url_for(options).split(%r{://}).last + path = controller.url_for(options).split('://', 2).last @path = normalize!(path) end private def normalize!(path) + ext = URI.parser.escape(extension) if extension path << 'index' if path[-1] == ?/ - path << ".#{extension}" if extension and !path.split('?').first.ends_with?(".#{extension}") + path << ".#{ext}" if extension and !path.split('?', 2).first.ends_with?(".#{ext}") URI.parser.unescape(path) end end 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 159f718029..73b8cd383c 100644 --- a/actionpack/lib/action_controller/caching/pages.rb +++ b/actionpack/lib/action_controller/caching/pages.rb @@ -60,7 +60,8 @@ module ActionController #:nodoc: end module ClassMethods - # Expires the page that was cached with the +path+ as a key. Example: + # Expires the page that was cached with the +path+ as a key. + # # expire_page "/lists/show" def expire_page(path) return unless perform_caching @@ -72,7 +73,8 @@ module ActionController #:nodoc: end end - # Manually cache the +content+ in the key determined by +path+. Example: + # Manually cache the +content+ in the key determined by +path+. + # # cache_page "I'm the cached content", "/lists/show" def cache_page(content, path, extension = nil, gzip = Zlib::BEST_COMPRESSION) return unless perform_caching @@ -93,13 +95,11 @@ module ActionController #:nodoc: # # You can also pass a :gzip option to override the class configuration one. # - # Usage: - # # # cache the index action # caches_page :index # # # cache the index action except for JSON requests - # caches_page :index, :if => Proc.new { |c| !c.request.format.json? } + # caches_page :index, :if => Proc.new { !request.format.json? } # # # don't gzip images # caches_page :image, :gzip => false @@ -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 @@ -142,7 +142,8 @@ module ActionController #:nodoc: end end - # Expires the page that was cached with the +options+ as a key. Example: + # Expires the page that was cached with the +options+ as a key. + # # expire_page :controller => "lists", :action => "show" def expire_page(options = {}) return unless self.class.perform_caching @@ -161,7 +162,8 @@ module ActionController #:nodoc: end # Manually cache the +content+ in the key determined by +options+. If no content is provided, the contents of response.body is used. - # If no options are provided, the url of the current request being handled is used. Example: + # If no options are provided, the url of the current request being handled is used. + # # cache_page "I'm the cached content", :controller => "lists", :action => "show" def cache_page(content = nil, options = nil, gzip = Zlib::BEST_COMPRESSION) return unless self.class.perform_caching && caching_allowed? diff --git a/actionpack/lib/action_controller/caching/sweeping.rb b/actionpack/lib/action_controller/caching/sweeping.rb index 49cf70ec21..73291ce083 100644 --- a/actionpack/lib/action_controller/caching/sweeping.rb +++ b/actionpack/lib/action_controller/caching/sweeping.rb @@ -54,6 +54,11 @@ module ActionController #:nodoc: class Sweeper < ActiveRecord::Observer #:nodoc: attr_accessor :controller + def initialize(*args) + super + @controller = nil + end + def before(controller) self.controller = controller callback(:before) if controller.perform_caching @@ -63,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 @@ -79,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}" @@ -88,7 +104,7 @@ module ActionController #:nodoc: end def method_missing(method, *arguments, &block) - return unless @controller + return super unless @controller @controller.__send__(method, *arguments, &block) end end diff --git a/actionpack/lib/action_controller/log_subscriber.rb b/actionpack/lib/action_controller/log_subscriber.rb index 4c76f4c43b..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 @@ -20,7 +19,7 @@ module ActionController status = payload[:status] if status.nil? && payload[:exception].present? - status = Rack::Utils.status_code(ActionDispatch::ExceptionWrapper.new({}, payload[:exception]).status_code) + status = ActionDispatch::ExceptionWrapper.new({}, payload[:exception]).status_code end message = "Completed #{status} #{Rack::Utils::HTTP_STATUS_CODES[status]} in %.0fms" % event.duration message << " (#{additions.join(" | ")})" unless additions.blank? @@ -33,9 +32,7 @@ module ActionController end def send_file(event) - message = "Sent file %s" - message << " (%.1fms)" - info(message % [event.payload[:path], event.duration]) + info("Sent file %s (%.1fms)" % [event.payload[:path], event.duration]) end def redirect_to(event) 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/conditional_get.rb b/actionpack/lib/action_controller/metal/conditional_get.rb index 1645400693..7521deaaca 100644 --- a/actionpack/lib/action_controller/metal/conditional_get.rb +++ b/actionpack/lib/action_controller/metal/conditional_get.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/class/attribute' + module ActionController module ConditionalGet extend ActiveSupport::Concern @@ -5,6 +7,33 @@ module ActionController include RackDelegation include Head + included do + class_attribute :etaggers + self.etaggers = [] + end + + module ClassMethods + # Allows you to consider additional controller-wide information when generating an etag. + # For example, if you serve pages tailored depending on who's logged in at the moment, you + # may want to add the current user id to be part of the etag to prevent authorized displaying + # of cached pages. + # + # === Example + # + # class InvoicesController < ApplicationController + # etag { current_user.try :id } + # + # def show + # # Etag will differ even for the same invoice when it's viewed by a different current_user + # @invoice = Invoice.find(params[:id]) + # fresh_when(@invoice) + # end + # end + def etag(&etagger) + self.etaggers += [etagger] + end + end + # Sets the etag, last_modified, or both on the response and renders a # <tt>304 Not Modified</tt> response if the request is already fresh. # @@ -42,12 +71,12 @@ module ActionController options.assert_valid_keys(:etag, :last_modified, :public) else record = record_or_options - options = { :etag => record, :last_modified => record.try(:updated_at) }.merge(additional_options) + options = { etag: record, last_modified: record.try(:updated_at) }.merge(additional_options) end - response.etag = options[:etag] if options[:etag] - response.last_modified = options[:last_modified] if options[:last_modified] - response.cache_control[:public] = true if options[:public] + response.etag = combine_etags(options[:etag]) if options[:etag] + response.last_modified = options[:last_modified] if options[:last_modified] + response.cache_control[:public] = true if options[:public] head :not_modified if request.fresh?(response) end @@ -108,18 +137,24 @@ module ActionController # Sets a HTTP 1.1 Cache-Control header. Defaults to issuing a <tt>private</tt> instruction, so that # intermediate caches must not cache the response. # - # Examples: # expires_in 20.minutes # expires_in 3.hours, :public => true - # expires_in 3.hours, 'max-stale' => 5.hours, :public => true + # expires_in 3.hours, :public => true, :must_revalidate => true # # This method will overwrite an existing Cache-Control header. # See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html for more possibilities. + # + # The method will also ensure a HTTP Date header for client compatibility. def expires_in(seconds, options = {}) #:doc: - response.cache_control.merge!(:max_age => seconds, :public => options.delete(:public)) + response.cache_control.merge!( + :max_age => seconds, + :public => options.delete(:public), + :must_revalidate => options.delete(:must_revalidate) + ) options.delete(:private) response.cache_control[:extras] = options.map {|k,v| "#{k}=#{v}"} + response.date = Time.now unless response.date? end # Sets a HTTP 1.1 Cache-Control header of <tt>no-cache</tt> so no caching should occur by the browser or @@ -127,5 +162,11 @@ module ActionController def expires_now #:doc: response.cache_control.replace(:no_cache => true) end + + + private + def combine_etags(etag) + [ etag, *etaggers.map { |etagger| instance_exec(&etagger) }.compact ] + end end end diff --git a/actionpack/lib/action_controller/metal/data_streaming.rb b/actionpack/lib/action_controller/metal/data_streaming.rb index 30ddf6c16e..5422cb93c4 100644 --- a/actionpack/lib/action_controller/metal/data_streaming.rb +++ b/actionpack/lib/action_controller/metal/data_streaming.rb @@ -8,15 +8,13 @@ module ActionController #:nodoc: include ActionController::Rendering - DEFAULT_SEND_FILE_OPTIONS = { - :type => 'application/octet-stream'.freeze, - :disposition => 'attachment'.freeze, - }.freeze + DEFAULT_SEND_FILE_TYPE = 'application/octet-stream'.freeze #:nodoc: + DEFAULT_SEND_FILE_DISPOSITION = 'attachment'.freeze #:nodoc: protected # Sends the file. This uses a server-appropriate method (such as X-Sendfile) # via the Rack::Sendfile middleware. The header to use is set via - # config.action_dispatch.x_sendfile_header. + # +config.action_dispatch.x_sendfile_header+. # Your server can also configure this for you by setting the X-Sendfile-Type header. # # Be careful to sanitize the path parameter if it is coming from a web @@ -74,7 +72,27 @@ module ActionController #:nodoc: self.status = options[:status] || 200 self.content_type = options[:content_type] if options.key?(:content_type) - self.response_body = File.open(path, "rb") + self.response_body = FileBody.new(path) + end + + # Avoid having to pass an open file handle as the response body. + # 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 + + def initialize(path) + @to_path = path + end + + # Stream the file's contents if Rack::Sendfile isn't present. + def each + File.open(to_path, 'rb') do |file| + while chunk = file.read(16384) + yield chunk + end + end + end end # Sends the given binary data to the browser. This method is similar to @@ -107,7 +125,7 @@ module ActionController #:nodoc: # # See +send_file+ for more information on HTTP Content-* headers and caching. def send_data(data, options = {}) #:doc: - send_file_headers! options.dup + send_file_headers! options render options.slice(:status, :content_type).merge(:text => data) end @@ -115,15 +133,8 @@ module ActionController #:nodoc: def send_file_headers!(options) type_provided = options.has_key?(:type) - options.update(DEFAULT_SEND_FILE_OPTIONS.merge(options)) - [:type, :disposition].each do |arg| - raise ArgumentError, ":#{arg} option required" if options[arg].nil? - end - - disposition = options[:disposition] - disposition += %(; filename="#{options[:filename]}") if options[:filename] - - content_type = options[:type] + content_type = options.fetch(:type, DEFAULT_SEND_FILE_TYPE) + raise ArgumentError, ":type option required" if content_type.nil? if content_type.is_a?(Symbol) extension = Mime[content_type] @@ -132,15 +143,18 @@ module ActionController #:nodoc: else if !type_provided && options[:filename] # If type wasn't provided, try guessing from file extension. - content_type = Mime::Type.lookup_by_extension(File.extname(options[:filename]).downcase.tr('.','')) || content_type + content_type = Mime::Type.lookup_by_extension(File.extname(options[:filename]).downcase.delete('.')) || content_type end self.content_type = content_type end - headers.merge!( - 'Content-Disposition' => disposition, - 'Content-Transfer-Encoding' => 'binary' - ) + disposition = options.fetch(:disposition, DEFAULT_SEND_FILE_DISPOSITION) + unless disposition.nil? + disposition += %(; filename="#{options[:filename]}") if options[:filename] + headers['Content-Disposition'] = disposition + end + + headers['Content-Transfer-Encoding'] = 'binary' response.sending_file = true diff --git a/actionpack/lib/action_controller/metal/exceptions.rb b/actionpack/lib/action_controller/metal/exceptions.rb index ece9ba3725..3c9d0c86a7 100644 --- a/actionpack/lib/action_controller/metal/exceptions.rb +++ b/actionpack/lib/action_controller/metal/exceptions.rb @@ -2,6 +2,9 @@ module ActionController class ActionControllerError < StandardError #:nodoc: end + class BadRequest < ActionControllerError #:nodoc: + end + class RenderError < ActionControllerError #:nodoc: end @@ -13,9 +16,10 @@ module ActionController end end - class MethodNotAllowed < ActionControllerError #:nodoc: - attr_reader :allowed_methods + class ActionController::UrlGenerationError < RoutingError #:nodoc: + end + class MethodNotAllowed < ActionControllerError #:nodoc: def initialize(*allowed_methods) super("Only #{allowed_methods.to_sentence(:locale => :en)} requests are allowed.") end @@ -30,9 +34,6 @@ module ActionController class MissingFile < ActionControllerError #:nodoc: end - class RenderError < ActionControllerError #:nodoc: - end - class SessionOverflowError < ActionControllerError #:nodoc: DEFAULT_MESSAGE = 'Your session data is larger than the data column in which it is to be stored. You must increase the size of your data column if you intend to store large data.' @@ -43,4 +44,7 @@ module ActionController class UnknownHttpMethod < ActionControllerError #:nodoc: end + + class UnknownFormat < ActionControllerError #:nodoc: + end end 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 69e37d8713..e905a3cf1d 100644 --- a/actionpack/lib/action_controller/metal/force_ssl.rb +++ b/actionpack/lib/action_controller/metal/force_ssl.rb @@ -18,23 +18,45 @@ module ActionController # Force the request to this particular controller or specified actions to be # under HTTPS protocol. # - # Note that this method will not be effective on development environment. + # If you need to disable this for any reason (e.g. development) then you can use + # an +:if+ or +:unless+ condition. + # + # class AccountsController < ApplicationController + # force_ssl :if => :ssl_configured? + # + # def ssl_configured? + # !Rails.env.development? + # end + # end # # ==== Options + # * <tt>host</tt> - Redirect to a different host name # * <tt>only</tt> - The callback should be run only for this action - # * <tt>except<tt> - The callback should be run for all actions except this action + # * <tt>except</tt> - The callback should be run for all actions except this action + # * <tt>if</tt> - A symbol naming an instance method or a proc; the callback + # will be called only when it returns a true value. + # * <tt>unless</tt> - A symbol naming an instance method or a proc; the callback + # will be called only when it returns a false value. def force_ssl(options = {}) host = options.delete(:host) before_filter(options) do - if !request.ssl? && !Rails.env.development? - redirect_options = {:protocol => 'https://', :status => :moved_permanently} - redirect_options.merge!(:host => host) if host - redirect_options.merge!(:params => request.query_parameters) - flash.keep - 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 a618533d09..747e1273be 100644 --- a/actionpack/lib/action_controller/metal/head.rb +++ b/actionpack/lib/action_controller/metal/head.rb @@ -20,6 +20,7 @@ module ActionController options, status = status, nil if status.is_a?(Hash) status ||= options.delete(:status) || :ok location = options.delete(:location) + content_type = options.delete(:content_type) options.each do |key, value| headers[key.to_s.dasherize.split('-').each { |v| v[0] = v[0].chr.upcase }.join('-')] = value.to_s @@ -27,8 +28,28 @@ module ActionController self.status = status self.location = url_for(location) if location - self.content_type = Mime[formats.first] if formats - self.response_body = " " + + 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 + end + + private + # :nodoc: + def include_content?(status) + case status + when 100..199 + false + when 204, 205, 304 + false + else + true + end end end end diff --git a/actionpack/lib/action_controller/metal/helpers.rb b/actionpack/lib/action_controller/metal/helpers.rb index d070eaae5d..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, @@ -16,7 +15,6 @@ module ActionController # Additional helpers can be specified using the +helper+ class method in ActionController::Base or any # controller which inherits from it. # - # ==== Examples # The +to_s+ method from the \Time class can be wrapped in a helper method to display a custom message if # a \Time object is blank: # @@ -52,6 +50,7 @@ module ActionController module Helpers extend ActiveSupport::Concern + class << self; attr_accessor :helpers_path; end include AbstractController::Helpers included do @@ -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 3d46163b74..03b8d8db1a 100644 --- a/actionpack/lib/action_controller/metal/http_authentication.rb +++ b/actionpack/lib/action_controller/metal/http_authentication.rb @@ -1,9 +1,9 @@ require 'base64' -require 'active_support/core_ext/object/blank' module ActionController + # Makes it dead easy to do HTTP Basic, Digest and Token authentication. module HttpAuthentication - # Makes it dead easy to do HTTP \Basic and \Digest authentication. + # Makes it dead easy to do HTTP \Basic authentication. # # === Simple \Basic example # @@ -60,47 +60,6 @@ module ActionController # # assert_equal 200, status # end - # - # === Simple \Digest example - # - # require 'digest/md5' - # class PostsController < ApplicationController - # REALM = "SuperSecret" - # USERS = {"dhh" => "secret", #plain text password - # "dap" => Digest::MD5.hexdigest(["dap",REALM,"secret"].join(":"))} #ha1 digest password - # - # before_filter :authenticate, :except => [:index] - # - # def index - # render :text => "Everyone can see me!" - # end - # - # def edit - # render :text => "I'm only accessible if you know the password" - # end - # - # private - # def authenticate - # authenticate_or_request_with_http_digest(REALM) do |username| - # USERS[username] - # end - # end - # end - # - # === Notes - # - # The +authenticate_or_request_with_http_digest+ block must return the user's password - # or the ha1 digest hash so the framework can appropriately hash to check the user's - # credentials. Returning +nil+ will cause authentication to fail. - # - # Storing the ha1 hash: MD5(username:realm:password), is better than storing a plain password. If - # the password file or database is compromised, the attacker would be able to use the ha1 hash to - # authenticate as the user at this +realm+, but would not have the user's password to try using at - # other sites. - # - # In rare instances, web servers or front proxies strip authorization headers before - # they reach your application. You can debug this situation by logging all environment - # variables, and check for HTTP_AUTHORIZATION, amongst others. module Basic extend self @@ -155,6 +114,48 @@ module ActionController end end + # Makes it dead easy to do HTTP \Digest authentication. + # + # === Simple \Digest example + # + # require 'digest/md5' + # class PostsController < ApplicationController + # REALM = "SuperSecret" + # USERS = {"dhh" => "secret", #plain text password + # "dap" => Digest::MD5.hexdigest(["dap",REALM,"secret"].join(":"))} #ha1 digest password + # + # before_filter :authenticate, :except => [:index] + # + # def index + # render :text => "Everyone can see me!" + # end + # + # def edit + # render :text => "I'm only accessible if you know the password" + # end + # + # private + # def authenticate + # authenticate_or_request_with_http_digest(REALM) do |username| + # USERS[username] + # end + # end + # end + # + # === Notes + # + # The +authenticate_or_request_with_http_digest+ block must return the user's password + # or the ha1 digest hash so the framework can appropriately hash to check the user's + # credentials. Returning +nil+ will cause authentication to fail. + # + # Storing the ha1 hash: MD5(username:realm:password), is better than storing a plain password. If + # the password file or database is compromised, the attacker would be able to use the ha1 hash to + # authenticate as the user at this +realm+, but would not have the user's password to try using at + # other sites. + # + # In rare instances, web servers or front proxies strip authorization headers before + # they reach your application. You can debug this situation by logging all environment + # variables, and check for HTTP_AUTHORIZATION, amongst others. module Digest extend self @@ -192,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| @@ -227,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(/^"|"$/,'').gsub(/'/, '')] + [key.strip, value.to_s.gsub(/^"|"$/,'').delete('\'')] end] end @@ -263,7 +264,7 @@ module ActionController # The quality of the implementation depends on a good choice. # A nonce might, for example, be constructed as the base 64 encoding of # - # => time-stamp H(time-stamp ":" ETag ":" private-key) + # time-stamp H(time-stamp ":" ETag ":" private-key) # # where time-stamp is a server-generated time or other non-repeating value, # ETag is the value of the HTTP ETag header associated with the requested entity, @@ -279,7 +280,7 @@ module ActionController # # An implementation might choose not to accept a previously used nonce or a previously used digest, in order to # protect against a replay attack. Or, an implementation might choose to use one-time nonces or digests for - # POST or PUT requests and a time-stamp for GET requests. For more details on the issues involved see Section 4 + # POST, PUT, or PATCH requests and a time-stamp for GET requests. For more details on the issues involved see Section 4 # of this document. # # The nonce is opaque to the client. Composed of Time, and hash of Time with secret @@ -293,7 +294,7 @@ module ActionController end # Might want a shorter timeout depending on whether the request - # is a PUT or POST, and if client is browser or web service. + # is a PATCH, PUT, or POST, and if client is browser or web service. # Can be much shorter if the Stale directive is implemented. This would # allow a user to use new nonce without prompting user again for their # username and password. @@ -370,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 @@ -399,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? @@ -430,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/instrumentation.rb b/actionpack/lib/action_controller/metal/instrumentation.rb index 640ebf5f00..ca4ae532ca 100644 --- a/actionpack/lib/action_controller/metal/instrumentation.rb +++ b/actionpack/lib/action_controller/metal/instrumentation.rb @@ -11,6 +11,7 @@ module ActionController extend ActiveSupport::Concern include AbstractController::Logger + include ActionController::RackDelegation attr_internal :view_runtime 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 80ecc16d53..18ae2c3bfc 100644 --- a/actionpack/lib/action_controller/metal/mime_responds.rb +++ b/actionpack/lib/action_controller/metal/mime_responds.rb @@ -1,13 +1,9 @@ require 'abstract_controller/collector' -require 'active_support/core_ext/class/attribute' -require 'active_support/core_ext/object/inclusion' module ActionController #:nodoc: module MimeResponds extend ActiveSupport::Concern - include ActionController::ImplicitRender - included do class_attribute :responder, :mimes_for_respond_to self.responder = ActionController::Responder @@ -18,8 +14,6 @@ module ActionController #:nodoc: # Defines mime types that are rendered by default when invoking # <tt>respond_with</tt>. # - # Examples: - # # respond_to :html, :xml, :json # # Specifies that all actions in the controller respond to requests @@ -58,7 +52,7 @@ module ActionController #:nodoc: # Clear all mime types in <tt>respond_to</tt>. # def clear_respond_to - self.mimes_for_respond_to = ActiveSupport::OrderedHash.new.freeze + self.mimes_for_respond_to = Hash.new.freeze end end @@ -76,7 +70,7 @@ module ActionController #:nodoc: # # respond_to do |format| # format.html - # format.xml { render :xml => @people.to_xml } + # format.xml { render :xml => @people } # end # end # @@ -186,31 +180,117 @@ 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? if collector = retrieve_collector_from_mimes(mimes, &block) response = collector.response - response ? response.call : default_render({}) + response ? response.call : render({}) end end - # respond_with wraps a resource around a responder for default representation. - # First it invokes respond_to, if a response cannot be found (ie. no block - # for the request was given and template was not available), it instantiates - # an ActionController::Responder with the controller and resource. + # For a given controller action, respond_with generates an appropriate + # response based on the mime-type requested by the client. # - # ==== Example + # If the method is called with just a resource, as in this example - # - # def index - # @users = User.all - # respond_with(@users) + # class PeopleController < ApplicationController + # respond_to :html, :xml, :json + # + # def index + # @people = Person.all + # respond_with @people + # end # end # - # It also accepts a block to be given. It's used to overwrite a default - # response: + # then the mime-type of the response is typically selected based on the + # request's Accept header and the set of available formats declared + # by previous calls to the controller's class method +respond_to+. Alternatively + # the mime-type can be selected by explicitly setting <tt>request.format</tt> in + # the controller. + # + # If an acceptable format is not identified, the application returns a + # '406 - not acceptable' status. Otherwise, the default response is to render + # a template named after the current action and the selected format, + # e.g. <tt>index.html.erb</tt>. If no template is available, the behavior + # depends on the selected format: + # + # * for an html response - if the request method is +get+, an exception + # is raised but for other requests such as +post+ the response + # depends on whether the resource has any validation errors (i.e. + # assuming that an attempt has been made to save the resource, + # e.g. by a +create+ action) - + # 1. If there are no errors, i.e. the resource + # was saved successfully, the response +redirect+'s to the resource + # i.e. its +show+ action. + # 2. If there are validation errors, the response + # renders a default action, which is <tt>:new</tt> for a + # +post+ request or <tt>:edit</tt> for +put+. + # Thus an example like this - + # + # respond_to :html, :xml + # + # def create + # @user = User.new(params[:user]) + # flash[:notice] = 'User was successfully created.' if @user.save + # respond_with(@user) + # end + # + # is equivalent, in the absence of <tt>create.html.erb</tt>, to - + # + # def create + # @user = User.new(params[:user]) + # respond_to do |format| + # if @user.save + # flash[:notice] = 'User was successfully created.' + # format.html { redirect_to(@user) } + # format.xml { render :xml => @user } + # else + # format.html { render :action => "new" } + # format.xml { render :xml => @user } + # end + # end + # end + # + # * for a javascript request - if the template isn't found, an exception is + # raised. + # * for other requests - i.e. data formats such as xml, json, csv etc, if + # the resource passed to +respond_with+ responds to <code>to_<format></code>, + # the method attempts to render the resource in the requested format + # directly, e.g. for an xml request, the response is equivalent to calling + # <code>render :xml => resource</code>. + # + # === Nested resources + # + # As outlined above, the +resources+ argument passed to +respond_with+ + # can play two roles. It can be used to generate the redirect url + # for successful html requests (e.g. for +create+ actions when + # no template exists), while for formats other than html and javascript + # it is the object that gets rendered, by being converted directly to the + # required format (again assuming no template exists). + # + # For redirecting successful html requests, +respond_with+ also supports + # the use of nested resources, which are supplied in the same way as + # in <code>form_for</code> and <code>polymorphic_url</code>. For example - + # + # def create + # @project = Project.find(params[:project_id]) + # @task = @project.comments.build(params[:task]) + # flash[:notice] = 'Task was successfully created.' if @task.save + # respond_with(@project, @task) + # end + # + # This would cause +respond_with+ to redirect to <code>project_task_url</code> + # instead of <code>task_url</code>. For request formats other than html or + # javascript, if multiple resources are passed in this way, it is the last + # one specified that is rendered. + # + # === Customizing response behavior + # + # Like +respond_to+, +respond_with+ may also be called with a block that + # can be used to overwrite any of the default responses, e.g. - # # def create # @user = User.new(params[:user]) @@ -221,30 +301,32 @@ module ActionController #:nodoc: # end # end # - # All options given to respond_with are sent to the underlying responder, - # except for the option :responder itself. Since the responder interface - # is quite simple (it just needs to respond to call), you can even give - # a proc to it. - # - # In order to use respond_with, first you need to declare the formats your - # controller responds to in the class level with a call to <tt>respond_to</tt>. - # + # The argument passed to the block is an ActionController::MimeResponds::Collector + # object which stores the responses for the formats defined within the + # block. Note that formats with responses defined explicitly in this way + # do not have to first be declared using the class method +respond_to+. + # + # Also, a hash passed to +respond_with+ immediately after the specified + # resource(s) is interpreted as a set of options relevant to all + # formats. Any option accepted by +render+ can be used, e.g. + # respond_with @people, :status => 200 + # However, note that these options are ignored after an unsuccessful attempt + # to save a resource, e.g. when automatically rendering <tt>:new</tt> + # after a post request. + # + # Two additional options are relevant specifically to +respond_with+ - + # 1. <tt>:location</tt> - overwrites the default redirect location used after + # a successful html +post+ request. + # 2. <tt>:action</tt> - overwrites the default render action used after an + # unsuccessful html +post+ request. def respond_with(*resources, &block) raise "In order to use respond_with, first you need to declare the formats your " << "controller responds to in the class level" if self.class.mimes_for_respond_to.empty? if collector = retrieve_collector_from_mimes(&block) options = resources.size == 1 ? {} : resources.extract_options! - - if defined_response = collector.response - if action = options.delete(:action) - render :action => action - else - defined_response.call - end - else - (options.delete(:responder) || self.class.responder).call(self, resources, options) - end + options[:default_response] = collector.response + (options.delete(:responder) || self.class.responder).call(self, resources, options) end end @@ -252,7 +334,6 @@ module ActionController #:nodoc: # Collect mimes declared in the class method respond_to valid for the # current action. - # def collect_mimes_from_class_level #:nodoc: action = action_name.to_s @@ -260,18 +341,21 @@ 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 end end - # Collects mimes and return the response for the negotiated format. Returns - # nil if :not_acceptable was sent to the client. + # Returns a Collector object containing the appropriate mime-type response + # for the current request, based on the available responses defined by a block. + # In typical usage this is the block passed to +respond_with+ or +respond_to+. # + # Sends :not_acceptable to the client and returns nil if no suitable format + # is available. def retrieve_collector_from_mimes(mimes=nil, &block) #:nodoc: mimes ||= collect_mimes_from_class_level collector = Collector.new(mimes) @@ -280,15 +364,37 @@ module ActionController #:nodoc: if format self.content_type ||= format.to_s - lookup_context.freeze_formats([format.to_sym]) + lookup_context.formats = [format.to_sym] + lookup_context.rendered_format = lookup_context.formats.first collector else - head :not_acceptable - nil + raise ActionController::UnknownFormat end end - class Collector #:nodoc: + # A container for responses available from the current controller for + # requests for different mime-types sent to a particular action. + # + # The public controller methods +respond_with+ and +respond_to+ may be called + # with a block that is used to define responses to different mime-types, e.g. + # for +respond_to+ : + # + # respond_to do |format| + # format.html + # format.xml { render :xml => @people } + # end + # + # In this usage, the argument passed to the block (+format+ above) is an + # instance of the ActionController::MimeResponds::Collector class. This + # object serves as a container in which available responses can be stored by + # calling any of the dynamically generated, mime-type-specific methods such + # as +html+, +xml+ etc on the Collector. Each response is represented by a + # corresponding block if present. + # + # A subsequent call to #negotiate_format(request) will enable the Collector + # to determine which specific mime-type it should respond with for the current + # request, with this response then being accessible by calling #response. + class Collector include AbstractController::Collector attr_accessor :order, :format diff --git a/actionpack/lib/action_controller/metal/params_wrapper.rb b/actionpack/lib/action_controller/metal/params_wrapper.rb index fa760f2658..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' @@ -48,7 +47,7 @@ module ActionController # method attribute_names. # # If you're going to pass the parameters to an +ActiveModel+ object (such as - # +User.new(params[:user])+), you might consider passing the model class to + # <tt>User.new(params[:user])</tt>), you might consider passing the model class to # the method instead. The +ParamsWrapper+ will actually try to determine the # list of attribute names from the model and only wrap those attributes: # @@ -66,7 +65,7 @@ module ActionController # class Admin::UsersController < ApplicationController # end # - # will try to check if +Admin::User+ or +User+ model exists, and use it to + # will try to check if <tt>Admin::User</tt> or +User+ model exists, and use it to # determine the wrapper key respectively. If both models don't exist, # it will then fallback to use +user+ as the key. module ParamsWrapper @@ -166,8 +165,9 @@ module ActionController unless options[:include] || options[:exclude] model ||= _default_wrap_model - if model.respond_to?(:accessible_attributes) && model.accessible_attributes.present? - options[:include] = model.accessible_attributes.to_a + role = options.fetch(:as, :default) + if model.respond_to?(:accessible_attributes) && model.accessible_attributes(role).present? + options[:include] = model.accessible_attributes(role).to_a elsif model.respond_to?(:attribute_names) && model.attribute_names.present? options[:include] = model.attribute_names end @@ -192,7 +192,8 @@ module ActionController def process_action(*args) if _wrapper_enabled? wrapped_hash = _wrap_parameters request.request_parameters - wrapped_filtered_hash = _wrap_parameters request.filtered_parameters + wrapped_keys = request.request_parameters.keys + wrapped_filtered_hash = _wrap_parameters request.filtered_parameters.slice(*wrapped_keys) # This will make the wrapped hash accessible from controller and view request.parameters.merge! wrapped_hash 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/redirecting.rb b/actionpack/lib/action_controller/metal/redirecting.rb index b07742e0e1..ee0e69d87c 100644 --- a/actionpack/lib/action_controller/metal/redirecting.rb +++ b/actionpack/lib/action_controller/metal/redirecting.rb @@ -24,7 +24,6 @@ module ActionController # * <tt>:back</tt> - Back to the page that issued the request. Useful for forms that are triggered from multiple places. # Short-hand for <tt>redirect_to(request.env["HTTP_REFERER"])</tt> # - # Examples: # redirect_to :action => "show", :id => 5 # redirect_to post # redirect_to "http://www.rubyonrails.org" @@ -35,7 +34,6 @@ module ActionController # # The redirection happens as a "302 Moved" header unless otherwise specified. # - # Examples: # redirect_to post_url(@post), :status => :found # redirect_to :action=>'atom', :status => :moved_permanently # redirect_to post_url(@post), :status => 301 @@ -45,10 +43,18 @@ module ActionController # integer, or a symbol representing the downcased, underscored and symbolized description. # Note that the status code must be a 3xx HTTP code, or redirection will not occur. # + # If you are using XHR requests other than GET or POST and redirecting after the + # request then some browsers will follow the redirect using the original request + # method. This may lead to undesirable behavior such as a double DELETE. To work + # around this you can return a <tt>303 See Other</tt> status code which will be + # followed using a GET request. + # + # redirect_to posts_url, :status => :see_other + # redirect_to :action => 'index', :status => 303 + # # It is also possible to assign a flash message as part of the redirection. There are two special accessors for the commonly used flash names # +alert+ and +notice+ as well as a general purpose +flash+ bucket. # - # Examples: # redirect_to post_url(@post), :alert => "Watch it, mister!" # redirect_to post_url(@post), :status=> :found, :notice => "Pay attention to the road" # redirect_to post_url(@post), :status => 301, :flash => { :updated_post_id => @post.id } @@ -59,6 +65,7 @@ module ActionController def redirect_to(options = {}, response_status = {}) #:doc: raise ActionControllerError.new("Cannot redirect to nil!") unless options raise AbstractController::DoubleRenderError if response_body + logger.debug { "Redirected by #{caller(1).first rescue "unknown"}" } if logger self.status = _extract_redirect_to_status(options, response_status) self.location = _compute_redirect_to_location(options) @@ -93,7 +100,7 @@ module ActionController _compute_redirect_to_location options.call else url_for(options) - end.gsub(/[\r\n]/, '') + end.delete("\0\r\n") end end end diff --git a/actionpack/lib/action_controller/metal/renderers.rb b/actionpack/lib/action_controller/metal/renderers.rb index 6e9ce450ac..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 @@ -49,7 +47,6 @@ module ActionController # is the value paired with its key and the second is the remaining # hash of options passed to +render+. # - # === Example # Create a csv renderer: # # ActionController::Renderers.add :csv do |obj, options| @@ -91,9 +88,14 @@ module ActionController add :json do |json, options| json = json.to_json(options) unless json.kind_of?(String) - json = "#{options[:callback]}(#{json})" unless options[:callback].blank? - self.content_type ||= Mime::JSON - json + + if options[:callback].present? + self.content_type ||= Mime::JS + "#{options[:callback]}(#{json})" + else + self.content_type ||= Mime::JSON + json + end end add :js do |js, options| diff --git a/actionpack/lib/action_controller/metal/rendering.rb b/actionpack/lib/action_controller/metal/rendering.rb index a677cdf15d..c5e7d4e357 100644 --- a/actionpack/lib/action_controller/metal/rendering.rb +++ b/actionpack/lib/action_controller/metal/rendering.rb @@ -14,7 +14,7 @@ module ActionController def render(*args) #:nodoc: raise ::AbstractController::DoubleRenderError if response_body super - self.content_type ||= Mime[formats.first].to_s + self.content_type ||= Mime[lookup_context.rendered_format].to_s response_body end diff --git a/actionpack/lib/action_controller/metal/request_forgery_protection.rb b/actionpack/lib/action_controller/metal/request_forgery_protection.rb index afa9243f02..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,10 +13,23 @@ 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. - # You can customize the error message by editing public/422.html. # # The token parameter is named <tt>authenticity_token</tt> by default. The name and # value of this token must be added to every layout that renders forms by including @@ -37,6 +49,10 @@ module ActionController #:nodoc: config_accessor :request_forgery_protection_token self.request_forgery_protection_token ||= :authenticity_token + # Controls how unverified request will be handled + config_accessor :request_forgery_protection_method + self.request_forgery_protection_method ||= :reset_session + # Controls whether request forgery protection is turned on or not. Turned off by default only in test mode. config_accessor :allow_forgery_protection self.allow_forgery_protection = true if allow_forgery_protection.nil? @@ -48,8 +64,6 @@ module ActionController #:nodoc: module ClassMethods # Turn on request forgery protection. Bear in mind that only non-GET, HTML/JavaScript requests are checked. # - # Example: - # # class FooController < ApplicationController # protect_from_forgery :except => :index # @@ -64,8 +78,10 @@ module ActionController #:nodoc: # Valid Options: # # * <tt>:only/:except</tt> - Passed to the <tt>before_filter</tt> call. Set which actions are verified. + # * <tt>:with</tt> - Set the method to handle unverified request. Valid values: <tt>:exception</tt> and <tt>:reset_session</tt> (default). def protect_from_forgery(options = {}) self.request_forgery_protection_token ||= :authenticity_token + self.request_forgery_protection_method = options.delete(:with) if options.key?(:with) prepend_before_filter :verify_authenticity_token, options end end @@ -80,9 +96,19 @@ module ActionController #:nodoc: end # This is the method that defines the application behavior when a request is found to be unverified. - # By default, \Rails resets the session when it finds an unverified request. + # By default, \Rails uses <tt>request_forgery_protection_method</tt> when it finds an unverified request: + # + # * <tt>:reset_session</tt> - Resets the session. + # * <tt>:exception</tt>: - Raises ActionController::InvalidAuthenticityToken exception. def handle_unverified_request - reset_session + case request_forgery_protection_method + when :exception + raise ActionController::InvalidAuthenticityToken + when :reset_session + reset_session + else + raise ArgumentError, 'Invalid request forgery protection method, use :exception or :reset_session' + end end # Returns true or false if a request is verified. Checks: diff --git a/actionpack/lib/action_controller/metal/responder.rb b/actionpack/lib/action_controller/metal/responder.rb index 4ad64bff20..42a0959a58 100644 --- a/actionpack/lib/action_controller/metal/responder.rb +++ b/actionpack/lib/action_controller/metal/responder.rb @@ -53,7 +53,7 @@ module ActionController #:nodoc: # end # end # - # The same happens for PUT and DELETE requests. + # The same happens for PATCH/PUT and DELETE requests. # # === Nested resources # @@ -63,7 +63,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) # end @@ -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 @@ -102,7 +102,7 @@ module ActionController #:nodoc: # # def create # @project = Project.find(params[:project_id]) - # @task = @project.comments.build(params[:task]) + # @task = @project.tasks.build(params[:task]) # respond_with(@project, @task, :status => 201) do |format| # if @task.save # flash[:notice] = 'Task was successfully created.' @@ -116,8 +116,9 @@ module ActionController #:nodoc: class Responder attr_reader :controller, :request, :format, :resource, :resources, :options - ACTIONS_FOR_VERBS = { + DEFAULT_ACTIONS_FOR_VERBS = { :post => :new, + :patch => :edit, :put => :edit } @@ -129,10 +130,11 @@ module ActionController #:nodoc: @resources = resources @options = options @action = options.delete(:action) + @default_response = options.delete(:default_response) end delegate :head, :render, :redirect_to, :to => :controller - delegate :get?, :post?, :put?, :delete?, :to => :request + delegate :get?, :post?, :patch?, :put?, :delete?, :to => :request # Undefine :to_json and :to_yaml since it's defined on Object undef_method(:to_json) if method_defined?(:to_json) @@ -171,7 +173,7 @@ module ActionController #:nodoc: # responds to :to_format and display it. # def to_format - if get? || !has_errors? + if get? || !has_errors? || response_overridden? default_render else display_errors @@ -225,7 +227,11 @@ module ActionController #:nodoc: # controller. # def default_render - controller.default_render(options) + if @default_response + @default_response.call(options) + else + controller.default_render(options) + end end # Display is just a shortcut to render a resource with the current format. @@ -259,19 +265,23 @@ module ActionController #:nodoc: resource.respond_to?(:errors) && !resource.errors.empty? end - # By default, render the <code>:edit</code> action for HTML requests with failure, unless - # the verb is POST. + # By default, render the <code>:edit</code> action for HTML requests with errors, unless + # the verb was POST. # def default_action - @action ||= ACTIONS_FOR_VERBS[request.request_method_symbol] + @action ||= DEFAULT_ACTIONS_FOR_VERBS[request.request_method_symbol] end def resource_errors - respond_to?("#{format}_resource_errors") ? send("#{format}_resource_errors") : resource.errors + respond_to?("#{format}_resource_errors", true) ? send("#{format}_resource_errors") : resource.errors end def json_resource_errors {:errors => resource.errors} end + + def response_overridden? + @default_response.present? + end end end diff --git a/actionpack/lib/action_controller/metal/session_management.rb b/actionpack/lib/action_controller/metal/session_management.rb deleted file mode 100644 index 91d89ff9a4..0000000000 --- a/actionpack/lib/action_controller/metal/session_management.rb +++ /dev/null @@ -1,9 +0,0 @@ -module ActionController #:nodoc: - module SessionManagement #:nodoc: - extend ActiveSupport::Concern - - module ClassMethods - - end - end -end diff --git a/actionpack/lib/action_controller/metal/streaming.rb b/actionpack/lib/action_controller/metal/streaming.rb index e9783e6919..9f3c997024 100644 --- a/actionpack/lib/action_controller/metal/streaming.rb +++ b/actionpack/lib/action_controller/metal/streaming.rb @@ -139,17 +139,14 @@ 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 +ActionDispatch::ClosedError+ - # will be raised, showing those objects are closed for modification. - # # == Middlewares # # Middlewares that need to manipulate the body won't work with streaming. # You should disable those middlewares whenever streaming in development - # or production. For instance, +Rack::Bug+ won't work when streaming as it + # or production. For instance, <tt>Rack::Bug</tt> won't work when streaming as it # needs to inject contents in the HTML body. # - # Also +Rack::Cache+ won't work with streaming as it does not support + # Also <tt>Rack::Cache</tt> won't work with streaming as it does not support # streaming bodies yet. Whenever streaming Cache-Control is automatically # set to "no-cache". # @@ -162,7 +159,7 @@ module ActionController #:nodoc: # Currently, when an exception happens in development or production, Rails # will automatically stream to the client: # - # "><script type="text/javascript">window.location = "/500.html"</script></html> + # "><script>window.location = "/500.html"</script></html> # # The first two characters (">) are required in case the exception happens # while rendering attributes for a given tag. You can check the real cause 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 0b40b1fc4c..0cdd17bc2e 100644 --- a/actionpack/lib/action_controller/metal/url_for.rb +++ b/actionpack/lib/action_controller/metal/url_for.rb @@ -1,25 +1,22 @@ -# Includes +url_for+ into the host class. The class has to provide a +RouteSet+ by implementing -# the <tt>_routes</tt> method. Otherwise, an exception will be raised. -# -# In addition to <tt>AbstractController::UrlFor</tt>, this module accesses the HTTP layer to define -# url options like the +host+. In order to do so, this module requires the host class -# to implement +env+ and +request+, which need to be a Rack-compatible. -# -# Example: -# -# class RootUrl -# include ActionController::UrlFor -# include Rails.application.routes.url_helpers -# -# delegate :env, :request, :to => :controller -# -# def initialize(controller) -# @controller = controller -# @url = root_path # named route from the application. -# end -# end -# module ActionController + # Includes +url_for+ into the host class. The class has to provide a +RouteSet+ by implementing + # the <tt>_routes</tt> method. Otherwise, an exception will be raised. + # + # In addition to <tt>AbstractController::UrlFor</tt>, this module accesses the HTTP layer to define + # url options like the +host+. In order to do so, this module requires the host class + # to implement +env+ and +request+, which need to be a Rack-compatible. + # + # class RootUrl + # include ActionController::UrlFor + # include Rails.application.routes.url_helpers + # + # delegate :env, :request, :to => :controller + # + # def initialize(controller) + # @controller = controller + # @url = root_path # named route from the application. + # end + # end module UrlFor extend ActiveSupport::Concern @@ -30,18 +27,23 @@ 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 @_url_options end end - end end 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/railtie.rb b/actionpack/lib/action_controller/railtie.rb index a288e69649..3ecc105e22 100644 --- a/actionpack/lib/action_controller/railtie.rb +++ b/actionpack/lib/action_controller/railtie.rb @@ -3,33 +3,34 @@ require "action_controller" require "action_dispatch/railtie" require "action_view/railtie" require "abstract_controller/railties/routes_helpers" -require "action_controller/railties/paths" +require "action_controller/railties/helpers" module ActionController - class Railtie < Rails::Railtie + class Railtie < Rails::Railtie #:nodoc: config.action_controller = ActiveSupport::OrderedOptions.new - initializer "action_controller.logger" do - ActiveSupport.on_load(:action_controller) { self.logger ||= Rails.logger } - end - - initializer "action_controller.initialize_framework_caches" do - ActiveSupport.on_load(:action_controller) { self.cache_store ||= Rails.cache } - end + config.eager_load_namespaces << ActionController initializer "action_controller.assets_config", :group => :all do |app| app.config.action_controller.assets_dir ||= app.config.paths["public"].first end + initializer "action_controller.set_helpers_path" do |app| + ActionController::Helpers.helpers_path = app.helpers_paths + end + initializer "action_controller.set_configs" do |app| paths = app.config.paths options = app.config.action_controller + options.logger ||= Rails.logger + options.cache_store ||= Rails.cache + options.javascripts_dir ||= paths["public/javascripts"].first options.stylesheets_dir ||= paths["public/stylesheets"].first options.page_cache_directory ||= paths["public"].first - # make sure readers methods get compiled + # Ensure readers methods get compiled options.asset_path ||= app.config.asset_path options.asset_host ||= app.config.asset_host options.relative_url_root ||= app.config.relative_url_root @@ -37,8 +38,16 @@ module ActionController ActiveSupport.on_load(:action_controller) do include app.routes.mounted_helpers extend ::AbstractController::Railties::RoutesHelpers.with(app.routes) - extend ::ActionController::Railties::Paths.with(app) - options.each { |k,v| send("#{k}=", v) } + extend ::ActionController::Railties::Helpers + + options.each do |k,v| + k = "#{k}=" + if respond_to?(k) + send(k, v) + elsif !Base.respond_to?(k) + raise "Invalid option key: #{k}" + end + end end end diff --git a/actionpack/lib/action_controller/railties/helpers.rb b/actionpack/lib/action_controller/railties/helpers.rb new file mode 100644 index 0000000000..3985c6b273 --- /dev/null +++ b/actionpack/lib/action_controller/railties/helpers.rb @@ -0,0 +1,22 @@ +module ActionController + module Railties + module Helpers + def inherited(klass) + super + return unless klass.respond_to?(:helpers_path=) + + if namespace = klass.parents.detect { |m| m.respond_to?(:railtie_helpers_paths) } + paths = namespace.railtie_helpers_paths + else + paths = ActionController::Helpers.helpers_path + end + + klass.helpers_path = paths + + if klass.superclass == ActionController::Base && ActionController::Base.include_all_helpers + klass.helper :all + end + end + end + end +end diff --git a/actionpack/lib/action_controller/railties/paths.rb b/actionpack/lib/action_controller/railties/paths.rb deleted file mode 100644 index bbe63149ad..0000000000 --- a/actionpack/lib/action_controller/railties/paths.rb +++ /dev/null @@ -1,25 +0,0 @@ -module ActionController - module Railties - module Paths - def self.with(app) - Module.new do - define_method(:inherited) do |klass| - super(klass) - - if namespace = klass.parents.detect { |m| m.respond_to?(:railtie_helpers_paths) } - paths = namespace.railtie_helpers_paths - else - paths = app.helpers_paths - end - - klass.helpers_path = paths - - if klass.superclass == ActionController::Base && ActionController::Base.include_all_helpers - klass.helper :all - end - end - end - end - end - end -end diff --git a/actionpack/lib/action_controller/record_identifier.rb b/actionpack/lib/action_controller/record_identifier.rb index 9c38ff44d8..bffd2a02d0 100644 --- a/actionpack/lib/action_controller/record_identifier.rb +++ b/actionpack/lib/action_controller/record_identifier.rb @@ -1,85 +1,20 @@ -require 'active_support/core_ext/module' +require 'active_support/deprecation' +require 'action_view/record_identifier' module ActionController - # The record identifier encapsulates a number of naming conventions for dealing with records, like Active Records or - # Active Resources or pretty much any other model type that has an id. These patterns are then used to try elevate - # the view actions to a higher logical level. Example: - # - # # routes - # resources :posts - # - # # view - # <%= div_for(post) do %> <div id="post_45" class="post"> - # <%= post.body %> What a wonderful world! - # <% end %> </div> - # - # # controller - # def update - # post = Post.find(params[:id]) - # post.update_attributes(params[:post]) - # - # redirect_to(post) # Calls polymorphic_url(post) which in turn calls post_url(post) - # end - # - # As the example above shows, you can stop caring to a large extent what the actual id of the post is. - # You just know that one is being assigned and that the subsequent calls in redirect_to expect that - # same naming convention and allows you to write less code if you follow it. module RecordIdentifier - extend self + MESSAGE = 'method will no longer be included by default in controllers since Rails 4.1. ' + + 'If you would like to use it in controllers, please include ' + + 'ActionView::RecodIdentifier module.' - JOIN = '_'.freeze - NEW = 'new'.freeze - - # The DOM class convention is to use the singular form of an object or class. Examples: - # - # dom_class(post) # => "post" - # dom_class(Person) # => "person" - # - # If you need to address multiple instances of the same class in the same view, you can prefix the dom_class: - # - # 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) - prefix ? "#{prefix}#{JOIN}#{singular}" : singular - end - - # The DOM id convention is to use the singular form of an object or class with the id following an underscore. - # If no id is found, prefix with "new_" instead. Examples: - # - # dom_id(Post.find(45)) # => "post_45" - # dom_id(Post.new) # => "new_post" - # - # If you need to address multiple instances of the same class in the same view, you can prefix the dom_id: - # - # dom_id(Post.find(45), :edit) # => "edit_post_45" def dom_id(record, prefix = nil) - if record_id = record_key_for_dom_id(record) - "#{dom_class(record, prefix)}#{JOIN}#{record_id}" - else - dom_class(record, prefix || NEW) - end - end - - protected - - # Returns a string representation of the key attribute(s) that is suitable for use in an HTML DOM id. - # This can be overwritten to customize the default generated string representation if desired. - # If you need to read back a key from a dom_id in order to query for the underlying database record, - # you should write a helper like 'person_record_from_dom_id' that will extract the key either based - # on the default implementation (which just joins all key attributes with '_') or on your own - # overwritten version of the method. By default, this implementation passes the key string through a - # 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 ? sanitize_dom_id(key.join('_')) : key + ActiveSupport::Deprecation.warn 'dom_id ' + MESSAGE + ActionView::RecordIdentifier.dom_id(record, prefix) end - # Replaces characters that are invalid in HTML DOM ids with valid ones. - def sanitize_dom_id(candidate_id) - candidate_id # TODO implement conversion to valid DOM id values + def dom_class(record, prefix = nil) + ActiveSupport::Deprecation.warn 'dom_class ' + MESSAGE + ActionView::RecordIdentifier.dom_class(record, prefix) end end end diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb index 1e226fc336..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 @@ -20,20 +18,25 @@ module ActionController ActiveSupport::Notifications.subscribe("render_template.action_view") do |name, start, finish, id, payload| path = payload[:layout] - @layouts[path] += 1 + if path + @layouts[path] += 1 + if path =~ /^layouts\/(.*)/ + @layouts[$1] += 1 + end + end end ActiveSupport::Notifications.subscribe("!render_template.action_view") do |name, start, finish, id, payload| path = payload[:virtual_path] next unless path partial = path =~ /^.*\/_[^\/]*$/ + if partial @partials[path] += 1 @partials[path.split("/").last] += 1 - @templates[path] += 1 - else - @templates[path] += 1 end + + @templates[path] += 1 end end @@ -51,11 +54,21 @@ module ActionController # Asserts that the request was rendered with the appropriate template file or partials. # - # ==== Examples - # # # assert that the "new" view template was rendered # assert_template "new" # + # # assert that the exact template "admin/posts/new" was rendered + # assert_template %r{\Aadmin/posts/new\Z} + # + # # assert that the layout 'admin' was rendered + # assert_template :layout => 'admin' + # assert_template :layout => 'layouts/admin' + # assert_template :layout => :admin + # + # # assert that no layout was rendered + # assert_template :layout => nil + # assert_template :layout => false + # # # assert that the "_customer" partial was rendered twice # assert_template :partial => '_customer', :count => 2 # @@ -67,32 +80,36 @@ module ActionController # # # assert that the "_customer" partial was rendered with a specific object # assert_template :partial => '_customer', :locals => { :customer => @customer } - # def assert_template(options = {}, message = nil) + # Force body to be read in case the + # template is being streamed + response.body + case options - when NilClass, String, Symbol + when NilClass, String, Symbol, Regexp options = options.to_s if Symbol === options rendered = @templates msg = message || sprintf("expecting <%s> but rendering with <%s>", - options, rendered.keys) - assert_block(msg) do + options.inspect, rendered.keys) + matches_template = if options rendered.any? { |t,num| t.match(options) } else @templates.blank? end - end + assert matches_template, msg when Hash - if expected_layout = options[:layout] + if options.key?(:layout) + expected_layout = options[:layout] msg = message || sprintf("expecting layout <%s> but action rendered <%s>", expected_layout, @layouts.keys) case expected_layout - when String - assert_includes @layouts.keys, expected_layout, msg + when String, Symbol + assert_includes @layouts.keys, expected_layout.to_s, msg when Regexp assert(@layouts.keys.any? {|l| l =~ expected_layout }, msg) - when nil + when nil, false assert(@layouts.empty?, msg) end end @@ -113,15 +130,20 @@ module ActionController options[:partial], @partials.keys) assert_includes @partials, expected_partial, msg end - else + elsif options.key?(:partial) assert @partials.empty?, "Expected no partials to be rendered" end + else + raise ArgumentError, "assert_template only accepts a String, Symbol, Hash, Regexp, or nil" end end end class TestRequest < ActionDispatch::TestRequest #:nodoc: + DEFAULT_ENV = ActionDispatch::TestRequest::DEFAULT_ENV.dup + DEFAULT_ENV.delete 'PATH_INFO' + def initialize(env = {}) super @@ -129,29 +151,28 @@ module ActionController self.session_options = TestSession::DEFAULT_OPTIONS.merge(:id => SecureRandom.hex(16)) end - class Result < ::Array #:nodoc: - def to_s() join '/' end - def self.new_escaped(strings) - new strings.collect {|str| uri_parser.unescape str} - 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) non_path_parameters = get? ? query_parameters : request_parameters parameters.each do |key, value| - if value.is_a? Fixnum - value = value.to_s - elsif value.is_a? Array - value = Result.new(value.map { |v| v.is_a?(String) ? v.dup : v }) - elsif value.is_a? String + if value.is_a?(Array) && (value.frozen? || value.any?(&:frozen?)) + value = value.map{ |v| v.duplicable? ? v.dup : v } + elsif value.is_a?(Hash) && (value.frozen? || value.any?{ |k,v| v.frozen? }) + value = Hash[value.map{ |k,v| [k, v.duplicable? ? v.dup : v] }] + elsif value.frozen? && value.duplicable? value = value.dup end if extra_keys.include?(key.to_sym) non_path_parameters[key] = value else + if value.is_a?(Array) + value = value.map(&:to_param) + else + value = value.to_param + end + path_parameters[key.to_s] = value end end @@ -187,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 @@ -225,7 +245,7 @@ module ActionController # == Basic example # # Functional tests are written as follows: - # 1. First, one uses the +get+, +post+, +put+, +delete+ or +head+ method to simulate + # 1. First, one uses the +get+, +post+, +patch+, +put+, +delete+ or +head+ method to simulate # an HTTP request. # 2. Then, one asserts whether the current state is as expected. "State" can be anything: # the controller's HTTP response, the database contents, etc. @@ -323,14 +343,13 @@ module ActionController # == \Testing named routes # # If you're using named routes, they can be easily tested using the original named routes' methods straight in the test case. - # Example: # # assert_redirected_to page_url(:title => 'foo') class TestCase < ActiveSupport::TestCase # 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 @@ -342,12 +361,11 @@ module ActionController module ClassMethods # Sets the controller class name. Useful if the name can't be inferred from test class. - # Normalizes +controller_class+ before using. Examples: + # Normalizes +controller_class+ before using. # # tests WidgetController # tests :widget # tests 'widget' - # def tests(controller_class) case controller_class when String, Symbol @@ -392,6 +410,11 @@ module ActionController process(action, "POST", *args) end + # Executes a request simulating PATCH HTTP method and set/volley the response + def patch(action, *args) + process(action, "PATCH", *args) + end + # Executes a request simulating PUT HTTP method and set/volley the response def put(action, *args) process(action, "PUT", *args) @@ -403,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) @@ -423,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 @@ -442,58 +470,79 @@ module ActionController # Ensure that numbers and symbols passed as params are converted to # proper params, as is the case when engaging rack. - parameters = paramify_values(parameters) + 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 ||= {} controller_class_name = @controller.class.anonymous? ? - "anonymous_controller" : + "anonymous" : @controller.class.name.underscore.sub(/_controller$/, '') @request.assign_parameters(@routes, controller_class_name, action.to_s, parameters) - @request.session = ActionController::TestSession.new(session) if session + @request.session.update(session) if session @request.session["flash"] = @request.flash.update(flash || {}) - @request.session["flash"].sweep - @controller.request = @request - @controller.params.merge!(parameters) + @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 - # Cause the action to be rescued according to the regular rules for rescue_action when the visitor is not local - def rescue_action_in_public! - @request.remote_addr = '208.77.188.166' # example.com + def build_request + TestRequest.new + end + + def build_response + TestResponse.new end included do @@ -503,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. @@ -532,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) @@ -541,6 +590,11 @@ module ActionController @request.env["QUERY_STRING"] = query_string || "" end end + + def html_format?(parameters) + return true unless parameters.is_a?(Hash) + Mime.fetch(parameters[:format]) { Mime['html'] }.html? + end end # When the request.remote_addr remains the default for testing, which is 0.0.0.0, the exception is simply raised inline @@ -550,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.rb b/actionpack/lib/action_controller/vendor/html-scanner.rb index 879b31e60e..896208bc05 100644 --- a/actionpack/lib/action_controller/vendor/html-scanner.rb +++ b/actionpack/lib/action_controller/vendor/html-scanner.rb @@ -1,20 +1,5 @@ -$LOAD_PATH << "#{File.dirname(__FILE__)}/html-scanner" +require 'action_view/vendor/html-scanner' +require 'active_support/deprecation' -module HTML - extend ActiveSupport::Autoload - - eager_autoload do - autoload :CDATA, 'html/node' - autoload :Document, 'html/document' - autoload :FullSanitizer, 'html/sanitizer' - autoload :LinkSanitizer, 'html/sanitizer' - autoload :Node, 'html/node' - autoload :Sanitizer, 'html/sanitizer' - autoload :Selector, 'html/selector' - autoload :Tag, 'html/node' - autoload :Text, 'html/node' - autoload :Tokenizer, 'html/tokenizer' - autoload :Version, 'html/version' - autoload :WhiteListSanitizer, 'html/sanitizer' - end -end +ActiveSupport::Deprecation.warn 'Vendored html-scanner was moved to action_view, please require "action_view/vendor/html-scanner" instead. ' + + 'This file will be removed in Rails 4.1' diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb index a9542a7d1b..0ec355246e 100644 --- a/actionpack/lib/action_dispatch.rb +++ b/actionpack/lib/action_dispatch.rb @@ -21,18 +21,11 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #++ -activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__) -$:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path) - -activemodel_path = File.expand_path('../../../activemodel/lib', __FILE__) -$:.unshift(activemodel_path) if File.directory?(activemodel_path) && !$:.include?(activemodel_path) - 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 @@ -42,9 +35,14 @@ end module ActionDispatch extend ActiveSupport::Autoload - autoload_under 'http' do - autoload :Request - autoload :Response + class IllegalStateError < StandardError + end + + eager_autoload do + autoload_under 'http' do + autoload :Request + autoload :Response + end end autoload_under 'middleware' do @@ -61,6 +59,7 @@ module ActionDispatch autoload :Reloader autoload :RemoteIp autoload :ShowExceptions + autoload :SSL autoload :Static end @@ -102,3 +101,8 @@ module ActionDispatch end autoload :Mime, 'action_dispatch/http/mime_type' + +ActiveSupport.on_load(:action_view) do + ActionView::Base.default_formats ||= Mime::SET.symbols + ActionView::Template::Types.delegate_to Mime +end diff --git a/actionpack/lib/action_dispatch/http/cache.rb b/actionpack/lib/action_dispatch/http/cache.rb index bea62b94d2..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 @@ -60,6 +59,20 @@ module ActionDispatch headers[LAST_MODIFIED] = utc_time.httpdate end + def date + if date_header = headers['Date'] + Time.httpdate(date_header) + end + end + + def date? + headers.include?('Date') + end + + def date=(utc_time) + headers['Date'] = utc_time.httpdate + end + def etag=(etag) key = ActiveSupport::Cache.expand_cache_key(etag) @etag = self[ETAG] = %("#{Digest::MD5.hexdigest(key)}") @@ -70,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! @@ -96,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 02a15ad599..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' @@ -10,8 +9,6 @@ module ActionDispatch # value of the params hash and all subhashes is passed to it, the value # or key can be replaced using String#replace or similar method. # - # Examples: - # # env["action_dispatch.parameter_filter"] = [:password] # => replaces the value to all keys matching /password/i with "[FILTERED]" # @@ -22,7 +19,6 @@ module ActionDispatch # v.reverse! if k =~ /secret/i # end # => reverses the value to all keys matching /secret/i - # module FilterParameters extend ActiveSupport::Concern @@ -50,7 +46,7 @@ module ActionDispatch end def env_filter - parameter_filter_for(Array(@env["action_dispatch.parameter_filter"]) << /RAW_POST_DATA/) + parameter_filter_for(Array(@env["action_dispatch.parameter_filter"]) + [/RAW_POST_DATA/, "rack.request.form_vars"]) end def parameter_filter_for(filters) diff --git a/actionpack/lib/action_dispatch/http/headers.rb b/actionpack/lib/action_dispatch/http/headers.rb index 040b51e040..a3bb25f75a 100644 --- a/actionpack/lib/action_dispatch/http/headers.rb +++ b/actionpack/lib/action_dispatch/http/headers.rb @@ -14,17 +14,18 @@ module ActionDispatch end def [](header_name) - if include?(header_name) - super - else - super(env_name(header_name)) - end + super env_name(header_name) + end + + def fetch(header_name, default=nil, &block) + super env_name(header_name), default, &block end private - # Converts a HTTP header name to an environment variable name. + # Converts a HTTP header name to an environment variable name if it is + # not contained within the headers hash. def env_name(header_name) - @@env_cache[header_name] + include?(header_name) ? header_name : @@env_cache[header_name] end end end diff --git a/actionpack/lib/action_dispatch/http/mime_negotiation.rb b/actionpack/lib/action_dispatch/http/mime_negotiation.rb index 5c48a60469..0f98e84788 100644 --- a/actionpack/lib/action_dispatch/http/mime_negotiation.rb +++ b/actionpack/lib/action_dispatch/http/mime_negotiation.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/module/attribute_accessors' + module ActionDispatch module Http module MimeNegotiation @@ -78,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 2152351703..3c1f1458ea 100644 --- a/actionpack/lib/action_dispatch/http/mime_type.rb +++ b/actionpack/lib/action_dispatch/http/mime_type.rb @@ -1,11 +1,10 @@ require 'set' require 'active_support/core_ext/class/attribute_accessors' -require 'active_support/core_ext/object/blank' module Mime class Mimes < Array def symbols - @symbols ||= map {|m| m.to_sym } + @symbols ||= map { |m| m.to_sym } end %w(<< concat shift unshift push pop []= clear compact! collect! @@ -24,9 +23,16 @@ module Mime EXTENSION_LOOKUP = {} LOOKUP = Hash.new { |h, k| h[k] = Type.new(k) unless k.blank? } - def self.[](type) - return type if type.is_a?(Type) - Type.lookup_by_extension(type.to_s) + class << self + def [](type) + return type if type.is_a?(Type) + Type.lookup_by_extension(type) + end + + def fetch(type) + return type if type.is_a?(Type) + EXTENSION_LOOKUP.fetch(type.to_s) { |k| yield k } + end end # Encapsulates the notion of a mime type. Can be used at render time, for example, with: @@ -38,7 +44,7 @@ module Mime # respond_to do |format| # format.html # format.ics { render :text => post.to_ics, :mime_type => Mime::Type["text/calendar"] } - # format.xml { render :xml => @people.to_xml } + # format.xml { render :xml => @people } # end # end # end @@ -53,36 +59,94 @@ 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 + attr_accessor :index, :name, :q + alias :to_s :name - def initialize(order, name, q=nil) - @order = order - @name = name.strip - q ||= 0.0 if @name == Mime::ALL # default wildcard match to end of list + def initialize(index, name, q = nil) + @index = index + @name = name + q ||= 0.0 if @name == Mime::ALL.to_s # default wildcard match to end of list @q = ((q || 1.0).to_f * 100).to_i end - def to_s - @name - end - def <=>(item) - result = item.q <=> q - result = order <=> item.order if result == 0 + result = item.q <=> @q + result = @index <=> item.index if result == 0 result end def ==(item) - name == (item.respond_to?(:name) ? item.name : item) + @name == item.to_s end end - class << self + class AcceptList < Array #:nodoc: + def assort! + sort! + + # Take care of the broken text/xml entry by renaming or deleting it + if text_xml_idx && app_xml_idx + app_xml.q = [text_xml.q, app_xml.q].max # set the q value to the max of the two + exchange_xml_items if app_xml_idx > text_xml_idx # make sure app_xml is ahead of text_xml in the list + delete_at(text_xml_idx) # delete text_xml from the list + elsif text_xml_idx + text_xml.name = Mime::XML.to_s + end + + # Look for more specific XML-based types and sort them ahead of app/xml + if app_xml_idx + idx = app_xml_idx + + while idx < length + type = self[idx] + break if type.q < app_xml.q + + if type.name.ends_with? '+xml' + self[app_xml_idx], self[idx] = self[idx], app_xml + @app_xml_idx = idx + end + idx += 1 + end + end + + map! { |i| Mime::Type.lookup(i.name) }.uniq! + to_a + end + + private + def text_xml_idx + @text_xml_idx ||= index('text/xml') + end + + def app_xml_idx + @app_xml_idx ||= index(Mime::XML.to_s) + end + + def text_xml + self[text_xml_idx] + end + + def app_xml + self[app_xml_idx] + end + + def exchange_xml_items + self[app_xml_idx], self[text_xml_idx] = text_xml, app_xml + @app_xml_idx, @text_xml_idx = text_xml_idx, app_xml_idx + end + end + class << self TRAILING_STAR_REGEXP = /(text|application)\/\*/ - Q_SEPARATOR_REGEXP = /;\s*q=/ + PARAMETER_SEPARATOR_REGEXP = /;\s*\w+="?\w+"?/ + + def register_callback(&block) + @register_callbacks << block + end def lookup(string) LOOKUP[string] @@ -99,91 +163,51 @@ 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) if accept_header !~ /,/ - accept_header = accept_header.split(Q_SEPARATOR_REGEXP).first - if accept_header =~ TRAILING_STAR_REGEXP - parse_data_with_trailing_star($1) - else - [Mime::Type.lookup(accept_header)] - end + accept_header = accept_header.split(PARAMETER_SEPARATOR_REGEXP).first + parse_trailing_star(accept_header) || [Mime::Type.lookup(accept_header)] else - # keep track of creation order to keep the subsequent sort stable - list, index = [], 0 - accept_header.split(/,/).each do |header| - params, q = header.split(Q_SEPARATOR_REGEXP) + list, index = AcceptList.new, 0 + accept_header.split(',').each do |header| + params, q = header.split(PARAMETER_SEPARATOR_REGEXP) if params.present? params.strip! - if params =~ TRAILING_STAR_REGEXP - parse_data_with_trailing_star($1).each do |m| - list << AcceptItem.new(index, m.to_s, q) - index += 1 - end - else - list << AcceptItem.new(index, params, q) - index += 1 - end - end - end - list.sort! - - # Take care of the broken text/xml entry by renaming or deleting it - text_xml = list.index("text/xml") - app_xml = list.index(Mime::XML.to_s) - - if text_xml && app_xml - # set the q value to the max of the two - list[app_xml].q = [list[text_xml].q, list[app_xml].q].max - - # make sure app_xml is ahead of text_xml in the list - if app_xml > text_xml - list[app_xml], list[text_xml] = list[text_xml], list[app_xml] - app_xml, text_xml = text_xml, app_xml - end + params = parse_trailing_star(params) || [params] - # delete text_xml from the list - list.delete_at(text_xml) - - elsif text_xml - list[text_xml].name = Mime::XML.to_s - end - - # Look for more specific XML-based types and sort them ahead of app/xml - - if app_xml - idx = app_xml - app_xml_type = list[app_xml] - - while(idx < list.length) - type = list[idx] - break if type.q < app_xml_type.q - if type.name =~ /\+xml$/ - list[app_xml], list[idx] = list[idx], list[app_xml] - app_xml = idx + params.each do |m| + list << AcceptItem.new(index, m.to_s, q) + index += 1 end - idx += 1 end end - - list.map! { |i| Mime::Type.lookup(i.name) }.uniq! - list + list.assort! end end - # input: 'text' - # returned value: [Mime::JSON, Mime::XML, Mime::ICS, Mime::HTML, Mime::CSS, Mime::CSV, Mime::JS, Mime::YAML, Mime::TEXT] + def parse_trailing_star(accept_header) + parse_data_with_trailing_star($1) if accept_header =~ TRAILING_STAR_REGEXP + end + + # For an input of <tt>'text'</tt>, returns <tt>[Mime::JSON, Mime::XML, Mime::ICS, + # Mime::HTML, Mime::CSS, Mime::CSV, Mime::JS, Mime::YAML, Mime::TEXT]</tt>. # - # input: 'application' - # returned value: [Mime::HTML, Mime::JS, Mime::XML, Mime::YAML, Mime::ATOM, Mime::JSON, Mime::RSS, Mime::URL_ENCODED_FORM] + # For an input of <tt>'application'</tt>, returns <tt>[Mime::HTML, Mime::JS, + # Mime::XML, Mime::YAML, Mime::ATOM, Mime::JSON, Mime::RSS, Mime::URL_ENCODED_FORM]</tt>. def parse_data_with_trailing_star(input) Mime::SET.select { |m| m =~ input } end @@ -192,9 +216,9 @@ module Mime # # Usage: # - # Mime::Type.unregister(:mobile) + # 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) } @@ -258,18 +282,18 @@ module Mime @@html_types.include?(to_sym) || @string =~ /html/ end - def respond_to?(method, include_private = false) #:nodoc: - super || method.to_s =~ /(\w+)\?$/ - end - private def method_missing(method, *args) - if method.to_s =~ /(\w+)\?$/ - $1.downcase.to_sym == to_sym + if method.to_s.ends_with? '?' + method[0..-2].downcase.to_sym == to_sym else super end end + + def respond_to_missing?(method, include_private = false) #:nodoc: + method.to_s.ends_with? '?' + end end end diff --git a/actionpack/lib/action_dispatch/http/parameters.rb b/actionpack/lib/action_dispatch/http/parameters.rb index d9b63faf5e..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 @@ -35,6 +40,10 @@ module ActionDispatch @env["action_dispatch.request.path_parameters"] ||= {} end + def reset_parameters #:nodoc: + @env.delete("action_dispatch.request.parameters") + end + private # TODO: Validate that the characters are UTF-8. If they aren't, diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb index 0a0ebe7fad..b8ebeb408f 100644 --- a/actionpack/lib/action_dispatch/http/request.rb +++ b/actionpack/lib/action_dispatch/http/request.rb @@ -17,7 +17,10 @@ module ActionDispatch include ActionDispatch::Http::Upload include ActionDispatch::Http::URL - LOCALHOST = [/^127\.0\.0\.\d{1,3}$/, "::1", /^0:0:0:0:0:0:0:1(%.*)?$/].freeze + autoload :Session, 'action_dispatch/request/session' + + LOCALHOST = Regexp.union [/^127\.0\.0\.\d{1,3}$/, /^::1$/, /^0:0:0:0:0:0:0:1(%.*)?$/] + ENV_METHODS = %w[ AUTH_TYPE GATEWAY_INTERFACE PATH_TRANSLATED REMOTE_HOST REMOTE_IDENT REMOTE_USER REMOTE_ADDR @@ -35,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 @@ -97,6 +111,12 @@ module ActionDispatch HTTP_METHOD_LOOKUP[request_method] == :post end + # Is this a PATCH request? + # Equivalent to <tt>request.request_method == :patch</tt>. + def patch? + HTTP_METHOD_LOOKUP[request_method] == :patch + end + # Is this a PUT request? # Equivalent to <tt>request.request_method_symbol == :put</tt>. def put? @@ -110,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: @@ -207,32 +227,42 @@ module ActionDispatch # TODO This should be broken apart into AD::Request::Session and probably # be included by the session middleware. def reset_session - session.destroy if session && session.respond_to?(:destroy) - self.session = {} + if session && session.respond_to?(:destroy) + session.destroy + else + self.session = {} + end @env['action_dispatch.request.flash_hash'] = nil end def session=(session) #:nodoc: - @env['rack.session'] = session + Session.set @env, session end def session_options=(options) - @env['rack.session.options'] = options + Session::Options.set @env, options end # Override Rack's GET method to support indifferent access def GET - @env["action_dispatch.request.query_parameters"] ||= (normalize_parameters(super) || {}) + begin + @env["action_dispatch.request.query_parameters"] ||= (normalize_parameters(super) || {}) + rescue TypeError => e + raise ActionController::BadRequest, "Invalid query parameters: #{e.message}" + end end alias :query_parameters :GET # Override Rack's POST method to support indifferent access def POST - @env["action_dispatch.request.request_parameters"] ||= (normalize_parameters(super) || {}) + begin + @env["action_dispatch.request.request_parameters"] ||= (normalize_parameters(super) || {}) + rescue TypeError => e + raise ActionController::BadRequest, "Invalid request parameters: #{e.message}" + end end alias :request_parameters :POST - # Returns the authorization header regardless of whether it was specified directly or through one of the # proxy alternatives. def authorization @@ -244,7 +274,28 @@ module ActionDispatch # True if the request came from localhost, 127.0.0.1. def local? - LOCALHOST.any? { |local_ip| local_ip === remote_addr && local_ip === remote_ip } + 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 diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb index 84732085f0..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 @@ -29,7 +28,7 @@ module ActionDispatch # :nodoc: # class DemoControllerTest < ActionDispatch::IntegrationTest # def test_print_root_path_to_console # get('/') - # puts @response.body + # puts response.body # end # end class Response @@ -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: @@ -51,22 +50,63 @@ module ActionDispatch # :nodoc: # If a character set has been defined for this response (see charset=) then # the character set information will also be included in the content type # information. - attr_accessor :charset, :content_type + attr_accessor :charset + attr_reader :content_type CONTENT_TYPE = "Content-Type".freeze SET_COOKIE = "Set-Cookie".freeze 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=/) @@ -79,10 +119,31 @@ 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 + def content_type=(content_type) + @content_type = content_type.to_s + end + # The response code of the request def response_code @status @@ -100,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 @@ -121,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) @@ -146,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 @@ -184,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 @@ -195,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/upload.rb b/actionpack/lib/action_dispatch/http/upload.rb index 5ab99d1061..ce8c2729e9 100644 --- a/actionpack/lib/action_dispatch/http/upload.rb +++ b/actionpack/lib/action_dispatch/http/upload.rb @@ -4,11 +4,12 @@ module ActionDispatch attr_accessor :original_filename, :content_type, :tempfile, :headers def initialize(hash) + @tempfile = hash[:tempfile] + raise(ArgumentError, ':tempfile is required') unless @tempfile + @original_filename = encode_filename(hash[:filename]) @content_type = hash[:type] @headers = hash[:head] - @tempfile = hash[:tempfile] - raise(ArgumentError, ':tempfile is required') unless @tempfile end def read(*args) @@ -16,18 +17,15 @@ module ActionDispatch end # Delegate these methods to the tempfile. - [:open, :path, :rewind, :size].each do |method| + [:open, :path, :rewind, :size, :eof?].each do |method| class_eval "def #{method}; @tempfile.#{method}; end" end - + private + def encode_filename(filename) # Encode the filename in the utf8 encoding, unless it is nil - if filename - filename.force_encoding("UTF-8").encode! - else - filename - end + filename.force_encoding("UTF-8").encode! if filename end end diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb index 80ffbe575b..8aa02ec482 100644 --- a/actionpack/lib/action_dispatch/http/url.rb +++ b/actionpack/lib/action_dispatch/http/url.rb @@ -23,36 +23,43 @@ module ActionDispatch end def url_for(options = {}) + path = "" + path << options.delete(:script_name).to_s.chomp("/") + path << options.delete(:path).to_s + + params = options[:params] || {} + params.reject! {|k,v| v.to_param.nil? } + + result = build_host_url(options) + + result << (options[:trailing_slash] ? path.sub(/\?|\z/) { "/" + $& } : path) + result << "?#{params.to_query}" unless params.empty? + result << "##{Journey::Router::Utils.escape_fragment(options[:anchor].to_param.to_s)}" if options[:anchor] + result + end + + private + + def build_host_url(options) if options[:host].blank? && options[:only_path].blank? raise ArgumentError, 'Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true' end - rewritten_url = "" + result = "" unless options[:only_path] unless options[:protocol] == false - rewritten_url << (options[:protocol] || "http") - rewritten_url << ":" unless rewritten_url.match(%r{:|//}) + result << (options[:protocol] || "http") + result << ":" unless result.match(%r{:|//}) end - rewritten_url << "//" unless rewritten_url.match("//") - rewritten_url << rewrite_authentication(options) - rewritten_url << host_or_subdomain_and_domain(options) - rewritten_url << ":#{options.delete(:port)}" if options[:port] + result << "//" unless result.match("//") + result << rewrite_authentication(options) + result << host_or_subdomain_and_domain(options) + result << ":#{options.delete(:port)}" if options[:port] end - - path = options.delete(:path) || '' - - params = options[:params] || {} - params.reject! {|k,v| v.to_param.nil? } - - rewritten_url << (options[:trailing_slash] ? path.sub(/\?|\z/) { "/" + $& } : path) - rewritten_url << "?#{params.to_query}" unless params.empty? - rewritten_url << "##{Journey::Router::Utils.escape_fragment(options[:anchor].to_param.to_s)}" if options[:anchor] - rewritten_url + result end - private - def named_host?(host) host && IP_HOST_REGEXP !~ host end @@ -80,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 8c0f4052ec..852f1cf6f5 100644 --- a/actionpack/lib/action_dispatch/middleware/callbacks.rb +++ b/actionpack/lib/action_dispatch/middleware/callbacks.rb @@ -1,11 +1,10 @@ -require 'active_support/core_ext/module/delegation' module ActionDispatch # Provide callbacks to be executed before and after the request dispatch. class Callbacks include ActiveSupport::Callbacks - define_callbacks :call, :rescuable => true + define_callbacks :call class << self delegate :to_prepare, :to_cleanup, :to => "ActionDispatch::Reloader" @@ -24,9 +23,15 @@ module ActionDispatch end def call(env) - run_callbacks :call do - @app.call(env) + error = nil + result = run_callbacks :call do + begin + @app.call(env) + rescue => error + end end + raise error if error + result end end end diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb index 25f1db8228..ba5d332d49 100644 --- a/actionpack/lib/action_dispatch/middleware/cookies.rb +++ b/actionpack/lib/action_dispatch/middleware/cookies.rb @@ -1,8 +1,8 @@ -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 + class Request < Rack::Request def cookie_jar env['action_dispatch.cookies'] ||= Cookies::CookieJar.build(self) end @@ -26,9 +26,9 @@ module ActionDispatch # # Sets a cookie that expires in 1 hour. # cookies[:login] = { :value => "XJ-122", :expires => 1.hour.from_now } # - # # Sets a signed cookie, which prevents a user from tampering with its value. + # # Sets a signed cookie, which prevents users from tampering with its value. # # The cookie is signed by your app's <tt>config.secret_token</tt> value. - # # Rails generates this value by default when you create a new Rails app. + # # It can be read using the signed method <tt>cookies.signed[:key]</tt> # cookies.signed[:user_id] = current_user.id # # # Sets a "permanent" cookie (which expires in 20 years from now). @@ -39,9 +39,10 @@ module ActionDispatch # # Examples for reading: # - # cookies[:user_name] # => "david" - # cookies.size # => 2 - # cookies[:lat_lon] # => [47.68, -122.37] + # cookies[:user_name] # => "david" + # cookies.size # => 2 + # cookies[:lat_lon] # => [47.68, -122.37] + # cookies.signed[:login] # => "XJ-122" # # Example for deleting: # @@ -82,7 +83,7 @@ module ActionDispatch TOKEN_KEY = "action_dispatch.secret_token".freeze # Raised when storing more than 4K of session data. - class CookieOverflow < StandardError; end + CookieOverflow = Class.new StandardError class CookieJar #:nodoc: include Enumerable @@ -117,7 +118,6 @@ module ActionDispatch @delete_cookies = {} @host = host @secure = secure - @closed = false @cookies = {} end @@ -154,7 +154,7 @@ module ActionDispatch end elsif options[:domain].is_a? Array # if host matches one of the supplied domains without a dot in front of it - options[:domain] = options[:domain].find {|domain| @host.include? domain[/^\.?(.*)$/, 1] } + options[:domain] = options[:domain].find {|domain| @host.include? domain.sub(/^\./, '') } end end @@ -169,12 +169,14 @@ module ActionDispatch options = { :value => value } end - @cookies[key.to_s] = value - handle_options(options) - @set_cookies[key.to_s] = options - @delete_cookies.delete(key.to_s) + if @cookies[key.to_s] != value or options[:expires] + @cookies[key.to_s] = value + @set_cookies[key.to_s] = options + @delete_cookies.delete(key.to_s) + end + value end @@ -182,8 +184,9 @@ module ActionDispatch # and setting its expiration date into the past. Like <tt>[]=</tt>, you can pass in # an options hash to delete cookies with extra data such as a <tt>:path</tt>. def delete(key, options = {}) - options.symbolize_keys! + return unless @cookies.has_key? key.to_s + options.symbolize_keys! handle_options(options) value = @cookies.delete(key.to_s) @@ -225,7 +228,7 @@ module ActionDispatch # cookie was tampered with by the user (or a 3rd party), an ActiveSupport::MessageVerifier::InvalidSignature exception will # be raised. # - # This jar requires that you set a suitable secret for the verification on your app's config.secret_token. + # This jar requires that you set a suitable secret for the verification on your app's +config.secret_token+. # # Example: # @@ -273,10 +276,6 @@ module ActionDispatch @parent_jar[key] = options end - def signed - @signed ||= SignedCookieJar.new(self, @secret) - end - def method_missing(method, *arguments, &block) @parent_jar.send(method, *arguments, &block) end @@ -343,7 +342,6 @@ module ActionDispatch end def call(env) - cookie_jar = nil status, headers, body = @app.call(env) if cookie_jar = env['action_dispatch.cookies'] 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/exception_wrapper.rb b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb index c0532c80c4..7349b578d2 100644 --- a/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb +++ b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb @@ -1,5 +1,6 @@ require 'action_controller/metal/exceptions' require 'active_support/core_ext/exception' +require 'active_support/core_ext/class/attribute_accessors' module ActionDispatch class ExceptionWrapper @@ -10,7 +11,9 @@ module ActionDispatch 'AbstractController::ActionNotFound' => :not_found, 'ActionController::MethodNotAllowed' => :method_not_allowed, 'ActionController::NotImplemented' => :not_implemented, - 'ActionController::InvalidAuthenticityToken' => :unprocessable_entity + 'ActionController::UnknownFormat' => :not_acceptable, + 'ActionController::InvalidAuthenticityToken' => :unprocessable_entity, + 'ActionController::BadRequest' => :bad_request ) cattr_accessor :rescue_templates @@ -75,4 +78,4 @@ module ActionDispatch @backtrace_cleaner ||= @env['action_dispatch.backtrace_cleaner'] end end -end
\ No newline at end of file +end diff --git a/actionpack/lib/action_dispatch/middleware/flash.rb b/actionpack/lib/action_dispatch/middleware/flash.rb index cff0877030..9928b7cc3a 100644 --- a/actionpack/lib/action_dispatch/middleware/flash.rb +++ b/actionpack/lib/action_dispatch/middleware/flash.rb @@ -1,23 +1,23 @@ module ActionDispatch - class Request + class Request < Rack::Request # Access the contents of the flash. Use <tt>flash["notice"]</tt> to # read a notice you put there or <tt>flash["notice"] = "hello"</tt> # to put a new one. def flash - @env[Flash::KEY] ||= (session["flash"] || Flash::FlashHash.new) + @env[Flash::KEY] ||= (session["flash"] || Flash::FlashHash.new).tap(&:sweep) end end # The flash provides a way to pass temporary objects between actions. Anything you place in the flash will be exposed # to the very next action and then cleared out. This is a great way of doing notices and alerts, such as a create # action that sets <tt>flash[:notice] = "Post successfully created"</tt> before redirecting to a display action that can - # then expose the flash to its template. Actually, that exposure is automatically done. Example: + # then expose the flash to its template. Actually, that exposure is automatically done. # # class PostsController < ActionController::Base # def create # # save post # flash[:notice] = "Post successfully created" - # redirect_to posts_path(@post) + # redirect_to @post # end # # def show @@ -79,7 +79,6 @@ module ActionDispatch def initialize #:nodoc: @discard = Set.new - @closed = false @flashes = {} @now = nil end @@ -217,13 +216,9 @@ module ActionDispatch end def call(env) - if (session = env['rack.session']) && (flash = session['flash']) - flash.sweep - end - @app.call(env) ensure - session = env['rack.session'] || {} + session = Request::Session.find(env) || {} flash_hash = env[KEY] if flash_hash @@ -237,7 +232,8 @@ module ActionDispatch env[KEY] = new_hash end - if session.key?('flash') && session['flash'].empty? + if (!session.respond_to?(:loaded?) || session.loaded?) && # (reset_session uses {}, which doesn't implement #loaded?) + session.key?('flash') && session['flash'].empty? session.delete('flash') 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/reloader.rb b/actionpack/lib/action_dispatch/middleware/reloader.rb index a0388e0e13..2f6968eb2e 100644 --- a/actionpack/lib/action_dispatch/middleware/reloader.rb +++ b/actionpack/lib/action_dispatch/middleware/reloader.rb @@ -18,10 +18,10 @@ module ActionDispatch # classes before they are unloaded. # # By default, ActionDispatch::Reloader is included in the middleware stack - # only in the development environment; specifically, when config.cache_classes + # only in the development environment; specifically, when +config.cache_classes+ # is false. Callbacks may be registered even when it is not included in the - # middleware stack, but are executed only when +ActionDispatch::Reloader.prepare!+ - # or +ActionDispatch::Reloader.cleanup!+ are called manually. + # middleware stack, but are executed only when <tt>ActionDispatch::Reloader.prepare!</tt> + # or <tt>ActionDispatch::Reloader.cleanup!</tt> are called manually. # class Reloader include ActiveSupport::Callbacks diff --git a/actionpack/lib/action_dispatch/middleware/remote_ip.rb b/actionpack/lib/action_dispatch/middleware/remote_ip.rb index d924f21fad..ec15a2a715 100644 --- a/actionpack/lib/action_dispatch/middleware/remote_ip.rb +++ b/actionpack/lib/action_dispatch/middleware/remote_ip.rb @@ -5,11 +5,14 @@ module ActionDispatch # IP addresses that are "trusted proxies" that can be stripped from # the comma-delimited list in the X-Forwarded-For header. See also: # http://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces + # http://en.wikipedia.org/wiki/Private_network#Private_IPv6_addresses. TRUSTED_PROXIES = %r{ ^127\.0\.0\.1$ | # localhost + ^::1$ | ^(10 | # private IP 10.x.x.x 172\.(1[6-9]|2[0-9]|3[0-1]) | # private IP in the range 172.16.0.0 .. 172.31.255.255 - 192\.168 # private IP 192.168.x.x + 192\.168 | # private IP 192.168.x.x + fc00:: # private IP fc00 )\. }x @@ -19,13 +22,13 @@ module ActionDispatch @app = app @check_ip = check_ip_spoofing @proxies = case custom_proxies - when Regexp - custom_proxies - when nil - TRUSTED_PROXIES - else - Regexp.union(TRUSTED_PROXIES, custom_proxies) - end + when Regexp + custom_proxies + when nil + TRUSTED_PROXIES + else + Regexp.union(TRUSTED_PROXIES, custom_proxies) + end end def call(env) @@ -34,6 +37,31 @@ module ActionDispatch end class GetIp + + # IP v4 and v6 (with compression) validation regexp + # https://gist.github.com/1289635 + VALID_IP = %r{ + (^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})){3}$) | # ip v4 + (^( + (([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}) | # ip v6 not abbreviated + (([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4}) | # ip v6 with double colon in the end + (([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4}) | # - ip addresses v6 + (([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4}) | # - with + (([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4}) | # - double colon + (([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4}) | # - in the middle + (([0-9A-Fa-f]{1,4}:){6} ((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3} (\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4 + (([0-9A-Fa-f]{1,4}:){1,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4 + (([0-9A-Fa-f]{1,4}:){1}:([0-9A-Fa-f]{1,4}:){0,4}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4 + (([0-9A-Fa-f]{1,4}:){0,2}:([0-9A-Fa-f]{1,4}:){0,3}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4 + (([0-9A-Fa-f]{1,4}:){0,3}:([0-9A-Fa-f]{1,4}:){0,2}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4 + (([0-9A-Fa-f]{1,4}:){0,4}:([0-9A-Fa-f]{1,4}:){1}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4 + (::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d) |(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4 + ([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4}) | # ip v6 with compatible to v4 + (::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4}) | # ip v6 with double colon at the begining + (([0-9A-Fa-f]{1,4}:){1,7}:) # ip v6 without ending + )$) + }x + def initialize(env, middleware) @env = env @middleware = middleware @@ -44,25 +72,31 @@ module ActionDispatch # but will be wrong if the user is behind a proxy. Proxies will set # HTTP_CLIENT_IP and/or HTTP_X_FORWARDED_FOR, so we prioritize those. # HTTP_X_FORWARDED_FOR may be a comma-delimited list in the case of - # multiple chained proxies. The last address which is not a known proxy - # will be the originating IP. + # multiple chained proxies. The first address which is in this list + # if it's not a known proxy will be the originating IP. + # Format of HTTP_X_FORWARDED_FOR: + # client_ip, proxy_ip1, proxy_ip2... + # http://en.wikipedia.org/wiki/X-Forwarded-For def calculate_ip - client_ip = @env['HTTP_CLIENT_IP'] - forwarded_ips = ips_from('HTTP_X_FORWARDED_FOR') - remote_addrs = ips_from('REMOTE_ADDR') + client_ip = @env['HTTP_CLIENT_IP'] + forwarded_ip = ips_from('HTTP_X_FORWARDED_FOR').first + remote_addrs = ips_from('REMOTE_ADDR') check_ip = client_ip && @middleware.check_ip - if check_ip && !forwarded_ips.include?(client_ip) + if check_ip && forwarded_ip != client_ip # We don't know which came from the proxy, and which from the user raise IpSpoofAttackError, "IP spoofing attack?!" \ "HTTP_CLIENT_IP=#{@env['HTTP_CLIENT_IP'].inspect}" \ "HTTP_X_FORWARDED_FOR=#{@env['HTTP_X_FORWARDED_FOR'].inspect}" end - not_proxy = client_ip || forwarded_ips.first || remote_addrs.first - - # Return first REMOTE_ADDR if there are no other options - not_proxy || ips_from('REMOTE_ADDR', :allow_proxies).first + client_ips = remove_proxies [client_ip, forwarded_ip, remote_addrs].flatten + if client_ips.present? + client_ips.first + else + # If there is no client ip we can return first valid proxy ip from REMOTE_ADDR + remote_addrs.find { |ip| valid_ip? ip } + end end def to_s @@ -71,12 +105,24 @@ module ActionDispatch @ip = calculate_ip end - protected + private - def ips_from(header, allow_proxies = false) - ips = @env[header] ? @env[header].strip.split(/[,\s]+/) : [] - allow_proxies ? ips : ips.reject{|ip| ip =~ @middleware.proxies } + def ips_from(header) + @env[header] ? @env[header].strip.split(/[,\s]+/) : [] end + + def valid_ip?(ip) + ip =~ VALID_IP + end + + def not_a_proxy?(ip) + ip !~ @middleware.proxies + end + + def remove_proxies(ips) + ips.select { |ip| valid_ip?(ip) && not_a_proxy?(ip) } + end + end end diff --git a/actionpack/lib/action_dispatch/middleware/request_id.rb b/actionpack/lib/action_dispatch/middleware/request_id.rb index d5a0b80fd5..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 @@ -19,10 +18,7 @@ module ActionDispatch def call(env) env["action_dispatch.request_id"] = external_request_id(env) || internal_request_id - status, headers, body = @app.call(env) - - headers["X-Request-Id"] = env["action_dispatch.request_id"] - [ status, headers, body ] + @app.call(env).tap { |status, headers, body| headers["X-Request-Id"] = env["action_dispatch.request_id"] } end private diff --git a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb index 6a8e690d18..7c12590c49 100644 --- a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb +++ b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb @@ -2,26 +2,22 @@ require 'rack/utils' require 'rack/request' require 'rack/session/abstract/id' require 'action_dispatch/middleware/cookies' -require 'active_support/core_ext/object/blank' +require 'action_dispatch/request/session' module ActionDispatch module Session class SessionRestoreError < StandardError #:nodoc: - end + attr_reader :original_exception + + def initialize(const_error) + @original_exception = const_error - module DestroyableSession - def destroy - clear - options = @env[Rack::Session::Abstract::ENV_SESSION_OPTIONS_KEY] if @env - options ||= {} - @by.send(:destroy_session, @env, options[:id], options) if @by - options[:id] = nil - @loaded = false + super("Session contains objects whose class definition isn't available.\n" + + "Remember to require the classes for all objects kept in the session.\n" + + "(Original exception: #{const_error.message} [#{const_error.class}])\n") end end - ::Rack::Session::Abstract::SessionHash.send :include, DestroyableSession - module Compatibility def initialize(app, options = {}) options[:key] ||= '_session_id' @@ -58,11 +54,8 @@ module ActionDispatch begin # Note that the regexp does not allow $1 to end with a ':' $1.constantize - rescue LoadError, NameError => const_error - raise ActionDispatch::Session::SessionRestoreError, - "Session contains objects whose class definition isn't available.\n" + - "Remember to require the classes for all objects kept in the session.\n" + - "(Original exception: #{const_error.message} [#{const_error.class}])\n" + rescue LoadError, NameError => e + raise ActionDispatch::Session::SessionRestoreError, e, e.backtrace end retry else @@ -71,9 +64,27 @@ module ActionDispatch end end + module SessionObject # :nodoc: + def prepare_session(env) + Request::Session.create(self, env, @default_options) + end + + def loaded_session?(session) + !session.is_a?(Request::Session) || session.loaded? + end + end + class AbstractStore < Rack::Session::Abstract::ID include Compatibility include StaleSessionCheck + include SessionObject + + private + + def set_cookie(env, session_id, cookie) + request = ActionDispatch::Request.new(env) + request.cookie_jar[key] = cookie + end end end end diff --git a/actionpack/lib/action_dispatch/middleware/session/cache_store.rb b/actionpack/lib/action_dispatch/middleware/session/cache_store.rb index d3b6fd12fa..1db6194271 100644 --- a/actionpack/lib/action_dispatch/middleware/session/cache_store.rb +++ b/actionpack/lib/action_dispatch/middleware/session/cache_store.rb @@ -1,5 +1,4 @@ require 'action_dispatch/middleware/session/abstract_store' -require 'rack/session/memcache' 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 8ebf870b95..019849ef95 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' @@ -27,7 +26,7 @@ module ActionDispatch # CGI::Session instance as an argument. It's important that the secret # is not vulnerable to a dictionary attack. Therefore, you should choose # a secret consisting of random numbers and letters and more than 30 - # characters. Examples: + # characters. # # :secret => '449fe2e7daee471bffae2fd8dc02313d' # :secret => Proc.new { User.current_user.secret_key } @@ -43,6 +42,15 @@ module ActionDispatch class CookieStore < Rack::Session::Cookie include Compatibility include StaleSessionCheck + include SessionObject + + # Override rack's method + def destroy_session(env, session_id, options) + new_sid = super + # Reset hash and Assign the new session id + env["action_dispatch.request.unsigned_session_cookie"] = new_sid ? { "session_id" => new_sid } : {} + new_sid + end private @@ -59,7 +67,8 @@ module ActionDispatch end def set_session(env, sid, session_data, options) - session_data.merge("session_id" => sid) + session_data["session_id"] = sid + session_data end def set_cookie(env, session_id, cookie) diff --git a/actionpack/lib/action_dispatch/middleware/session/mem_cache_store.rb b/actionpack/lib/action_dispatch/middleware/session/mem_cache_store.rb index 4dd9a946c2..38a737cd2b 100644 --- a/actionpack/lib/action_dispatch/middleware/session/mem_cache_store.rb +++ b/actionpack/lib/action_dispatch/middleware/session/mem_cache_store.rb @@ -6,6 +6,7 @@ module ActionDispatch class MemCacheStore < Rack::Session::Memcache include Compatibility include StaleSessionCheck + include SessionObject def initialize(app, options = {}) require 'memcache' diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb index 836136eb95..ab740a0190 100644 --- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb @@ -9,7 +9,7 @@ module ActionDispatch # of ShowExceptions. Everytime there is an exception, ShowExceptions will # store the exception in env["action_dispatch.exception"], rewrite the # PATH_INFO to the exception status code and call the rack app. - # + # # If the application returns a "X-Cascade" pass response, this middleware # will send an empty response as result with the correct status code. # If any exception happens inside the exceptions app, this middleware diff --git a/actionpack/lib/action_dispatch/middleware/ssl.rb b/actionpack/lib/action_dispatch/middleware/ssl.rb new file mode 100644 index 0000000000..9098f4e170 --- /dev/null +++ b/actionpack/lib/action_dispatch/middleware/ssl.rb @@ -0,0 +1,70 @@ +module ActionDispatch + class SSL + YEAR = 31536000 + + def self.default_hsts_options + { :expires => YEAR, :subdomains => false } + end + + def initialize(app, options = {}) + @app = app + + @hsts = options.fetch(:hsts, {}) + @hsts = {} if @hsts == true + @hsts = self.class.default_hsts_options.merge(@hsts) if @hsts + + @host = options[:host] + @port = options[:port] + end + + def call(env) + request = Request.new(env) + + if request.ssl? + status, headers, body = @app.call(env) + headers = hsts_headers.merge(headers) + flag_cookies_as_secure!(headers) + [status, headers, body] + else + redirect_to_https(request) + end + end + + private + def redirect_to_https(request) + url = URI(request.url) + url.scheme = "https" + url.host = @host if @host + url.port = @port if @port + headers = hsts_headers.merge('Content-Type' => 'text/html', + 'Location' => url.to_s) + + [301, headers, []] + end + + # http://tools.ietf.org/html/draft-hodges-strict-transport-sec-02 + def hsts_headers + if @hsts + value = "max-age=#{@hsts[:expires]}" + value += "; includeSubDomains" if @hsts[:subdomains] + { 'Strict-Transport-Security' => value } + else + {} + end + end + + def flag_cookies_as_secure!(headers) + if cookies = headers['Set-Cookie'] + cookies = cookies.split("\n") + + headers['Set-Cookie'] = cookies.map { |cookie| + if cookie !~ /;\s+secure(;|$)/ + "#{cookie}; secure" + else + cookie + end + }.join("\n") + end + end + end +end diff --git a/actionpack/lib/action_dispatch/middleware/stack.rb b/actionpack/lib/action_dispatch/middleware/stack.rb index 28e8fbdab8..bbf734f103 100644 --- a/actionpack/lib/action_dispatch/middleware/stack.rb +++ b/actionpack/lib/action_dispatch/middleware/stack.rb @@ -75,6 +75,11 @@ module ActionDispatch middlewares[i] end + def unshift(*args, &block) + middleware = self.class::Middleware.new(*args, &block) + middlewares.unshift(middleware) + end + def initialize_copy(other) self.middlewares = other.middlewares.dup end @@ -110,7 +115,7 @@ module ActionDispatch def build(app = nil, &block) app ||= block raise "MiddlewareStack#build requires an app" unless app - middlewares.reverse.inject(app) { |a, e| e.build(a) } + middlewares.freeze.reverse.inject(app) { |a, e| e.build(a) } end protected diff --git a/actionpack/lib/action_dispatch/middleware/static.rb b/actionpack/lib/action_dispatch/middleware/static.rb index 404943d720..9073e6582d 100644 --- a/actionpack/lib/action_dispatch/middleware/static.rb +++ b/actionpack/lib/action_dispatch/middleware/static.rb @@ -1,4 +1,5 @@ require 'rack/utils' +require 'active_support/core_ext/uri' module ActionDispatch class FileHandler @@ -11,14 +12,14 @@ module ActionDispatch def match?(path) path = path.dup - full_path = path.empty? ? @root : File.join(@root, ::Rack::Utils.unescape(path)) + full_path = path.empty? ? @root : File.join(@root, escape_glob_chars(unescape_path(path))) paths = "#{full_path}#{ext}" matches = Dir[paths] match = matches.detect { |m| File.file?(m) } if match match.sub!(@compiled_root, '') - match + ::Rack::Utils.escape(match) end end @@ -32,6 +33,15 @@ module ActionDispatch "{,#{ext},/index#{ext}}" end end + + def unescape_path(path) + URI.parser.unescape(path) + end + + def escape_glob_chars(path) + path.force_encoding('binary') if path.respond_to? :force_encoding + path.gsub(/[*?{}\[\]]/, "\\\\\\&") + end end class Static diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb index 0c5bafa666..823f5d25b6 100644 --- a/actionpack/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb +++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb @@ -12,8 +12,8 @@ request_dump = clean_params.empty? ? 'None' : clean_params.inspect.gsub(',', ",\n") - def debug_hash(hash) - hash.sort_by { |k, v| k.to_s }.map { |k, v| "#{k}: #{v.inspect rescue $!.message}" }.join("\n") + def debug_hash(object) + object.to_hash.sort_by { |k, v| k.to_s }.map { |k, v| "#{k}: #{v.inspect rescue $!.message}" }.join("\n") end unless self.class.method_defined?(:debug_hash) %> 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 f06c07daa5..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,6 +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. -</p>
\ No newline at end of file + Routes match in priority from top to bottom +</p> + +<p><pre><%= @routes %></pre></p> diff --git a/actionpack/lib/action_dispatch/railtie.rb b/actionpack/lib/action_dispatch/railtie.rb index 35f901c575..ccc0435a39 100644 --- a/actionpack/lib/action_dispatch/railtie.rb +++ b/actionpack/lib/action_dispatch/railtie.rb @@ -16,13 +16,22 @@ module ActionDispatch config.action_dispatch.rack_cache = { :metastore => "rails:/", :entitystore => "rails:/", - :verbose => true + :verbose => false } + config.action_dispatch.default_headers = { + 'X-Frame-Options' => 'SAMEORIGIN', + 'X-XSS-Protection' => '1; mode=block', + 'X-Content-Type-Options' => 'nosniff' + } + + config.eager_load_namespaces << ActionDispatch + 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/request/session.rb b/actionpack/lib/action_dispatch/request/session.rb new file mode 100644 index 0000000000..a05a23d953 --- /dev/null +++ b/actionpack/lib/action_dispatch/request/session.rb @@ -0,0 +1,177 @@ +require 'rack/session/abstract/id' + +module ActionDispatch + class Request < Rack::Request + # Session is responsible for lazily loading the session from store. + class Session # :nodoc: + ENV_SESSION_KEY = Rack::Session::Abstract::ENV_SESSION_KEY # :nodoc: + ENV_SESSION_OPTIONS_KEY = Rack::Session::Abstract::ENV_SESSION_OPTIONS_KEY # :nodoc: + + def self.create(store, env, default_options) + session_was = find env + session = Request::Session.new(store, env) + session.merge! session_was if session_was + + set(env, session) + Options.set(env, Request::Session::Options.new(store, env, default_options)) + session + end + + def self.find(env) + env[ENV_SESSION_KEY] + end + + def self.set(env, session) + env[ENV_SESSION_KEY] = session + end + + class Options #:nodoc: + def self.set(env, options) + env[ENV_SESSION_OPTIONS_KEY] = options + end + + def self.find(env) + env[ENV_SESSION_OPTIONS_KEY] + end + + def initialize(by, env, default_options) + @by = by + @env = env + @delegate = default_options.dup + end + + def [](key) + if key == :id + @delegate.fetch(key) { + @delegate[:id] = @by.send(:extract_session_id, @env) + } + else + @delegate[key] + end + end + + def []=(k,v); @delegate[k] = v; end + def to_hash; @delegate.dup; end + def values_at(*args); @delegate.values_at(*args); end + end + + def initialize(by, env) + @by = by + @env = env + @delegate = {} + @loaded = false + @exists = nil # we haven't checked yet + end + + def options + Options.find @env + end + + def destroy + clear + options = self.options || {} + new_sid = @by.send(:destroy_session, @env, options[:id], options) + options[:id] = new_sid # Reset session id with a new value or nil + + # Load the new sid to be written with the response + @loaded = false + load_for_write! + end + + def [](key) + load_for_read! + @delegate[key.to_s] + end + + def has_key?(key) + load_for_read! + @delegate.key?(key.to_s) + end + alias :key? :has_key? + alias :include? :has_key? + + def keys + @delegate.keys + end + + def values + @delegate.values + end + + def []=(key, value) + load_for_write! + @delegate[key.to_s] = value + end + + def clear + load_for_write! + @delegate.clear + end + + def to_hash + load_for_read! + @delegate.dup.delete_if { |_,v| v.nil? } + end + + def update(hash) + load_for_write! + @delegate.update stringify_keys(hash) + end + + def delete(key) + load_for_write! + @delegate.delete key.to_s + end + + def inspect + if loaded? + super + else + "#<#{self.class}:0x#{(object_id << 1).to_s(16)} not yet loaded>" + end + end + + def exists? + return @exists unless @exists.nil? + @exists = @by.send(:session_exists?, @env) + end + + def loaded? + @loaded + end + + def empty? + load_for_read! + @delegate.empty? + end + + def merge!(other) + load_for_write! + @delegate.merge!(other) + end + + private + + def load_for_read! + load! if !loaded? && exists? + end + + def load_for_write! + load! unless loaded? + end + + def load! + id, session = @by.load_session @env + options[:id] = id + @delegate.replace(stringify_keys(session)) + @loaded = true + end + + def stringify_keys(other) + other.each_with_object({}) { |(key, value), hash| + hash[key.to_s] = value + } + end + end + end +end diff --git a/actionpack/lib/action_dispatch/routing.rb b/actionpack/lib/action_dispatch/routing.rb index 107fe80d1f..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' @@ -182,10 +183,13 @@ module ActionDispatch # # == HTTP Methods # - # Using the <tt>:via</tt> option when specifying a route allows you to restrict it to a specific HTTP method. - # Possible values are <tt>:post</tt>, <tt>:get</tt>, <tt>:put</tt>, <tt>:delete</tt> and <tt>:any</tt>. - # If your route needs to respond to more than one method you can use an array, e.g. <tt>[ :get, :post ]</tt>. - # The default value is <tt>:any</tt> which means that the route will respond to any of the HTTP methods. + # Using the <tt>:via</tt> option when specifying a route allows you to + # restrict it to a specific HTTP method. Possible values are <tt>:post</tt>, + # <tt>:get</tt>, <tt>:patch</tt>, <tt>:put</tt>, <tt>:delete</tt> and + # <tt>:any</tt>. If your route needs to respond to more than one method you + # can use an array, e.g. <tt>[ :get, :post ]</tt>. The default value is + # <tt>:any</tt> which means that the route will respond to any of the HTTP + # methods. # # Examples: # @@ -198,7 +202,7 @@ module ActionDispatch # === HTTP helper methods # # An alternative method of specifying which HTTP method a route should respond to is to use the helper - # methods <tt>get</tt>, <tt>post</tt>, <tt>put</tt> and <tt>delete</tt>. + # methods <tt>get</tt>, <tt>post</tt>, <tt>patch</tt>, <tt>put</tt> and <tt>delete</tt>. # # Examples: # @@ -215,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 @@ -283,6 +293,6 @@ module ActionDispatch autoload :PolymorphicRoutes, 'action_dispatch/routing/polymorphic_routes' SEPARATORS = %w( / . ? ) #:nodoc: - HTTP_METHODS = [:get, :head, :post, :put, :delete, :options] #:nodoc: + HTTP_METHODS = [:get, :head, :post, :patch, :put, :delete, :options] #:nodoc: end end 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 cf9c0d7b6a..ddb34a2394 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -1,6 +1,7 @@ require 'active_support/core_ext/hash/except' -require 'active_support/core_ext/object/blank' -require 'active_support/core_ext/object/inclusion' +require 'active_support/core_ext/hash/reverse_merge' +require 'active_support/core_ext/hash/slice' +require 'active_support/core_ext/enumerable' require 'active_support/inflector' require 'action_dispatch/routing/redirection' @@ -34,6 +35,8 @@ module ActionDispatch } return true + ensure + req.reset_parameters end def call(env) @@ -58,6 +61,16 @@ module ActionDispatch @options = (@scope[:options] || {}).merge(options) @path = normalize_path(path) normalize_options! + + via_all = @options.delete(:via) if @options[:via] == :all + + if !via_all && request_method_condition.empty? + msg = "You should not use the `match` method in your router without specifying an HTTP method.\n" \ + "If you want to expose your action to GET, use `get` in the router:\n\n" \ + " Instead of: match \"controller#action\"\n" \ + " Do: get \"controller#action\"" + raise msg + end end def to_route @@ -87,6 +100,10 @@ module ActionDispatch raise ArgumentError, "Regexp multiline option not allowed in routing requirements: #{requirement.inspect}" end end + + if @options[:constraints].is_a?(Hash) + (@options[:defaults] ||= {}).reverse_merge!(defaults_from_constraints(@options[:constraints])) + end end # match "account/overview" @@ -232,6 +249,11 @@ module ActionDispatch def default_action @options[:action] || @scope[:action] end + + def defaults_from_constraints(constraints) + url_keys = [:protocol, :subdomain, :domain, :host, :port] + constraints.slice(*url_keys).select{ |k, v| v.is_a?(String) || v.is_a?(Fixnum) } + end end # Invokes Rack::Mount::Utils.normalize path and ensure that @@ -239,12 +261,12 @@ 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 def self.normalize_name(name) - normalize_path(name)[1..-1].gsub("/", "_") + normalize_path(name)[1..-1].tr("/", "_") end module Base @@ -254,11 +276,16 @@ module ActionDispatch # # For options, see +match+, as +root+ uses it internally. # + # You can also pass a string which will expand + # + # root 'pages#main' + # # You should put the root route at the top of <tt>config/routes.rb</tt>, # because this means it will be matched first. As this is the most popular route # of most Rails applications, this is beneficial. def root(options = {}) - match '/', { :as => :root }.merge(options) + options = { :to => options } if options.is_a?(String) + match '/', { :as => :root, :via => :get }.merge(options) end # Matches a url pattern to one or more routes. Any symbols in a pattern @@ -328,7 +355,7 @@ module ActionDispatch # +call+ or a string representing a controller's action. # # match 'path', :to => 'controller#action' - # match 'path', :to => lambda { [200, {}, "Success!"] } + # match 'path', :to => lambda { |env| [200, {}, "Success!"] } # match 'path', :to => RackApp # # [:on] @@ -376,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 @@ -402,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 @@ -409,7 +444,8 @@ 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)) @@ -436,7 +472,7 @@ module ActionDispatch app.railtie_name else class_name = app.class.is_a?(Class) ? app.name : app.class.name - ActiveSupport::Inflector.underscore(class_name).gsub("/", "_") + ActiveSupport::Inflector.underscore(class_name).tr("/", "_") end end @@ -446,7 +482,11 @@ module ActionDispatch _route = @set.named_routes.routes[name.to_sym] _routes = @set app.routes.define_mounted_helper(name) - app.routes.class_eval do + app.routes.singleton_class.class_eval do + define_method :mounted? do + true + end + define_method :_generate_prefix do |options| prefix_options = options.slice(*_route.segment_keys) # we must actually delete prefix segment keys to avoid passing them to next url_for @@ -463,9 +503,7 @@ module ActionDispatch # Define a route that only recognizes HTTP GET. # For supported arguments, see <tt>Base#match</tt>. # - # Example: - # - # get 'bacon', :to => 'food#bacon' + # get 'bacon', :to => 'food#bacon' def get(*args, &block) map_method(:get, args, &block) end @@ -473,19 +511,23 @@ module ActionDispatch # Define a route that only recognizes HTTP POST. # For supported arguments, see <tt>Base#match</tt>. # - # Example: - # - # post 'bacon', :to => 'food#bacon' + # post 'bacon', :to => 'food#bacon' def post(*args, &block) map_method(:post, args, &block) end - # Define a route that only recognizes HTTP PUT. + # Define a route that only recognizes HTTP PATCH. # For supported arguments, see <tt>Base#match</tt>. # - # Example: + # patch 'bacon', :to => 'food#bacon' + def patch(*args, &block) + map_method(:patch, args, &block) + end + + # Define a route that only recognizes HTTP PUT. + # For supported arguments, see <tt>Base#match</tt>. # - # put 'bacon', :to => 'food#bacon' + # put 'bacon', :to => 'food#bacon' def put(*args, &block) map_method(:put, args, &block) end @@ -493,9 +535,7 @@ module ActionDispatch # Define a route that only recognizes HTTP DELETE. # For supported arguments, see <tt>Base#match</tt>. # - # Example: - # - # delete 'broccoli', :to => 'food#broccoli' + # delete 'broccoli', :to => 'food#broccoli' def delete(*args, &block) map_method(:delete, args, &block) end @@ -503,7 +543,8 @@ module ActionDispatch private def map_method(method, args, &block) options = args.extract_options! - options[:via] = method + options[:via] = method + options[:path] ||= args.first if args.first.is_a?(String) match(*args, options, &block) self end @@ -522,13 +563,13 @@ module ActionDispatch # This will create a number of routes for each of the posts and comments # controller. For <tt>Admin::PostsController</tt>, Rails will create: # - # GET /admin/posts - # GET /admin/posts/new - # POST /admin/posts - # GET /admin/posts/1 - # GET /admin/posts/1/edit - # PUT /admin/posts/1 - # DELETE /admin/posts/1 + # GET /admin/posts + # GET /admin/posts/new + # POST /admin/posts + # GET /admin/posts/1 + # GET /admin/posts/1/edit + # PATCH/PUT /admin/posts/1 + # DELETE /admin/posts/1 # # If you want to route /posts (without the prefix /admin) to # <tt>Admin::PostsController</tt>, you could use @@ -556,13 +597,13 @@ module ActionDispatch # not use scope. In the last case, the following paths map to # +PostsController+: # - # GET /admin/posts - # GET /admin/posts/new - # POST /admin/posts - # GET /admin/posts/1 - # GET /admin/posts/1/edit - # PUT /admin/posts/1 - # DELETE /admin/posts/1 + # GET /admin/posts + # GET /admin/posts/new + # POST /admin/posts + # GET /admin/posts/1 + # GET /admin/posts/1/edit + # PATCH/PUT /admin/posts/1 + # DELETE /admin/posts/1 module Scoping # Scopes a set of routes to the given default options. # @@ -608,6 +649,10 @@ module ActionDispatch block, options[:constraints] = options[:constraints], {} end + if options[:constraints].is_a?(Hash) + (options[:defaults] ||= {}).reverse_merge!(defaults_from_constraints(options[:constraints])) + end + scope_options.each do |option| if value = options.delete(option) recover[option] = @scope[option] @@ -634,7 +679,6 @@ module ActionDispatch # Scopes routes to a specific controller # - # Example: # controller "food" do # match "bacon", :action => "bacon" # end @@ -651,13 +695,13 @@ module ActionDispatch # # This generates the following routes: # - # admin_posts GET /admin/posts(.:format) admin/posts#index - # admin_posts POST /admin/posts(.:format) admin/posts#create - # new_admin_post GET /admin/posts/new(.:format) admin/posts#new - # edit_admin_post GET /admin/posts/:id/edit(.:format) admin/posts#edit - # admin_post GET /admin/posts/:id(.:format) admin/posts#show - # admin_post PUT /admin/posts/:id(.:format) admin/posts#update - # admin_post DELETE /admin/posts/:id(.:format) admin/posts#destroy + # admin_posts GET /admin/posts(.:format) admin/posts#index + # admin_posts POST /admin/posts(.:format) admin/posts#create + # new_admin_post GET /admin/posts/new(.:format) admin/posts#new + # edit_admin_post GET /admin/posts/:id/edit(.:format) admin/posts#edit + # admin_post GET /admin/posts/:id(.:format) admin/posts#show + # admin_post PATCH/PUT /admin/posts/:id(.:format) admin/posts#update + # admin_post DELETE /admin/posts/:id(.:format) admin/posts#destroy # # === Options # @@ -713,7 +757,7 @@ module ActionDispatch # # Routes can also be constrained to an IP or a certain range of IP addresses: # - # constraints(:ip => /192.168.\d+.\d+/) do + # constraints(:ip => /192\.168\.\d+\.\d+/) do # resources :posts # end # @@ -816,6 +860,11 @@ module ActionDispatch def override_keys(child) #:nodoc: child.key?(:only) || child.key?(:except) ? [:only, :except] : [] end + + def defaults_from_constraints(constraints) + url_keys = [:protocol, :subdomain, :domain, :host, :port] + constraints.slice(*url_keys).select{ |k, v| v.is_a?(String) || v.is_a?(Fixnum) } + end end # Resource routing allows you to quickly declare all of the common routes @@ -861,17 +910,18 @@ 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] + RESOURCE_OPTIONS = [:as, :controller, :path, :only, :except, :param, :concerns] CANONICAL_ACTIONS = %w(index create new show update destroy) class Resource #:nodoc: - attr_reader :controller, :path, :options + attr_reader :controller, :path, :options, :param def initialize(entities, options = {}) @name = entities.to_s @path = (options[:path] || @name).to_s @controller = (options[:controller] || @name).to_s @as = options[:as] + @param = (options[:param] || :id).to_sym @options = options end @@ -916,15 +966,21 @@ module ActionDispatch alias :collection_scope :path def member_scope - "#{path}/:id" + "#{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}_id" + "#{path}/:#{nested_param}" end end @@ -972,12 +1028,12 @@ module ActionDispatch # the +GeoCoders+ controller (note that the controller is named after # the plural): # - # GET /geocoder/new - # POST /geocoder - # GET /geocoder - # GET /geocoder/edit - # PUT /geocoder - # DELETE /geocoder + # GET /geocoder/new + # POST /geocoder + # GET /geocoder + # GET /geocoder/edit + # PATCH/PUT /geocoder + # DELETE /geocoder # # === Options # Takes same options as +resources+. @@ -991,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) @@ -1000,9 +1058,12 @@ module ActionDispatch end if parent_resource.actions.include?(:new) member do - get :edit if parent_resource.actions.include?(:edit) - get :show if parent_resource.actions.include?(:show) - put :update if parent_resource.actions.include?(:update) + get :edit if parent_resource.actions.include?(:edit) + get :show if parent_resource.actions.include?(:show) + if parent_resource.actions.include?(:update) + patch :update + put :update + end delete :destroy if parent_resource.actions.include?(:destroy) end end @@ -1020,13 +1081,13 @@ module ActionDispatch # creates seven different routes in your application, all mapping to # the +Photos+ controller: # - # GET /photos - # GET /photos/new - # POST /photos - # GET /photos/:id - # GET /photos/:id/edit - # PUT /photos/:id - # DELETE /photos/:id + # GET /photos + # GET /photos/new + # POST /photos + # GET /photos/:id + # GET /photos/:id/edit + # PATCH/PUT /photos/:id + # DELETE /photos/:id # # Resources can also be nested infinitely by using this block syntax: # @@ -1036,13 +1097,13 @@ module ActionDispatch # # This generates the following comments routes: # - # GET /photos/:photo_id/comments - # GET /photos/:photo_id/comments/new - # POST /photos/:photo_id/comments - # GET /photos/:photo_id/comments/:id - # GET /photos/:photo_id/comments/:id/edit - # PUT /photos/:photo_id/comments/:id - # DELETE /photos/:photo_id/comments/:id + # GET /photos/:photo_id/comments + # GET /photos/:photo_id/comments/new + # POST /photos/:photo_id/comments + # GET /photos/:photo_id/comments/:id + # GET /photos/:photo_id/comments/:id/edit + # PATCH/PUT /photos/:photo_id/comments/:id + # DELETE /photos/:photo_id/comments/:id # # === Options # Takes same options as <tt>Base#match</tt> as well as: @@ -1104,13 +1165,36 @@ module ActionDispatch # # The +comments+ resource here will have the following routes generated for it: # - # post_comments GET /posts/:post_id/comments(.:format) - # post_comments POST /posts/:post_id/comments(.:format) - # new_post_comment GET /posts/:post_id/comments/new(.:format) - # edit_comment GET /sekret/comments/:id/edit(.:format) - # comment GET /sekret/comments/:id(.:format) - # comment PUT /sekret/comments/:id(.:format) - # comment DELETE /sekret/comments/:id(.:format) + # post_comments GET /posts/:post_id/comments(.:format) + # post_comments POST /posts/:post_id/comments(.:format) + # new_post_comment GET /posts/:post_id/comments/new(.:format) + # edit_comment GET /sekret/comments/:id/edit(.:format) + # comment GET /sekret/comments/:id(.:format) + # comment PATCH/PUT /sekret/comments/:id(.:format) + # comment DELETE /sekret/comments/:id(.:format) + # + # [:shallow_prefix] + # Prefixes nested shallow route names with specified prefix. + # + # scope :shallow_prefix => "sekret" do + # resources :posts do + # resources :comments, :shallow => true + # end + # end + # + # The +comments+ resource here will have the following routes generated for it: + # + # post_comments GET /posts/:post_id/comments(.:format) + # post_comments POST /posts/:post_id/comments(.:format) + # new_post_comment GET /posts/:post_id/comments/new(.:format) + # edit_sekret_comment GET /comments/:id/edit(.:format) + # sekret_comment GET /comments/:id(.:format) + # 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 # @@ -1129,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) @@ -1139,9 +1225,12 @@ module ActionDispatch end if parent_resource.actions.include?(:new) member do - get :edit if parent_resource.actions.include?(:edit) - get :show if parent_resource.actions.include?(:show) - put :update if parent_resource.actions.include?(:update) + get :edit if parent_resource.actions.include?(:edit) + get :show if parent_resource.actions.include?(:show) + if parent_resource.actions.include?(:update) + patch :update + put :update + end delete :destroy if parent_resource.actions.include?(:destroy) end end @@ -1304,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 @@ -1410,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: @@ -1434,9 +1523,9 @@ 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] - path = if canonical_action?(action, path.blank?) + if canonical_action?(action, path.blank?) prefix.to_s else "#{prefix}/#{action_path(action, path)}" @@ -1496,15 +1585,122 @@ module ActionDispatch end end + # Routing Concerns allow 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. + # + # Concerns may be defined inline, using a block, or handled by + # another object, by passing that object as the second parameter. + # + # The concern object, if supplied, should respond to <tt>call</tt>, + # which will receive two parameters: + # + # * The current mapper + # * A hash of options which the concern object may use + # + # Options may also be used by concerns defined in a block by accepting + # a block parameter. So, using a block, you might do something as + # simple as limit the actions available on certain resources, passing + # standard resource options through the concern: + # + # concern :commentable do |options| + # resources :comments, options + # end + # + # resources :posts, concerns: :commentable + # resources :archived_posts do + # # Don't allow comments on archived posts + # concerns :commentable, only: [:index, :show] + # end + # + # Or, using a callable object, you might implement something more + # specific to your application, which would be out of place in your + # routes file. + # + # # purchasable.rb + # class Purchasable + # def initialize(defaults = {}) + # @defaults = defaults + # end + # + # def call(mapper, options = {}) + # options = @defaults.merge(options) + # mapper.resources :purchases + # mapper.resources :receipts + # mapper.resources :returns if options[:returnable] + # end + # end + # + # # routes.rb + # concern :purchasable, Purchasable.new(returnable: true) + # + # resources :toys, concerns: :purchasable + # resources :electronics, concerns: :purchasable + # resources :pets do + # concerns :purchasable, returnable: false + # end + # + # Any routing helpers can be used inside a concern. If using a + # callable, they're accessible from the Mapper that's passed to + # <tt>call</tt>. + def concern(name, callable = nil, &block) + callable ||= lambda { |mapper, options| mapper.instance_exec(options, &block) } + @concerns[name] = callable + 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(*args) + options = args.extract_options! + args.flatten.each do |name| + if concern = @concerns[name] + concern.call(self, options) + else + raise ArgumentError, "No concern named #{name} was found!" + end + end + end + end + def initialize(set) #:nodoc: @set = set @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 013cf93dbc..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 @@ -43,18 +45,18 @@ module ActionDispatch # edit_polymorphic_path(@post) # => "/posts/1/edit" # polymorphic_path(@post, :format => :pdf) # => "/posts/1.pdf" # - # == Using with mounted engines - # - # If you use mounted engine, there is a possibility that you will need to use - # polymorphic_url pointing at engine's routes. To do that, just pass proxy used - # to reach engine's routes as a first argument: + # == Usage with mounted engines # - # For example: + # If you are using a mounted engine and you need to use a polymorphic_url + # pointing at the engine's routes, pass in the engine's route proxy as the first + # argument to the method. For example: # - # polymorphic_url([blog, @post]) # it will call blog.post_path(@post) - # form_for([blog, @post]) # => "/blog/posts/1 + # polymorphic_url([blog, @post]) # calls blog.post_path(@post) + # 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: # @@ -97,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 : @@ -124,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 @@ -165,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 @@ -177,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/redirection.rb b/actionpack/lib/action_dispatch/routing/redirection.rb index 617b24b46a..205ff44b1c 100644 --- a/actionpack/lib/action_dispatch/routing/redirection.rb +++ b/actionpack/lib/action_dispatch/routing/redirection.rb @@ -1,4 +1,8 @@ require 'action_dispatch/http/request' +require 'active_support/core_ext/uri' +require 'active_support/core_ext/array/extract_options' +require 'rack/utils' +require 'action_controller/metal/exceptions' module ActionDispatch module Routing @@ -13,6 +17,14 @@ module ActionDispatch def call(env) req = Request.new(env) + # If any of the path parameters has a invalid encoding then + # raise since it's likely to trigger errors further on. + req.symbolized_path_parameters.each do |key, value| + unless value.valid_encoding? + raise ActionController::BadRequest, "Invalid parameter: #{key} => #{value}" + end + end + uri = URI.parse(path(req.symbolized_path_parameters, req)) uri.scheme ||= req.scheme uri.host ||= req.host @@ -32,6 +44,25 @@ module ActionDispatch def path(params, request) block.call params, request end + + def inspect + "redirect(#{status})" + end + end + + class PathRedirect < Redirect + def path(params, request) + (params.empty? || !block.match(/%\{\w*\}/)) ? block : (block % escape(params)) + end + + def inspect + "redirect(#{status}, #{block})" + end + + private + def escape(params) + Hash[params.map{ |k,v| [k, Rack::Utils.escape(v)] }] + end end class OptionRedirect < Redirect # :nodoc: @@ -46,8 +77,21 @@ module ActionDispatch :params => request.query_parameters }.merge options + if !params.empty? && url_options[:path].match(/%\{\w*\}/) + url_options[:path] = (url_options[:path] % escape_path(params)) + end + ActionDispatch::Http::URL.url_for url_options end + + def inspect + "redirect(#{status}, #{options.map{ |k,v| "#{k}: #{v}" }.join(', ')})" + end + + private + def escape_path(params) + Hash[params.map{ |k,v| [k, URI.parser.escape(v)] }] + end end module Redirection @@ -67,10 +111,13 @@ module ActionDispatch # params, depending of how many arguments your block accepts. A string is required as a # return value. # - # match 'jokes/:number', :to => redirect do |params, request| - # path = (params[:number].to_i.even? ? "/wheres-the-beef" : "/i-love-lamp") + # match 'jokes/:number', :to => redirect { |params, request| + # path = (params[:number].to_i.even? ? "wheres-the-beef" : "i-love-lamp") # "http://#{request.host_with_port}/#{path}" - # end + # } + # + # Note that the +do end+ syntax for the redirect block wouldn't work, as Ruby would pass + # the block to +match+ instead of +redirect+. Use <tt>{ ... }</tt> instead. # # The options version of redirect allows you to supply only the parts of the url which need # to change, it also supports interpolation of the path similar to the first example. @@ -85,16 +132,12 @@ module ActionDispatch # match 'accounts/:name' => redirect(SubdomainRedirector.new('api')) # def redirect(*args, &block) - options = args.last.is_a?(Hash) ? args.pop : {} + options = args.extract_options! status = options.delete(:status) || 301 + path = args.shift return OptionRedirect.new(status, options) if options.any? - - path = args.shift - - block = lambda { |params, request| - (params.empty? || !path.match(/%\{\w*\}/)) ? path : (path % params) - } if String === path + return PathRedirect.new(status, path) if String === path block = path if path.respond_to? :call raise ArgumentError, "redirection argument not supported" unless block diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 8e3975e369..1fe40d8458 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' @@ -9,6 +8,12 @@ require 'action_controller/metal/exceptions' module ActionDispatch module Routing class RouteSet #:nodoc: + # Since the router holds references to many parts of the system + # like engines, controllers and the application itself, inspecting + # the route set can actually be really slow, therefore we default + # alias inspect to to_s. + alias inspect to_s + PARAMETERS_KEY = 'action_dispatch.request.path_parameters' class Dispatcher #:nodoc: @@ -20,6 +25,15 @@ module ActionDispatch def call(env) params = env[PARAMETERS_KEY] + + # If any of the path parameters has a invalid encoding then + # raise since it's likely to trigger errors further on. + params.each do |key, value| + unless value.valid_encoding? + raise ActionController::BadRequest, "Invalid parameter: #{key} => #{value}" + end + end + prepare_params!(params) # Just raise undefined constant errors if a controller was specified as default. @@ -31,6 +45,7 @@ module ActionDispatch end def prepare_params!(params) + normalize_controller!(params) merge_default_action!(params) split_glob_param!(params) if @glob_param end @@ -66,6 +81,10 @@ module ActionDispatch controller.action(action).call(env) end + def normalize_controller!(params) + params[:controller] = params[:controller].underscore if params.key?(:controller) + end + def merge_default_action!(params) params[:action] ||= 'index' end @@ -85,7 +104,25 @@ module ActionDispatch def initialize @routes = {} @helpers = [] - @module = Module.new + @module = Module.new do + protected + + def handle_positional_args(args, options, segment_keys) + inner_options = args.extract_options! + result = options.dup + + if args.size > 0 + keys = segment_keys + if args.size < keys.size - 1 # take format into account + keys -= self.url_options.keys if self.respond_to?(:url_options) + keys -= options.keys + end + result.merge!(Hash[keys.zip(args)]) + end + + result.merge!(inner_options) + end + end end def helper_names @@ -124,43 +161,12 @@ module ActionDispatch end private - def url_helper_name(name, kind = :url) - :"#{name}_#{kind}" - end - - def hash_access_name(name, kind = :url) - :"hash_for_#{name}_#{kind}" - end def define_named_route_methods(name, route) - {:url => {:only_path => false}, :path => {:only_path => true}}.each do |kind, opts| - hash = route.defaults.merge(:use_route => name).merge(opts) - define_hash_access route, name, kind, hash - define_url_helper route, name, kind, hash - end - end - - def define_hash_access(route, name, kind, options) - selector = hash_access_name(name, kind) - - @module.module_eval do - remove_possible_method selector - - define_method(selector) do |*args| - inner_options = args.extract_options! - result = options.dup - - if args.any? - result[:_positional_args] = args - result[:_positional_keys] = route.segment_keys - end - - result.merge(inner_options) - end - - protected selector - end - helpers << selector + 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 @@ -176,23 +182,51 @@ module ActionDispatch # # foo_url(bar, baz, bang, :sort_by => 'baz') # - def define_url_helper(route, name, kind, options) - selector = url_helper_name(name, kind) - hash_access_method = hash_access_name(name, kind) - + def define_url_helper(route, name, options) @module.module_eval <<-END_EVAL, __FILE__, __LINE__ + 1 - remove_possible_method :#{selector} - def #{selector}(*args) - url_for(#{hash_access_method}(*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) + options[:path] = "#{optimized_helper(route)}" + ActionDispatch::Http::URL.url_for(options) + else + url_for(handle_positional_args(args, #{options.inspect}, #{route.segment_keys.inspect})) + end end END_EVAL - helpers << selector + + helpers << name + end + + # Clause check about when we need to generate an optimized helper. + def optimize_helper?(route) #:nodoc: + route.requirements.except(:controller, :action).empty? + end + + # Generates the interpolation to be used in the optimized helper. + def optimized_helper(route) + string_route = route.ast.to_s + + while string_route.gsub!(/\([^\)]*\)/, "") + true + end + + route.required_parts.each_with_index do |part, i| + # Replace each route parameter + # e.g. :id for regular parameter or *path for globbing + # with ruby string interpolation code + string_route.gsub!(/(\*|:)#{part}/, "\#{Journey::Router::Utils.escape_fragment(args[#{i}].to_param)}") + end + + string_route end end 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 :default_url_options, :request_class alias :routes :set @@ -204,17 +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.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 = [] @@ -246,8 +270,7 @@ module ActionDispatch def eval_block(block) if block.arity == 1 raise "You are using the old router DSL which has been removed in Rails 3.1. " << - "Please check how to update your routes file at: http://www.engineyard.com/blog/2010/the-lowdown-on-routes-in-rails-3/ " << - "or add the rails_legacy_mapper gem to your Gemfile" + "Please check how to update your routes file at: http://www.engineyard.com/blog/2010/the-lowdown-on-routes-in-rails-3/" end mapper = Mapper.new(self) if default_scope @@ -294,7 +317,7 @@ module ActionDispatch end end - MountedHelpers.class_eval <<-RUBY + MountedHelpers.class_eval(<<-RUBY, __FILE__, __LINE__ + 1) def #{name} @#{name} ||= _#{name} end @@ -313,7 +336,7 @@ module ActionDispatch # Rails.application.routes.url_helpers.url_for(args) @_routes = routes class << self - delegate :url_for, :to => '@_routes' + delegate :url_for, :optimize_routes_generation?, :to => '@_routes' end # Make named_routes available in the module singleton @@ -346,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] @@ -383,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 @@ -414,22 +438,21 @@ module ActionDispatch attr_reader :options, :recall, :set, :named_route - def initialize(options, recall, set, extras = false) + def initialize(options, recall, set) @named_route = options.delete(:use_route) @options = options.dup @recall = recall.dup @set = set - @extras = extras normalize_options! normalize_controller_action_id! use_relative_controller! - controller.sub!(%r{^/}, '') if controller + normalize_controller! handle_nil_action! end def controller - @controller ||= @options[:controller] + @options[:controller] end def current_controller @@ -438,9 +461,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 @@ -486,10 +507,15 @@ module ActionDispatch old_parts = current_controller.split('/') size = controller.count("/") + 1 parts = old_parts[0...-size] << controller - @controller = @options[:controller] = parts.join("/") + @options[:controller] = parts.join("/") end end + # Remove leading slashes from controllers + def normalize_controller! + @options[:controller] = controller.sub(%r{^/}, '') if controller + end + # This handles the case of :action => nil being explicitly passed. # It is identical to :action => "index" def handle_nil_action! @@ -499,20 +525,12 @@ module ActionDispatch recall[:action] = options.delete(:action) if options[:action] == 'index' end + # Generates a path from routes, returns [path, params] + # if no path is returned the formatter will raise Journey::Router::RoutingError def generate - path, params = @set.formatter.generate(:path_info, named_route, options, recall, PARAMETERIZE) - - raise_routing_error unless path - - return [path, params.keys] if @extras - - [path, params] - rescue Journey::Router::RoutingError - raise_routing_error - end - - def raise_routing_error - raise ActionController::RoutingError, "No route matches #{options.inspect}" + @set.formatter.generate(:path_info, named_route, options, recall, PARAMETERIZE) + rescue Journey::Router::RoutingError => e + raise ActionController::UrlGenerationError, "No route matches #{options.inspect} #{e.message}" end def different_controller? @@ -537,40 +555,53 @@ module ActionDispatch end def generate_extras(options, recall={}) - generate(options, recall, true) + path, params = generate(options, recall) + return path, params.keys end - def generate(options, recall = {}, extras = false) - Generator.new(options, recall, self, extras).generate + def generate(options, recall = {}) + Generator.new(options, recall, self).generate 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 + end + + def optimize_routes_generation? + !mounted? && default_url_options.empty? + end def _generate_prefix(options = {}) nil end + # The +options+ argument must be +nil+ or a hash whose keys are *symbols*. def url_for(options) - options = (options || {}).reverse_merge!(default_url_options) - - handle_positional_args(options) + options = default_url_options.merge(options || {}) user, password = extract_authentication(options) - path_segments = options.delete(:_path_segments) - script_name = options.delete(:script_name) + recall = options.delete(:_recall) - path = (script_name.blank? ? _generate_prefix(options) : script_name.chomp('/')).to_s + 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_addition, params = generate(path_options, path_segments || {}) - path << path_addition + path, params = generate(path_options, recall || {}) params.merge!(options[:params] || {}) ActionDispatch::Http::URL.url_for(options.merge!({ :path => path, + :script_name => script_name, :params => params, :user => user, :password => password @@ -584,6 +615,7 @@ module ActionDispatch def recognize_path(path, environment = {}) method = (environment[:method] || "GET").to_s.upcase path = Journey::Router::Utils.normalize_path(path) unless path =~ %r{://} + extras = environment[:extras] || {} begin env = Rack::MockRequest.env_for(path, {:method => method}) @@ -593,6 +625,7 @@ module ActionDispatch req = @request_class.new(env) @router.recognize(req) do |route, matches, params| + params.merge!(extras) params.each do |key, value| if value.is_a?(String) value = value.dup.force_encoding(Encoding::BINARY) @@ -606,9 +639,13 @@ module ActionDispatch dispatcher = dispatcher.app end - if dispatcher.is_a?(Dispatcher) && dispatcher.controller(params, false) - dispatcher.prepare_params!(params) - return params + if dispatcher.is_a?(Dispatcher) + if dispatcher.controller(params, false) + dispatcher.prepare_params!(params) + return params + else + raise ActionController::RoutingError, "A route matches #{path.inspect}, but references missing controller: #{params[:controller].camelize}Controller" + end end end @@ -625,16 +662,6 @@ module ActionDispatch end end - def handle_positional_args(options) - return unless args = options.delete(:_positional_args) - - keys = options.delete(:_positional_keys) - keys -= options.keys if args.size < keys.size - 1 # take format into account - - # Tell url_for to skip default_url_options - options.merge!(Hash[args.zip(keys).map { |v, k| [k, v] }]) - end - end end end diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb index ee6616c5d3..d4cd537048 100644 --- a/actionpack/lib/action_dispatch/routing/url_for.rb +++ b/actionpack/lib/action_dispatch/routing/url_for.rb @@ -68,7 +68,7 @@ module ActionDispatch # This generates, among other things, the method <tt>users_path</tt>. By default, # this method is accessible from your controllers, views and mailers. If you need # to access this auto-generated method from other places (such as a model), then - # you can do that by including ActionController::UrlFor in your class: + # you can do that by including Rails.application.routes.url_helpers in your class: # # class User < ActiveRecord::Base # include Rails.application.routes.url_helpers @@ -95,6 +95,8 @@ module ActionDispatch self.default_url_options = {} end + + include(*_url_for_modules) if respond_to?(:_url_for_modules) end def initialize(*) @@ -102,6 +104,9 @@ module ActionDispatch super end + # Hook overridden in controller to add request information + # with `default_url_options`. Application logic should not + # go into url_options. def url_options default_url_options end @@ -129,8 +134,6 @@ module ActionDispatch # Any other key (<tt>:controller</tt>, <tt>:action</tt>, etc.) given to # +url_for+ is forwarded to the Routes module. # - # Examples: - # # url_for :controller => 'tasks', :action => 'testing', :host => 'somehost.org', :port => '8080' # # => 'http://somehost.org:8080/tasks/testing' # url_for :controller => 'tasks', :action => 'testing', :host => 'somehost.org', :anchor => 'ok', :only_path => true @@ -141,10 +144,12 @@ module ActionDispatch # # => 'http://somehost.org/tasks/testing?number=33' def url_for(options = nil) case options + when nil + _routes.url_for(url_options.symbolize_keys) + when Hash + _routes.url_for(options.symbolize_keys.reverse_merge!(url_options)) when String options - when nil, Hash - _routes.url_for((options || {}).symbolize_keys.reverse_merge!(url_options)) else polymorphic_url(options) end @@ -152,6 +157,11 @@ module ActionDispatch protected + def optimize_routes_generation? + return @_optimized_routes if defined?(@_optimized_routes) + @_optimized_routes = _routes.optimize_routes_generation? && default_url_options.empty? + end + def _with_routes(routes) old_routes, @_routes = @_routes, routes yield diff --git a/actionpack/lib/action_dispatch/testing/assertions/dom.rb b/actionpack/lib/action_dispatch/testing/assertions/dom.rb index edea6dab39..6c61d4e61a 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/dom.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/dom.rb @@ -1,15 +1,12 @@ -require 'action_controller/vendor/html-scanner' +require 'action_view/vendor/html-scanner' module ActionDispatch module Assertions module DomAssertions # \Test two HTML strings for equivalency (e.g., identical up to reordering of attributes) # - # ==== Examples - # # # assert that the referenced method generates the appropriate HTML string # assert_dom_equal '<a href="http://www.example.com">Apples</a>', link_to("Apples", "http://www.example.com") - # def assert_dom_equal(expected, actual, message = "") expected_dom = HTML::Document.new(expected).root actual_dom = HTML::Document.new(actual).root @@ -18,11 +15,8 @@ module ActionDispatch # The negated form of +assert_dom_equivalent+. # - # ==== Examples - # # # assert that the referenced method does not generate the specified HTML string # assert_dom_not_equal '<a href="http://www.example.com">Apples</a>', link_to("Oranges", "http://www.example.com") - # def assert_dom_not_equal(expected, actual, message = "") expected_dom = HTML::Document.new(expected).root actual_dom = HTML::Document.new(actual).root diff --git a/actionpack/lib/action_dispatch/testing/assertions/response.rb b/actionpack/lib/action_dispatch/testing/assertions/response.rb index 094cfbfc76..b15e0446de 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/response.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/response.rb @@ -1,14 +1,11 @@ -require 'active_support/core_ext/object/inclusion' module ActionDispatch module Assertions # A small suite of assertions that test responses from \Rails applications. module ResponseAssertions - extend ActiveSupport::Concern - # Asserts that the response is one of the following types: # - # * <tt>:success</tt> - Status code was 200 + # * <tt>:success</tt> - Status code was in the 200-299 range # * <tt>:redirect</tt> - Status code was in the 300-399 range # * <tt>:missing</tt> - Status code was 404 # * <tt>:error</tt> - Status code was in the 500-599 range @@ -17,14 +14,11 @@ module ActionDispatch # or its symbolic equivalent <tt>assert_response(:not_implemented)</tt>. # See Rack::Utils::SYMBOL_TO_STATUS_CODE for a full list. # - # ==== Examples - # # # assert that the response was a redirection # assert_response :redirect # # # assert that the response code was status code 401 (unauthorized) # assert_response 401 - # def assert_response(type, message = nil) message ||= "Expected response to be a <#{type}>, but was <#{@response.response_code}>" @@ -33,7 +27,7 @@ module ActionDispatch assert @response.send("#{type}?"), message else code = Rack::Utils::SYMBOL_TO_STATUS_CODE[type] - assert_equal @response.response_code, code, message + assert_equal code, @response.response_code, message end else assert_equal type, @response.response_code, message @@ -44,8 +38,6 @@ module ActionDispatch # This match can be partial, such that <tt>assert_redirected_to(:controller => "weblog")</tt> will also # match the redirection of <tt>redirect_to(:controller => "weblog", :action => "show")</tt> and so on. # - # ==== Examples - # # # assert that the redirection was to the "index" action on the WeblogController # assert_redirected_to :controller => "weblog", :action => "index" # @@ -55,15 +47,17 @@ module ActionDispatch # # assert that the redirection was to the url for @customer # assert_redirected_to @customer # + # # asserts that the redirection matches the regular expression + # assert_redirected_to %r(\Ahttp://example.org) def assert_redirected_to(options = {}, message=nil) assert_response(:redirect, message) - return true if options == @response.location + return true if options === @response.location redirect_is = normalize_argument_to_redirection(@response.location) redirect_expected = normalize_argument_to_redirection(options) message ||= "Expected response to be a redirect to <#{redirect_expected}> but was a redirect to <#{redirect_is}>" - assert_equal redirect_expected, redirect_is, message + assert_operator redirect_expected, :===, redirect_is, message end private @@ -73,17 +67,21 @@ module ActionDispatch end def normalize_argument_to_redirection(fragment) - case fragment - when %r{^\w[A-Za-z\d+.-]*:.*} - fragment - when String - @request.protocol + @request.host_with_port + fragment - when :back - raise RedirectBackError unless refer = @request.headers["Referer"] - refer - else - @controller.url_for(fragment) - end.gsub(/[\r\n]/, '') + normalized = case fragment + when Regexp + fragment + when %r{^\w[A-Za-z\d+.-]*:.*} + fragment + when String + @request.protocol + @request.host_with_port + fragment + when :back + raise RedirectBackError unless refer = @request.headers["Referer"] + refer + else + @controller.url_for(fragment) + end + + normalized.respond_to?(:delete) ? normalized.delete("\0\r\n") : normalized end end end diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb index 1552676fbb..9de545b3c5 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb @@ -26,7 +26,6 @@ module ActionDispatch # # The +message+ parameter allows you to pass in an error message that is displayed upon failure. # - # ==== Examples # # Check the default route (i.e., the index action) # assert_recognizes({:controller => 'items', :action => 'index'}, 'items') # @@ -39,10 +38,9 @@ module ActionDispatch # # Test a custom route # assert_recognizes({:controller => 'items', :action => 'show', :id => '1'}, 'view/item1') def assert_recognizes(expected_options, path, extras={}, message=nil) - request = recognized_request_for(path) + request = recognized_request_for(path, extras) expected_options = expected_options.clone - extras.each_key { |key| expected_options.delete key } unless extras.nil? expected_options.stringify_keys! @@ -58,7 +56,6 @@ module ActionDispatch # # The +defaults+ parameter is unused. # - # ==== Examples # # Asserts that the default action is generated for a route with no action # assert_generates "/items", :controller => "items", :action => "index" # @@ -72,11 +69,9 @@ module ActionDispatch # assert_generates "changesets/12", { :controller => 'scm', :action => 'show_diff', :revision => "12" } def assert_generates(expected_path, options, defaults={}, extras = {}, message=nil) if expected_path =~ %r{://} - begin + fail_on(URI::InvalidURIError) do uri = URI.parse(expected_path) expected_path = uri.path.to_s.empty? ? "/" : uri.path - rescue URI::InvalidURIError => e - raise ActionController::RoutingError, e.message end else expected_path = "/#{expected_path}" unless expected_path.first == '/' @@ -101,7 +96,6 @@ module ActionDispatch # The +extras+ hash allows you to specify options that would normally be provided as a query string to the action. The # +message+ parameter allows you to specify a custom error message to display upon failure. # - # ==== Examples # # Assert a basic route: a controller with the default action (index) # assert_routing '/home', :controller => 'home', :action => 'index' # @@ -133,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 @@ -181,7 +172,7 @@ module ActionDispatch private # Recognizes the route for a given path. - def recognized_request_for(path) + def recognized_request_for(path, extras = {}) if path.is_a?(Hash) method = path[:method] path = path[:path] @@ -193,14 +184,12 @@ module ActionDispatch request = ActionController::TestRequest.new if path =~ %r{://} - begin + fail_on(URI::InvalidURIError) do uri = URI.parse(path) request.env["rack.url_scheme"] = uri.scheme || "http" request.host = uri.host if uri.host request.port = uri.port if uri.port request.path = uri.path.to_s.empty? ? "/" : uri.path - rescue URI::InvalidURIError => e - raise ActionController::RoutingError, e.message end else path = "/#{path}" unless path.first == "/" @@ -209,11 +198,21 @@ module ActionDispatch request.request_method = method if method - params = @routes.recognize_path(path, { :method => method }) + params = fail_on(ActionController::RoutingError) do + @routes.recognize_path(path, { :method => method, :extras => extras }) + end request.path_parameters = params.with_indifferent_access request end + + def fail_on(exception_class) + begin + yield + rescue exception_class => e + raise MiniTest::Assertion, e.message + end + end end end end diff --git a/actionpack/lib/action_dispatch/testing/assertions/selector.rb b/actionpack/lib/action_dispatch/testing/assertions/selector.rb index 33796008bd..9388d44eef 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/selector.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/selector.rb @@ -1,4 +1,4 @@ -require 'action_controller/vendor/html-scanner' +require 'action_view/vendor/html-scanner' require 'active_support/core_ext/object/inclusion' #-- @@ -39,7 +39,6 @@ module ActionDispatch # The selector may be a CSS selector expression (String), an expression # with substitution values (Array) or an HTML::Selector object. # - # ==== Examples # # Selects all div tags # divs = css_select("div") # @@ -58,7 +57,6 @@ module ActionDispatch # inputs = css_select(form, "input") # ... # end - # def css_select(*args) # See assert_select to understand what's going on here. arg = args.shift @@ -269,6 +267,7 @@ module ActionDispatch end end text.strip! unless NO_STRIP.include?(match.name) + text.sub!(/\A\n/, '') if match.name == "textarea" unless match_with.is_a?(Regexp) ? (text =~ match_with) : (text == match_with.to_s) content_mismatch ||= sprintf("<%s> expected but was\n<%s>.", match_with, text) true @@ -339,9 +338,8 @@ module ActionDispatch # The content of each element is un-encoded, and wrapped in the root # element +encoded+. It then calls the block with all un-encoded elements. # - # ==== Examples - # # Selects all bold tags from within the title of an ATOM feed's entries (perhaps to nab a section name prefix) - # assert_select_feed :atom, 1.0 do + # # Selects all bold tags from within the title of an Atom feed's entries (perhaps to nab a section name prefix) + # assert_select "feed[xmlns='http://www.w3.org/2005/Atom']" do # # Select each entry item and then the title item # assert_select "entry>title" do # # Run assertions on the encoded title elements @@ -353,7 +351,7 @@ module ActionDispatch # # # # Selects all paragraph tags from within the description of an RSS feed - # assert_select_feed :rss, 2.0 do + # assert_select "rss[version=2.0]" do # # Select description element of each feed item. # assert_select "channel>item>description" do # # Run assertions on the encoded elements. @@ -400,8 +398,6 @@ module ActionDispatch # You must enable deliveries for this assertion to work, use: # ActionMailer::Base.perform_deliveries = true # - # ==== Examples - # # assert_select_email do # assert_select "h1", "Email alert" # end @@ -412,7 +408,6 @@ module ActionDispatch # # Work with items here... # end # end - # def assert_select_email(&block) deliveries = ActionMailer::Base.deliveries assert !deliveries.empty?, "No e-mail in delivery list" diff --git a/actionpack/lib/action_dispatch/testing/assertions/tag.rb b/actionpack/lib/action_dispatch/testing/assertions/tag.rb index 5c735e61b2..2e38266aba 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/tag.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/tag.rb @@ -1,4 +1,4 @@ -require 'action_controller/vendor/html-scanner' +require 'action_view/vendor/html-scanner' module ActionDispatch module Assertions @@ -48,8 +48,6 @@ module ActionDispatch # * if the condition is +true+, the value must not be +nil+. # * if the condition is +false+ or +nil+, the value must be +nil+. # - # === Examples - # # # Assert that there is a "span" tag # assert_tag :tag => "span" # @@ -104,7 +102,6 @@ module ActionDispatch # Identical to +assert_tag+, but asserts that a matching tag does _not_ # exist. (See +assert_tag+ for a full discussion of the syntax.) # - # === Examples # # Assert that there is not a "div" containing a "p" # assert_no_tag :tag => "div", :descendant => { :tag => "p" } # diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index 08b7ff49c2..a8b27ffafd 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' @@ -17,17 +16,17 @@ module ActionDispatch # a Hash, or a String that is appropriately encoded # (<tt>application/x-www-form-urlencoded</tt> or # <tt>multipart/form-data</tt>). - # - +headers+: Additional HTTP headers to pass, as a Hash. The keys will - # automatically be upcased, with the prefix 'HTTP_' added if needed. + # - +headers+: Additional headers to pass, as a Hash. The headers will be + # merged into the Rack env hash. # - # This method returns an Response object, which one can use to + # This method returns a Response object, which one can use to # inspect the details of the response. Furthermore, if this method was # called from an ActionDispatch::IntegrationTest object, then that # object's <tt>@response</tt> instance variable will point to the same # response object. # - # You can also perform POST, PUT, DELETE, and HEAD requests with +#post+, - # +#put+, +#delete+, and +#head+. + # You can also perform POST, PATCH, PUT, DELETE, and HEAD requests with + # +#post+, +#patch+, +#put+, +#delete+, and +#head+. def get(path, parameters = nil, headers = nil) process :get, path, parameters, headers end @@ -38,6 +37,12 @@ module ActionDispatch process :post, path, parameters, headers end + # Performs a PATCH request with the given parameters. See +#get+ for more + # details. + def patch(path, parameters = nil, headers = nil) + process :patch, path, parameters, headers + end + # Performs a PUT request with the given parameters. See +#get+ for more # details. def put(path, parameters = nil, headers = nil) @@ -56,13 +61,18 @@ module ActionDispatch process :head, path, parameters, headers end + # Performs a OPTIONS request with the given parameters. See +#get+ for + # more details. + def options(path, parameters = nil, headers = nil) + process :options, path, parameters, headers + end + # Performs an XMLHttpRequest request with the given parameters, mirroring # a request from the Prototype library. # - # The request_method is +:get+, +:post+, +:put+, +:delete+ or +:head+; the - # parameters are +nil+, a hash, or a url-encoded or multipart string; - # the headers are a hash. Keys are automatically upcased and prefixed - # with 'HTTP_' if not already. + # The request_method is +:get+, +:post+, +:patch+, +:put+, +:delete+ or + # +:head+; the parameters are +nil+, a hash, or a url-encoded or multipart + # string; the headers are a hash. def xml_http_request(request_method, path, parameters = nil, headers = nil) headers ||= {} headers['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest' @@ -102,6 +112,12 @@ module ActionDispatch request_via_redirect(:post, path, parameters, headers) end + # Performs a PATCH request, following any subsequent redirect. + # See +request_via_redirect+ for more information. + def patch_via_redirect(path, parameters = nil, headers = nil) + request_via_redirect(:patch, path, parameters, headers) + end + # Performs a PUT request, following any subsequent redirect. # See +request_via_redirect+ for more information. def put_via_redirect(path, parameters = nil, headers = nil) @@ -176,16 +192,26 @@ 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! end - remove_method :default_url_options - def default_url_options - { :host => host, :protocol => https? ? "https" : "http" } + def url_options + @url_options ||= default_url_options.dup.tap do |url_options| + url_options.reverse_merge!(controller.url_options) if controller + + if @app.respond_to?(:routes) && @app.routes.respond_to?(:default_url_options) + url_options.reverse_merge!(@app.routes.default_url_options) + end + + url_options.reverse_merge!(:host => host, :protocol => https? ? "https" : "http") + end end # Resets the instance. This can be used to reset the state information @@ -198,6 +224,7 @@ module ActionDispatch @controller = @request = @response = nil @_mock_session = nil @request_count = 0 + @url_options = nil self.host = DEFAULT_HOST self.remote_addr = "127.0.0.1" @@ -292,6 +319,7 @@ module ActionDispatch response = _mock_session.last_response @response = ActionDispatch::TestResponse.new(response.status, response.headers, response.body) @html_document = nil + @url_options = nil @controller = session.last_request.env['action_controller.instance'] @@ -312,12 +340,12 @@ module ActionDispatch @integration_session = Integration::Session.new(app) end - %w(get post put head delete cookies assigns + %w(get post patch put head delete options cookies assigns xml_http_request xhr get_via_redirect post_via_redirect).each do |method| define_method(method) do |*args| reset! unless integration_session # reset the html_document variable, 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 @@ -349,12 +377,14 @@ module ActionDispatch end end - extend ActiveSupport::Concern - include ActionDispatch::Routing::UrlFor + def default_url_options + reset! unless integration_session + integration_session.default_url_options + end - def url_options + def default_url_options=(options) reset! unless integration_session - integration_session.url_options + integration_session.default_url_options = options end def respond_to?(method, include_private = false) @@ -458,6 +488,7 @@ module ActionDispatch class IntegrationTest < ActiveSupport::TestCase include Integration::Runner include ActionController::TemplateAssertions + include ActionDispatch::Routing::UrlFor @@app = nil @@ -477,5 +508,10 @@ module ActionDispatch def app super || self.class.app end + + def url_options + reset! unless integration_session + integration_session.url_options + end end end diff --git a/actionpack/lib/action_dispatch/testing/test_process.rb b/actionpack/lib/action_dispatch/testing/test_process.rb index b08ff41950..3a6d081721 100644 --- a/actionpack/lib/action_dispatch/testing/test_process.rb +++ b/actionpack/lib/action_dispatch/testing/test_process.rb @@ -5,7 +5,8 @@ require 'active_support/core_ext/hash/indifferent_access' module ActionDispatch module TestProcess def assigns(key = nil) - assigns = @controller.view_assigns.with_indifferent_access + assigns = {}.with_indifferent_access + @controller.view_assigns.each {|k, v| assigns.regular_writer(k, v)} key.nil? ? assigns : assigns[key] end diff --git a/actionpack/lib/action_dispatch/testing/test_request.rb b/actionpack/lib/action_dispatch/testing/test_request.rb index 7280e9a93b..c63778f870 100644 --- a/actionpack/lib/action_dispatch/testing/test_request.rb +++ b/actionpack/lib/action_dispatch/testing/test_request.rb @@ -1,6 +1,4 @@ -require 'active_support/core_ext/object/blank' require 'active_support/core_ext/hash/indifferent_access' -require 'active_support/core_ext/hash/reverse_merge' require 'rack/utils' module ActionDispatch @@ -12,8 +10,8 @@ module ActionDispatch end def initialize(env = {}) - env = Rails.application.env_config.merge(env) if defined?(Rails.application) - super(DEFAULT_ENV.merge(env)) + env = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application + super(default_env.merge(env)) self.host = 'test.host' self.remote_addr = '0.0.0.0' @@ -70,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 349a3fcc6e..091b0d8cd2 100644 --- a/actionpack/lib/action_view.rb +++ b/actionpack/lib/action_view.rb @@ -21,9 +21,8 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #++ -require 'active_support/ruby/shim' -require 'active_support/core_ext/class/attribute_accessors' - +require 'active_support' +require 'active_support/rails' require 'action_pack' module ActionView @@ -34,11 +33,13 @@ module ActionView autoload :Base autoload :Context autoload :CompiledTemplates, "action_view/context" + autoload :Digestor autoload :Helpers autoload :LookupContext autoload :PathSet + autoload :RecordIdentifier + autoload :RoutingUrlFor autoload :Template - autoload :TestCase autoload_under "renderer" do autoload :Renderer @@ -70,15 +71,24 @@ module ActionView autoload :MissingTemplate autoload :ActionViewError autoload :EncodingError + autoload :MissingRequestError autoload :TemplateError autoload :WrongEncodingError end end + autoload :TestCase + ENCODING_FLAG = '#.*coding[:=]\s*(\S+)[ \t]*' + + def self.eager_load! + super + ActionView::Template.eager_load! + end end -require 'active_support/i18n' require 'active_support/core_ext/string/output_safety' -I18n.load_path << "#{File.dirname(__FILE__)}/action_view/locale/en.yml" +ActiveSupport.on_load(:i18n) do + I18n.load_path << "#{File.dirname(__FILE__)}/action_view/locale/en.yml" +end diff --git a/actionpack/lib/action_view/asset_paths.rb b/actionpack/lib/action_view/asset_paths.rb index 2a28e780bf..4bbb31b3ee 100644 --- a/actionpack/lib/action_view/asset_paths.rb +++ b/actionpack/lib/action_view/asset_paths.rb @@ -1,10 +1,9 @@ require 'zlib' require 'active_support/core_ext/file' -require 'action_controller/metal/exceptions' module ActionView class AssetPaths #:nodoc: - URI_REGEXP = %r{^[-a-z]+://|^cid:|^//} + URI_REGEXP = %r{^[-a-z]+://|^(?:cid|data):|^//} attr_reader :config, :controller @@ -35,7 +34,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) @@ -92,7 +97,7 @@ module ActionView end def invalid_asset_host!(help_message) - raise ActionController::RoutingError, "This asset host cannot be computed without a request in scope. #{help_message}" + raise ActionView::MissingRequestError, "This asset host cannot be computed without a request in scope. #{help_message}" end # Pick an asset host for this source. Returns +nil+ if no host is set, @@ -117,7 +122,7 @@ module ActionView end def relative_url_root - config.relative_url_root + config.relative_url_root || current_request.try(:script_name) end def asset_host_config diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb index 23329d7f35..3464ec523e 100644 --- a/actionpack/lib/action_view/base.rb +++ b/actionpack/lib/action_view/base.rb @@ -1,6 +1,5 @@ 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' @@ -139,9 +138,17 @@ module ActionView #:nodoc: # How to complete the streaming when an exception occurs. # This is our best guess: first try to close the attribute, then the tag. cattr_accessor :streaming_completion_on_exception - @@streaming_completion_on_exception = %("><script type="text/javascript">window.location = "/500.html"</script></html>) + @@streaming_completion_on_exception = %("><script>window.location = "/500.html"</script></html>) + + # Specify whether rendering within namespaced controllers should prefix + # the partial paths for ActiveModel objects with the namespace. + # (e.g., an Admin::PostsController would render @post using /admin/posts/_post.erb) + cattr_accessor :prefix_partial_path_with_controller_namespace + @@prefix_partial_path_with_controller_namespace = true + + # Specify default_formats that can be rendered. + cattr_accessor :default_formats - class_attribute :helpers class_attribute :_routes class_attribute :logger @@ -159,22 +166,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 @@ -190,11 +181,9 @@ module ActionView #:nodoc: def initialize(context = nil, assigns = {}, controller = nil, formats = nil) #:nodoc: @_config = ActiveSupport::InheritableOptions.new - # Handle all these for backwards compatibility. - # TODO Provide a new API for AV::Base and deprecate this one. if context.is_a?(ActionView::Renderer) @view_renderer = context - elsif + else lookup_context = context.is_a?(ActionView::LookupContext) ? context : ActionView::LookupContext.new(context) lookup_context.formats = formats if formats diff --git a/actionpack/lib/action_view/context.rb b/actionpack/lib/action_view/context.rb index 083856b2ca..ee263df484 100644 --- a/actionpack/lib/action_view/context.rb +++ b/actionpack/lib/action_view/context.rb @@ -5,7 +5,7 @@ module ActionView # = Action View Context # - # Action View contexts are supplied to Action Controller to render template. + # Action View contexts are supplied to Action Controller to render a template. # The default Action View context is ActionView::Base. # # In order to work with ActionController, a Context must just include this module. @@ -25,12 +25,12 @@ module ActionView end # 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. + # returns the correct buffer on +yield+. This is usually + # 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/digestor.rb b/actionpack/lib/action_view/digestor.rb new file mode 100644 index 0000000000..5d3add4091 --- /dev/null +++ b/actionpack/lib/action_view/digestor.rb @@ -0,0 +1,104 @@ +module ActionView + class Digestor + EXPLICIT_DEPENDENCY = /# Template Dependency: ([^ ]+)/ + + # Matches: + # render partial: "comments/comment", collection: commentable.comments + # render "comments/comments" + # render 'comments/comments' + # render('comments/comments') + # + # render(@topic) => render("topics/topic") + # render(topics) => render("topics/topic") + # render(message.topics) => render("topics/topic") + RENDER_DEPENDENCY = / + render\s* # render, followed by optional whitespace + \(? # start an optional parenthesis for the render call + (partial:|:partial\s+=>)?\s* # naming the partial, used with collection -- 1st capture + ([@a-z"'][@a-z_\/\."']+) # the template name itself -- 2nd capture + /x + + cattr_reader(:cache) + @@cache = Hash.new + + def self.digest(name, format, finder, options = {}) + cache["#{name}.#{format}"] ||= new(name, format, finder, options).digest + end + + attr_reader :name, :format, :finder, :options + + def initialize(name, format, finder, options = {}) + @name, @format, @finder, @options = name, format, finder, options + end + + def digest + Digest::MD5.hexdigest("#{source}-#{dependency_digest}").tap do |digest| + logger.try :info, "Cache digest for #{name}.#{format}: #{digest}" + end + rescue ActionView::MissingTemplate + logger.try :error, "Couldn't find template for digesting: #{name}.#{format}" + '' + end + + def dependencies + render_dependencies + explicit_dependencies + rescue ActionView::MissingTemplate + [] # File doesn't exist, so no dependencies + end + + def nested_dependencies + dependencies.collect do |dependency| + dependencies = Digestor.new(dependency, format, finder, partial: true).nested_dependencies + dependencies.any? ? { dependency => dependencies } : dependency + end + end + + private + + def logger + ActionView::Base.logger + end + + def logical_name + name.gsub(%r|/_|, "/") + end + + def directory + name.split("/").first + end + + def partial? + options[:partial] || name.include?("/_") + end + + def source + @source ||= finder.find(logical_name, [], partial?, formats: [ format ]).source + end + + def dependency_digest + dependencies.collect do |template_name| + Digestor.digest(template_name, format, finder, partial: true) + end.join("-") + end + + def render_dependencies + source.scan(RENDER_DEPENDENCY). + collect(&:second).uniq. + + # render(@topic) => render("topics/topic") + # render(topics) => render("topics/topic") + # render(message.topics) => render("topics/topic") + collect { |name| name.sub(/\A@?([a-z]+\.)*([a-z_]+)\z/) { "#{$2.pluralize}/#{$2.singularize}" } }. + + # render("headline") => render("message/headline") + collect { |name| name.include?("/") ? name : "#{directory}/#{name}" }. + + # replace quotes from string renders + collect { |name| name.gsub(/["']/, "") } + end + + def explicit_dependencies + source.scan(EXPLICIT_DEPENDENCY).flatten.uniq + end + end +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 c035dde51e..db4da6f9c8 100644 --- a/actionpack/lib/action_view/helpers/asset_tag_helper.rb +++ b/actionpack/lib/action_view/helpers/asset_tag_helper.rb @@ -13,27 +13,29 @@ module ActionView # the assets exist before linking to them: # # image_tag("rails.png") - # # => <img alt="Rails" src="/images/rails.png?1230601161" /> + # # => <img alt="Rails" src="/assets/rails.png" /> # stylesheet_link_tag("application") - # # => <link href="/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" type="text/css" /> + # # => <link href="/assets/application.css?body=1" media="screen" rel="stylesheet" /> + # # # === Using asset hosts # # By default, Rails links to these assets on the current host in the public # folder, but you can direct Rails to link to assets from a dedicated asset - # server by setting ActionController::Base.asset_host in the application + # server by setting <tt>ActionController::Base.asset_host</tt> in the application # configuration, typically in <tt>config/environments/production.rb</tt>. # For example, you'd define <tt>assets.example.com</tt> to be your asset - # host this way: + # host this way, inside the <tt>configure</tt> block of your environment-specific + # configuration files or <tt>config/application.rb</tt>: # - # ActionController::Base.asset_host = "assets.example.com" + # config.action_controller.asset_host = "assets.example.com" # # Helpers take that into account: # # image_tag("rails.png") - # # => <img alt="Rails" src="http://assets.example.com/images/rails.png?1230601161" /> + # # => <img alt="Rails" src="http://assets.example.com/assets/rails.png" /> # stylesheet_link_tag("application") - # # => <link href="http://assets.example.com/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" type="text/css" /> + # # => <link href="http://assets.example.com/assets/application.css" media="screen" rel="stylesheet" /> # # Browsers typically open at most two simultaneous connections to a single # host, which means your assets often have to wait for other assets to finish @@ -44,9 +46,9 @@ module ActionView # will open eight simultaneous connections rather than two. # # image_tag("rails.png") - # # => <img alt="Rails" src="http://assets0.example.com/images/rails.png?1230601161" /> + # # => <img alt="Rails" src="http://assets0.example.com/assets/rails.png" /> # stylesheet_link_tag("application") - # # => <link href="http://assets2.example.com/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" type="text/css" /> + # # => <link href="http://assets2.example.com/assets/application.css" media="screen" rel="stylesheet" /> # # To do this, you can either setup four actual hosts, or you can use wildcard # DNS to CNAME the wildcard to a single asset host. You can read more about @@ -63,29 +65,28 @@ module ActionView # "http://assets#{Digest::MD5.hexdigest(source).to_i(16) % 2 + 1}.example.com" # } # image_tag("rails.png") - # # => <img alt="Rails" src="http://assets1.example.com/images/rails.png?1230601161" /> + # # => <img alt="Rails" src="http://assets1.example.com/assets/rails.png" /> # stylesheet_link_tag("application") - # # => <link href="http://assets2.example.com/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" type="text/css" /> + # # => <link href="http://assets2.example.com/assets/application.css" media="screen" rel="stylesheet" /> # # The example above generates "http://assets1.example.com" and # "http://assets2.example.com". This option is useful for example if # you need fewer/more than four hosts, custom host names, etc. # # As you see the proc takes a +source+ parameter. That's a string with the - # absolute path of the asset with any extensions and timestamps in place, - # for example "/images/rails.png?1230601161". + # absolute path of the asset, for example "/assets/rails.png". # # ActionController::Base.asset_host = Proc.new { |source| - # if source.starts_with?('/images') - # "http://images.example.com" + # if source.ends_with?('.css') + # "http://stylesheets.example.com" # else # "http://assets.example.com" # end # } # image_tag("rails.png") - # # => <img alt="Rails" src="http://images.example.com/images/rails.png?1230601161" /> + # # => <img alt="Rails" src="http://assets.example.com/assets/rails.png" /> # stylesheet_link_tag("application") - # # => <link href="http://assets.example.com/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" type="text/css" /> + # # => <link href="http://stylesheets.example.com/assets/application.css" media="screen" rel="stylesheet" /> # # Alternatively you may ask for a second parameter +request+. That one is # particularly useful for serving assets from an SSL-protected page. The @@ -94,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 @@ -162,7 +163,7 @@ module ActionView # image_tag("rails.png") # # => <img alt="Rails" src="/release-12345/images/rails.png" /> # stylesheet_link_tag("application") - # # => <link href="/release-12345/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" type="text/css" /> + # # => <link href="/release-12345/stylesheets/application.css?1232285206" media="screen" rel="stylesheet" /> # # Changing the asset_path does require that your web servers have # knowledge of the asset template paths that you rewrite to so it's not @@ -198,7 +199,7 @@ module ActionView include JavascriptTagHelpers include StylesheetTagHelpers # Returns a link tag that browsers and news readers can use to auto-detect - # an RSS or ATOM feed. The +type+ can either be <tt>:rss</tt> (default) or + # an RSS or Atom feed. The +type+ can either be <tt>:rss</tt> (default) or # <tt>:atom</tt>. Control the link options in url_for format using the # +url_options+. You can modify the LINK tag itself in +tag_options+. # @@ -208,19 +209,27 @@ 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 = {}) + if !(type == :rss || type == :atom) && tag_options[:type].blank? + message = "You have passed type other than :rss or :atom to auto_discovery_link_tag and haven't supplied " + + "the :type option key. This behavior is deprecated and will be remove in Rails 4.1. You should pass " + + ":type option explicitly if you want to use other types, for example: " + + "auto_discovery_link_tag(:xml, '/feed.xml', :type => 'application/xml')" + ActiveSupport::Deprecation.warn message + end + tag( "link", "rel" => tag_options[:rel] || "alternate", @@ -251,7 +260,6 @@ module ActionView # The following call would generate such a tag: # # <%= favicon_link_tag 'mb-icon.png', :rel => 'apple-touch-icon', :type => 'image/png' %> - # def favicon_link_tag(source='favicon.ico', options={}) tag('link', { :rel => 'shortcut icon', @@ -260,13 +268,13 @@ module ActionView }.merge(options.symbolize_keys)) end - # Computes the path to an image asset in the public images directory. + # Computes the path to an image asset. # Full paths from the document root will be passed through. # Used internally by +image_tag+ to build the image path: # - # image_path("edit") # => "/images/edit" - # image_path("edit.png") # => "/images/edit.png" - # image_path("icons/edit.png") # => "/images/icons/edit.png" + # image_path("edit") # => "/assets/edit" + # image_path("edit.png") # => "/assets/edit.png" + # image_path("icons/edit.png") # => "/assets/icons/edit.png" # image_path("/icons/edit.png") # => "/icons/edit.png" # image_path("http://www.example.com/img/edit.png") # => "http://www.example.com/img/edit.png" # @@ -274,11 +282,11 @@ module ActionView # The alias +path_to_image+ is provided to avoid that. Rails uses the alias internally, and # plugin authors are encouraged to do so. def image_path(source) - asset_paths.compute_public_path(source, 'images') + source.present? ? asset_paths.compute_public_path(source, 'images') : "" end alias_method :path_to_image, :image_path # aliased to avoid conflicts with an image_path named route - # Computes the full URL to an image asset in the public images directory. + # Computes the full URL to an image asset. # This will use +image_path+ internally, so most of their behaviors will be the same. def image_url(source) URI.join(current_host, path_to_image(source)).to_s @@ -289,7 +297,6 @@ module ActionView # Full paths from the document root will be passed through. # Used internally by +video_tag+ to build the video path. # - # ==== Examples # video_path("hd") # => /videos/hd # video_path("hd.avi") # => /videos/hd.avi # video_path("trailers/hd.avi") # => /videos/trailers/hd.avi @@ -311,7 +318,6 @@ module ActionView # Full paths from the document root will be passed through. # Used internally by +audio_tag+ to build the audio path. # - # ==== Examples # audio_path("horse") # => /audios/horse # audio_path("horse.wav") # => /audios/horse.wav # audio_path("sounds/horse.wav") # => /audios/sounds/horse.wav @@ -322,20 +328,19 @@ module ActionView end alias_method :path_to_audio, :audio_path # aliased to avoid conflicts with an audio_path named route - # Computes the full URL to a audio asset in the public audios directory. + # Computes the full URL to an audio asset in the public audios directory. # This will use +audio_path+ internally, so most of their behaviors will be the same. def audio_url(source) URI.join(current_host, path_to_audio(source)).to_s end alias_method :url_to_audio, :audio_url # aliased to avoid conflicts with an audio_url named route - # Computes the path to a font asset in the public fonts directory. + # Computes the path to a font asset. # Full paths from the document root will be passed through. # - # ==== Examples - # font_path("font") # => /fonts/font - # font_path("font.ttf") # => /fonts/font.ttf - # font_path("dir/font.ttf") # => /fonts/dir/font.ttf + # font_path("font") # => /assets/font + # font_path("font.ttf") # => /assets/font.ttf + # font_path("dir/font.ttf") # => /assets/dir/font.ttf # font_path("/dir/font.ttf") # => /dir/font.ttf # font_path("http://www.example.com/dir/font.ttf") # => http://www.example.com/dir/font.ttf def font_path(source) @@ -343,7 +348,7 @@ module ActionView end alias_method :path_to_font, :font_path # aliased to avoid conflicts with an font_path named route - # Computes the full URL to a font asset in the public fonts directory. + # Computes the full URL to a font asset. # This will use +font_path+ internally, so most of their behaviors will be the same. def font_url(source) URI.join(current_host, path_to_font(source)).to_s @@ -351,7 +356,7 @@ module ActionView alias_method :url_to_font, :font_url # aliased to avoid conflicts with an font_url named route # Returns an html image tag for the +source+. The +source+ can be a full - # path or a file that exists in your public images directory. + # path or a file. # # ==== Options # You can add HTML attributes using the +options+. The +options+ supports @@ -362,33 +367,25 @@ module ActionView # * <tt>:size</tt> - Supplied as "{Width}x{Height}", so "30x45" becomes # width="30" and height="45". <tt>:size</tt> will be ignored if the # value is not in the correct format. - # * <tt>:mouseover</tt> - Set an alternate image to be used when the onmouseover - # event is fired, and sets the original image to be replaced onmouseout. - # This can be used to implement an easy image toggle that fires on onmouseover. # - # ==== Examples - # image_tag("icon") # => - # <img src="/images/icon" alt="Icon" /> - # image_tag("icon.png") # => - # <img src="/images/icon.png" alt="Icon" /> - # image_tag("icon.png", :size => "16x10", :alt => "Edit Entry") # => - # <img src="/images/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("mouse.png", :mouseover => "/images/mouse_over.png") # => - # <img src="/images/mouse.png" onmouseover="this.src='/images/mouse_over.png'" onmouseout="this.src='/images/mouse.png'" alt="Mouse" /> - # image_tag("mouse.png", :mouseover => image_path("mouse_over.png")) # => - # <img src="/images/mouse.png" onmouseover="this.src='/images/mouse_over.png'" onmouseout="this.src='/images/mouse.png'" alt="Mouse" /> + # 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.dup.symbolize_keys! + options = options.symbolize_keys src = options[:src] = path_to_image(source) - unless src =~ /^cid:/ + unless src =~ /^(?:cid|data):/ || src.blank? options[:alt] = options.fetch(:alt){ image_alt(src) } end @@ -396,11 +393,6 @@ module ActionView options[:width], options[:height] = size.split("x") if size =~ %r{^\d+x\d+$} end - if mouseover = options.delete(:mouseover) - options[:onmouseover] = "this.src='#{path_to_image(mouseover)}'" - options[:onmouseout] = "this.src='#{src}'" - end - tag("img", options) end @@ -424,25 +416,24 @@ module ActionView # width="30" and height="45". <tt>:size</tt> will be ignored if the # value is not in the correct format. # - # ==== Examples - # 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="/images/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] @@ -457,15 +448,14 @@ module ActionView # The +source+ can be full path or file that exists in # your public audios directory. # - # ==== Examples - # audio_tag("sound") # => - # <audio src="/audios/sound" /> - # audio_tag("sound.wav") # => - # <audio src="/audios/sound.wav" /> - # audio_tag("sound.wav", :autoplay => true, :controls => true) # => - # <audio autoplay="autoplay" controls="controls" src="/audios/sound.wav" /> - # audio_tag("sound.wav", "sound.mid") # => - # <audio><source src="/audios/sound.wav" /><source src="/audios/sound.mid" /></audio> + # audio_tag("sound") # => + # <audio src="/audios/sound" /> + # audio_tag("sound.wav") # => + # <audio src="/audios/sound.wav" /> + # audio_tag("sound.wav", :autoplay => true, :controls => true) # => + # <audio autoplay="autoplay" controls="controls" src="/audios/sound.wav" /> + # audio_tag("sound.wav", "sound.mid") # => + # <audio><source src="/audios/sound.wav" /><source src="/audios/sound.mid" /></audio> def audio_tag(*sources) multiple_sources_tag('audio', sources) end @@ -477,7 +467,7 @@ module ActionView end def multiple_sources_tag(type, sources) - options = sources.extract_options!.dup.symbolize_keys! + options = sources.extract_options!.symbolize_keys sources.flatten! yield options if block_given? 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/asset_paths.rb b/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_paths.rb index dd4e9ae4cc..35f91cec18 100644 --- a/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_paths.rb +++ b/actionpack/lib/action_view/helpers/asset_tag_helpers/asset_paths.rb @@ -1,5 +1,6 @@ require 'thread' require 'active_support/core_ext/file' +require 'active_support/core_ext/module/attribute_accessors' module ActionView module Helpers 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 c67f81dcf4..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 @@ -16,7 +15,7 @@ module ActionView end def asset_tag(source, options) - content_tag("script", "", { "type" => Mime::JS, "src" => path_to_asset(source) }.merge(options)) + content_tag("script", "", { "src" => path_to_asset(source) }.merge(options)) end def custom_dir @@ -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 @@ -60,9 +60,9 @@ module ActionView # ActionView::Helpers::AssetTagHelper.register_javascript_expansion :monkey => ["head", "body", "tail"] # # javascript_include_tag :monkey # => - # <script type="text/javascript" src="/javascripts/head.js"></script> - # <script type="text/javascript" src="/javascripts/body.js"></script> - # <script type="text/javascript" src="/javascripts/tail.js"></script> + # <script src="/javascripts/head.js"></script> + # <script src="/javascripts/body.js"></script> + # <script src="/javascripts/tail.js"></script> def register_javascript_expansion(expansions) js_expansions = JavascriptIncludeTag.expansions expansions.each do |key, values| @@ -76,7 +76,6 @@ module ActionView # Full paths from the document root will be passed through. # Used internally by javascript_include_tag to build the script path. # - # ==== Examples # javascript_path "xmlhr" # => /javascripts/xmlhr.js # javascript_path "dir/xmlhr.js" # => /javascripts/dir/xmlhr.js # javascript_path "/dir/xmlhr" # => /dir/xmlhr.js @@ -108,44 +107,43 @@ 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. # - # ==== Examples # javascript_include_tag "xmlhr" - # # => <script type="text/javascript" src="/javascripts/xmlhr.js?1284139606"></script> + # # => <script src="/javascripts/xmlhr.js?1284139606"></script> # # javascript_include_tag "xmlhr.js" - # # => <script type="text/javascript" src="/javascripts/xmlhr.js?1284139606"></script> + # # => <script src="/javascripts/xmlhr.js?1284139606"></script> # # javascript_include_tag "common.javascript", "/elsewhere/cools" - # # => <script type="text/javascript" src="/javascripts/common.javascript?1284139606"></script> - # # <script type="text/javascript" src="/elsewhere/cools.js?1423139606"></script> + # # => <script src="/javascripts/common.javascript?1284139606"></script> + # # <script src="/elsewhere/cools.js?1423139606"></script> # # javascript_include_tag "http://www.example.com/xmlhr" - # # => <script type="text/javascript" src="http://www.example.com/xmlhr"></script> + # # => <script src="http://www.example.com/xmlhr"></script> # # javascript_include_tag "http://www.example.com/xmlhr.js" - # # => <script type="text/javascript" src="http://www.example.com/xmlhr.js"></script> + # # => <script src="http://www.example.com/xmlhr.js"></script> # # javascript_include_tag :defaults - # # => <script type="text/javascript" src="/javascripts/jquery.js?1284139606"></script> - # # <script type="text/javascript" src="/javascripts/rails.js?1284139606"></script> - # # <script type="text/javascript" src="/javascripts/application.js?1284139606"></script> + # # => <script src="/javascripts/jquery.js?1284139606"></script> + # # <script src="/javascripts/rails.js?1284139606"></script> + # # <script src="/javascripts/application.js?1284139606"></script> # - # * = The application.js file is only referenced if it exists + # 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 type="text/javascript" src="/javascripts/jquery.js?1284139606"></script> - # # <script type="text/javascript" src="/javascripts/rails.js?1284139606"></script> - # # <script type="text/javascript" src="/javascripts/application.js?1284139606"></script> - # # <script type="text/javascript" src="/javascripts/shop.js?1284139606"></script> - # # <script type="text/javascript" src="/javascripts/checkout.js?1284139606"></script> + # # => <script src="/javascripts/jquery.js?1284139606"></script> + # # <script src="/javascripts/rails.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,29 +160,27 @@ module ActionView # <tt>config.perform_caching</tt> is set to true (which is the case by default for the Rails # production environment, but not for the development environment). # - # ==== Examples - # # # assuming config.perform_caching is false # javascript_include_tag :all, :cache => true - # # => <script type="text/javascript" src="/javascripts/jquery.js?1284139606"></script> - # # <script type="text/javascript" src="/javascripts/rails.js?1284139606"></script> - # # <script type="text/javascript" src="/javascripts/application.js?1284139606"></script> - # # <script type="text/javascript" src="/javascripts/shop.js?1284139606"></script> - # # <script type="text/javascript" src="/javascripts/checkout.js?1284139606"></script> + # # => <script src="/javascripts/jquery.js?1284139606"></script> + # # <script src="/javascripts/rails.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 - # # => <script type="text/javascript" src="/javascripts/all.js?1344139789"></script> + # # => <script src="/javascripts/all.js?1344139789"></script> # # # assuming config.perform_caching is false # javascript_include_tag "jquery", "cart", "checkout", :cache => "shop" - # # => <script type="text/javascript" src="/javascripts/jquery.js?1284139606"></script> - # # <script type="text/javascript" src="/javascripts/cart.js?1289139157"></script> - # # <script type="text/javascript" src="/javascripts/checkout.js?1299139816"></script> + # # => <script src="/javascripts/jquery.js?1284139606"></script> + # # <script src="/javascripts/cart.js?1289139157"></script> + # # <script src="/javascripts/checkout.js?1299139816"></script> # # # assuming config.perform_caching is true # javascript_include_tag "jquery", "cart", "checkout", :cache => "shop" - # # => <script type="text/javascript" src="/javascripts/shop.js?1299139816"></script> + # # => <script src="/javascripts/shop.js?1299139816"></script> # # The <tt>:recursive</tt> option is also available for caching: # 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 2584b67548..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 @@ -17,7 +16,7 @@ module ActionView def asset_tag(source, options) # We force the :request protocol here to avoid a double-download bug in IE7 and IE8 - tag("link", { "rel" => "stylesheet", "type" => Mime::CSS, "media" => "screen", "href" => path_to_asset(source, :protocol => :request) }.merge(options)) + tag("link", { "rel" => "stylesheet", "media" => "screen", "href" => path_to_asset(source, :protocol => :request) }.merge(options)) end def custom_dir @@ -38,9 +37,9 @@ module ActionView # ActionView::Helpers::AssetTagHelper.register_stylesheet_expansion :monkey => ["head", "body", "tail"] # # stylesheet_link_tag :monkey # => - # <link href="/stylesheets/head.css" media="screen" rel="stylesheet" type="text/css" /> - # <link href="/stylesheets/body.css" media="screen" rel="stylesheet" type="text/css" /> - # <link href="/stylesheets/tail.css" media="screen" rel="stylesheet" type="text/css" /> + # <link href="/stylesheets/head.css" media="screen" rel="stylesheet" /> + # <link href="/stylesheets/body.css" media="screen" rel="stylesheet" /> + # <link href="/stylesheets/tail.css" media="screen" rel="stylesheet" /> def register_stylesheet_expansion(expansions) style_expansions = StylesheetIncludeTag.expansions expansions.each do |key, values| @@ -53,8 +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. - # - # ==== Examples + # # stylesheet_path "style" # => /stylesheets/style.css # stylesheet_path "dir/style.css" # => /stylesheets/dir/style.css # stylesheet_path "/dir/style.css" # => /dir/style.css @@ -79,32 +77,31 @@ module ActionView # to "screen", so you must explicitely set it to "all" for the stylesheet(s) to # apply to all media types. # - # ==== Examples # stylesheet_link_tag "style" # => - # <link href="/stylesheets/style.css" media="screen" rel="stylesheet" type="text/css" /> + # <link href="/stylesheets/style.css" media="screen" rel="stylesheet" /> # # stylesheet_link_tag "style.css" # => - # <link href="/stylesheets/style.css" media="screen" rel="stylesheet" type="text/css" /> + # <link href="/stylesheets/style.css" media="screen" rel="stylesheet" /> # # stylesheet_link_tag "http://www.example.com/style.css" # => - # <link href="http://www.example.com/style.css" media="screen" rel="stylesheet" type="text/css" /> + # <link href="http://www.example.com/style.css" media="screen" rel="stylesheet" /> # # stylesheet_link_tag "style", :media => "all" # => - # <link href="/stylesheets/style.css" media="all" rel="stylesheet" type="text/css" /> + # <link href="/stylesheets/style.css" media="all" rel="stylesheet" /> # # stylesheet_link_tag "style", :media => "print" # => - # <link href="/stylesheets/style.css" media="print" rel="stylesheet" type="text/css" /> + # <link href="/stylesheets/style.css" media="print" rel="stylesheet" /> # # stylesheet_link_tag "random.styles", "/css/stylish" # => - # <link href="/stylesheets/random.styles" media="screen" rel="stylesheet" type="text/css" /> - # <link href="/css/stylish.css" media="screen" rel="stylesheet" type="text/css" /> + # <link href="/stylesheets/random.styles" media="screen" rel="stylesheet" /> + # <link href="/css/stylish.css" media="screen" rel="stylesheet" /> # # You can also include all styles in the stylesheets directory using <tt>:all</tt> as the source: # # stylesheet_link_tag :all # => - # <link href="/stylesheets/style1.css" media="screen" rel="stylesheet" type="text/css" /> - # <link href="/stylesheets/styleB.css" media="screen" rel="stylesheet" type="text/css" /> - # <link href="/stylesheets/styleX2.css" media="screen" rel="stylesheet" type="text/css" /> + # <link href="/stylesheets/style1.css" media="screen" rel="stylesheet" /> + # <link href="/stylesheets/styleB.css" media="screen" rel="stylesheet" /> + # <link href="/stylesheets/styleX2.css" media="screen" rel="stylesheet" /> # # If you want Rails to search in all the subdirectories under stylesheets, you should explicitly set <tt>:recursive</tt>: # @@ -113,26 +110,25 @@ module ActionView # == Caching multiple stylesheets into one # # You can also cache multiple stylesheets into one file, which requires less HTTP connections and can better be - # compressed by gzip (leading to faster transfers). Caching will only happen if config.perform_caching + # compressed by gzip (leading to faster transfers). Caching will only happen if +config.perform_caching+ # is set to true (which is the case by default for the Rails production environment, but not for the development # environment). Examples: # - # ==== Examples # stylesheet_link_tag :all, :cache => true # when config.perform_caching is false => - # <link href="/stylesheets/style1.css" media="screen" rel="stylesheet" type="text/css" /> - # <link href="/stylesheets/styleB.css" media="screen" rel="stylesheet" type="text/css" /> - # <link href="/stylesheets/styleX2.css" media="screen" rel="stylesheet" type="text/css" /> + # <link href="/stylesheets/style1.css" media="screen" rel="stylesheet" /> + # <link href="/stylesheets/styleB.css" media="screen" rel="stylesheet" /> + # <link href="/stylesheets/styleX2.css" media="screen" rel="stylesheet" /> # # stylesheet_link_tag :all, :cache => true # when config.perform_caching is true => - # <link href="/stylesheets/all.css" media="screen" rel="stylesheet" type="text/css" /> + # <link href="/stylesheets/all.css" media="screen" rel="stylesheet" /> # # stylesheet_link_tag "shop", "cart", "checkout", :cache => "payment" # when config.perform_caching is false => - # <link href="/stylesheets/shop.css" media="screen" rel="stylesheet" type="text/css" /> - # <link href="/stylesheets/cart.css" media="screen" rel="stylesheet" type="text/css" /> - # <link href="/stylesheets/checkout.css" media="screen" rel="stylesheet" type="text/css" /> + # <link href="/stylesheets/shop.css" media="screen" rel="stylesheet" /> + # <link href="/stylesheets/cart.css" media="screen" rel="stylesheet" /> + # <link href="/stylesheets/checkout.css" media="screen" rel="stylesheet" /> # # stylesheet_link_tag "shop", "cart", "checkout", :cache => "payment" # when config.perform_caching is true => - # <link href="/stylesheets/payment.css" media="screen" rel="stylesheet" type="text/css" /> + # <link href="/stylesheets/payment.css" media="screen" rel="stylesheet" /> # # The <tt>:recursive</tt> option is also available for caching: # diff --git a/actionpack/lib/action_view/helpers/atom_feed_helper.rb b/actionpack/lib/action_view/helpers/atom_feed_helper.rb index 73824dc1f8..f9aa8d7cee 100644 --- a/actionpack/lib/action_view/helpers/atom_feed_helper.rb +++ b/actionpack/lib/action_view/helpers/atom_feed_helper.rb @@ -176,6 +176,7 @@ module ActionView # * <tt>:updated</tt>: Time of update. Defaults to the updated_at attribute on the record if one such exists. # * <tt>:url</tt>: The URL for this entry. Defaults to the polymorphic_url for the record. # * <tt>:id</tt>: The ID for this entry. Defaults to "tag:#{@view.request.host},#{@feed_options[:schema_date]}:#{record.class}/#{record.id}" + # * <tt>:type</tt>: The TYPE for this entry. Defaults to "text/html". def entry(record, options = {}) @xml.entry do @xml.id(options[:id] || "tag:#{@view.request.host},#{@feed_options[:schema_date]}:#{record.class}/#{record.id}") @@ -188,7 +189,9 @@ module ActionView @xml.updated((options[:updated] || record.updated_at).xmlschema) end - @xml.link(:rel => 'alternate', :type => 'text/html', :href => options[:url] || @view.polymorphic_url(record)) + type = options.fetch(:type, 'text/html') + + @xml.link(:rel => 'alternate', :type => type, :href => options[:url] || @view.polymorphic_url(record)) yield AtomBuilder.new(@xml) end diff --git a/actionpack/lib/action_view/helpers/cache_helper.rb b/actionpack/lib/action_view/helpers/cache_helper.rb index 850dd5f448..59e1015976 100644 --- a/actionpack/lib/action_view/helpers/cache_helper.rb +++ b/actionpack/lib/action_view/helpers/cache_helper.rb @@ -8,32 +8,104 @@ 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 # - # ==== Examples - # If you want to cache a navigation menu, you can do following: + # When using this method, you list the cache dependency as the name of the cache, like so: # - # <% cache do %> - # <%= render :partial => "menu" %> + # <% cache 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> + # views/projects/123-20120806214154/7a1156131a6928cb0026877f8b749ac9 + # ^class ^id ^updated_at ^template tree digest + # + # The cache is thus automatically bumped whenever the project updated_at is touched. + # + # If your template cache depends on multiple sources (try to avoid this to keep things simple), + # you can name all these dependencies as part of an array: + # + # <% cache [ project, current_user ] do %> + # <b>All the topics on this project</b> + # <%= render project.topics %> # <% end %> # - # Static content with embedded ruby content can be cached as - # well: + # This will include both records as part of the cache key and updating either of them will + # expire the cache. + # + # ==== Template digest + # + # The template digest that's added to the cache key is computed by taking an md5 of the + # contents of the entire template file. This ensures that your caches will automatically + # expire when you change the template file. + # + # Note that the md5 is taken of the entire template file, not just what's within the + # cache do/end call. So it's possible that changing something outside of that call will + # still expire the cache. + # + # Additionally, the digestor will automatically look through your template file for + # explicit and implicit dependencies, and include those as part of the digest. + # + # ==== Implicit dependencies # - # <% cache do %> - # Topics: - # <%= render :partial => "topics", :collection => @topic_list %> - # <i>Topics listed alphabetically</i> - # <% end %> + # Most template dependencies can be derived from calls to render in the template itself. + # Here are some examples of render calls that Cache Digests knows how to decode: + # + # render partial: "comments/comment", collection: commentable.comments + # render "comments/comments" + # render 'comments/comments' + # render('comments/comments') + # + # render "header" => render("comments/header") + # + # render(@topic) => render("topics/topic") + # render(topics) => render("topics/topic") + # render(message.topics) => render("topics/topic") + # + # It's not possible to derive all render calls like that, though. Here are a few examples of things that can't be derived: + # + # render group_of_attachments + # render @project.documents.where(published: true).order('created_at') + # + # You will have to rewrite those to the explicit form: + # + # render partial: 'attachments/attachment', collection: group_of_attachments + # render partial: 'documents/document', collection: @project.documents.where(published: true).order('created_at') + # + # === Explicit dependencies + # + # Some times you'll have template dependencies that can't be derived at all. This is typically + # the case when you have template rendering that happens in helpers. Here's an example: + # + # <%= render_sortable_todolists @project.todolists %> + # + # You'll need to use a special comment format to call those out: + # + # <%# Template Dependency: todolists/todolist %> + # <%= render_sortable_todolists @project.todolists %> + # + # The pattern used to match these is /# Template Dependency: ([^ ]+)/, so it's important that you type it out just so. + # You can only declare one template dependency per line. + # + # === External dependencies + # + # If you use a helper method, for example, inside of a cached block and you then update that helper, + # you'll have to bump the cache as well. It doesn't really matter how you do it, but the md5 of the template file + # must change. One recommendation is to simply be explicit in a comment, like: + # + # <%# Helper Dependency Updated: May 6, 2012 at 6pm %> + # <%= some_helper_method(person) %> + # + # Now all you'll have to do is change that timestamp when the helper method changes. def cache(name = {}, options = nil, &block) if controller.perform_caching - safe_concat(fragment_for(name, options, &block)) + safe_concat(fragment_for(fragment_name_with_digest(name), options, &block)) else yield end @@ -59,6 +131,17 @@ module ActionView controller.write_fragment(name, fragment, options) end end + + def fragment_name_with_digest(name) + if @virtual_path + [ + *Array(name.is_a?(Hash) ? controller.url_for(name).split("://").last : name), + Digestor.digest(@virtual_path, formats.last.to_sym, lookup_context) + ] + else + name + end + end end end end diff --git a/actionpack/lib/action_view/helpers/capture_helper.rb b/actionpack/lib/action_view/helpers/capture_helper.rb index 17bbfe2efd..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 @@ -13,7 +12,6 @@ module ActionView # The capture method allows you to extract part of a template into a # variable. You can then use this variable anywhere in your templates or layout. # - # ==== Examples # The capture method can be used in ERB templates... # # <% @greeting = capture do %> @@ -96,7 +94,7 @@ module ActionView # Please login! # # <% content_for :script do %> - # <script type="text/javascript">alert('You are not authorized to view this page!')</script> + # <script>alert('You are not authorized to view this page!')</script> # <% end %> # # Then, in another view, you could to do something like this: @@ -135,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 %> # @@ -149,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 @@ -214,8 +212,8 @@ 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 - self.output_buffer = output_buffer[0,0] + response.stream.write output_buffer + self.output_buffer = output_buffer.respond_to?(:clone_empty) ? output_buffer.clone_empty : output_buffer[0, 0] nil end 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 2d37923825..795440cacc 100644 --- a/actionpack/lib/action_view/helpers/date_helper.rb +++ b/actionpack/lib/action_view/helpers/date_helper.rb @@ -12,14 +12,14 @@ module ActionView # elements. All of the select-type methods share a number of common options that are as follows: # # * <tt>:prefix</tt> - overwrites the default prefix of "date" used for the select names. So specifying "birthday" - # would give birthday[month] instead of date[month] if passed to the <tt>select_month</tt> method. + # would give \birthday[month] instead of \date[month] if passed to the <tt>select_month</tt> method. # * <tt>:include_blank</tt> - set to true if it should be possible to set an empty date. # * <tt>:discard_type</tt> - set to true if you want to discard the type part of the select name. If set to true, # the <tt>select_month</tt> method would use simply "date" (which can be overwritten using <tt>:prefix</tt>) instead - # of "date[month]". + # of \date[month]. module DateHelper # Reports the approximate distance in time between two Time, Date or DateTime objects or integers as seconds. - # Set <tt>include_seconds</tt> to true if you want more detailed approximations when distance < 1 min, 29 secs. + # Pass <tt>:include_seconds => true</tt> if you want more detailed approximations when distance < 1 min, 29 secs. # Distances are reported based on the following table: # # 0 <-> 29 secs # => less than a minute @@ -29,14 +29,15 @@ module ActionView # 89 mins, 30 secs <-> 23 hrs, 59 mins, 29 secs # => about [2..24] hours # 23 hrs, 59 mins, 30 secs <-> 41 hrs, 59 mins, 29 secs # => 1 day # 41 hrs, 59 mins, 30 secs <-> 29 days, 23 hrs, 59 mins, 29 secs # => [2..29] days - # 29 days, 23 hrs, 59 mins, 30 secs <-> 59 days, 23 hrs, 59 mins, 29 secs # => about 1 month + # 29 days, 23 hrs, 59 mins, 30 secs <-> 44 days, 23 hrs, 59 mins, 29 secs # => about 1 month + # 44 days, 23 hrs, 59 mins, 30 secs <-> 59 days, 23 hrs, 59 mins, 29 secs # => about 2 months # 59 days, 23 hrs, 59 mins, 30 secs <-> 1 yr minus 1 sec # => [2..12] months # 1 yr <-> 1 yr, 3 months # => about 1 year # 1 yr, 3 months <-> 1 yr, 9 months # => over 1 year # 1 yr, 9 months <-> 2 yr minus 1 sec # => almost 2 years # 2 yrs <-> max time or date # => (same rules as 1 yr) # - # With <tt>include_seconds</tt> = true and the difference < 1 minute 29 seconds: + # With <tt>:include_seconds => true</tt> and the difference < 1 minute 29 seconds: # 0-4 secs # => less than 5 seconds # 5-9 secs # => less than 10 seconds # 10-19 secs # => less than 20 seconds @@ -46,36 +47,44 @@ module ActionView # # ==== Examples # from_time = Time.now - # distance_of_time_in_words(from_time, from_time + 50.minutes) # => about 1 hour - # distance_of_time_in_words(from_time, 50.minutes.from_now) # => about 1 hour - # distance_of_time_in_words(from_time, from_time + 15.seconds) # => less than a minute - # distance_of_time_in_words(from_time, from_time + 15.seconds, true) # => less than 20 seconds - # distance_of_time_in_words(from_time, 3.years.from_now) # => about 3 years - # distance_of_time_in_words(from_time, from_time + 60.hours) # => 3 days - # distance_of_time_in_words(from_time, from_time + 45.seconds, true) # => less than a minute - # distance_of_time_in_words(from_time, from_time - 45.seconds, true) # => less than a minute - # distance_of_time_in_words(from_time, 76.seconds.from_now) # => 1 minute - # distance_of_time_in_words(from_time, from_time + 1.year + 3.days) # => about 1 year - # distance_of_time_in_words(from_time, from_time + 3.years + 6.months) # => over 3 years + # distance_of_time_in_words(from_time, from_time + 50.minutes) # => about 1 hour + # distance_of_time_in_words(from_time, 50.minutes.from_now) # => about 1 hour + # distance_of_time_in_words(from_time, from_time + 15.seconds) # => less than a minute + # distance_of_time_in_words(from_time, from_time + 15.seconds, :include_seconds => true) # => less than 20 seconds + # distance_of_time_in_words(from_time, 3.years.from_now) # => about 3 years + # distance_of_time_in_words(from_time, from_time + 60.hours) # => 3 days + # distance_of_time_in_words(from_time, from_time + 45.seconds, :include_seconds => true) # => less than a minute + # distance_of_time_in_words(from_time, from_time - 45.seconds, :include_seconds => true) # => less than a minute + # distance_of_time_in_words(from_time, 76.seconds.from_now) # => 1 minute + # distance_of_time_in_words(from_time, from_time + 1.year + 3.days) # => about 1 year + # distance_of_time_in_words(from_time, from_time + 3.years + 6.months) # => over 3 years # distance_of_time_in_words(from_time, from_time + 4.years + 9.days + 30.minutes + 5.seconds) # => about 4 years # # to_time = Time.now + 6.years + 19.days - # distance_of_time_in_words(from_time, to_time, true) # => about 6 years - # distance_of_time_in_words(to_time, from_time, true) # => about 6 years - # distance_of_time_in_words(Time.now, Time.now) # => less than a minute - # - def distance_of_time_in_words(from_time, to_time = 0, include_seconds = false, options = {}) + # distance_of_time_in_words(from_time, to_time, :include_seconds => true) # => about 6 years + # distance_of_time_in_words(to_time, from_time, :include_seconds => true) # => about 6 years + # distance_of_time_in_words(Time.now, Time.now) # => less than a minute + def distance_of_time_in_words(from_time, to_time = 0, include_seconds_or_options = {}, options = {}) + if include_seconds_or_options.is_a?(Hash) + options = include_seconds_or_options + else + ActiveSupport::Deprecation.warn "distance_of_time_in_words and time_ago_in_words now accept :include_seconds " + + "as a part of options hash, not a boolean argument", caller + options[:include_seconds] ||= !!include_seconds_or_options + end + from_time = from_time.to_time if from_time.respond_to?(:to_time) to_time = to_time.to_time if to_time.respond_to?(:to_time) - distance_in_minutes = (((to_time - from_time).abs)/60).round - distance_in_seconds = ((to_time - from_time).abs).round + from_time, to_time = to_time, from_time if from_time > to_time + distance_in_minutes = ((to_time - from_time)/60.0).round + distance_in_seconds = (to_time - from_time).round I18n.with_options :locale => options[:locale], :scope => :'datetime.distance_in_words' do |locale| case distance_in_minutes when 0..1 return distance_in_minutes == 0 ? locale.t(:less_than_x_minutes, :count => 1) : - locale.t(:x_minutes, :count => distance_in_minutes) unless include_seconds + locale.t(:x_minutes, :count => distance_in_minutes) unless options[:include_seconds] case distance_in_seconds when 0..4 then locale.t :less_than_x_seconds, :count => 5 @@ -86,26 +95,35 @@ module ActionView else locale.t :x_minutes, :count => 1 end - when 2..44 then locale.t :x_minutes, :count => distance_in_minutes - when 45..89 then locale.t :about_x_hours, :count => 1 - when 90..1439 then locale.t :about_x_hours, :count => (distance_in_minutes.to_f / 60.0).round - when 1440..2519 then locale.t :x_days, :count => 1 - when 2520..43199 then locale.t :x_days, :count => (distance_in_minutes.to_f / 1440.0).round - when 43200..86399 then locale.t :about_x_months, :count => 1 - when 86400..525599 then locale.t :x_months, :count => (distance_in_minutes.to_f / 43200.0).round + when 2...45 then locale.t :x_minutes, :count => distance_in_minutes + when 45...90 then locale.t :about_x_hours, :count => 1 + # 90 mins up to 24 hours + when 90...1440 then locale.t :about_x_hours, :count => (distance_in_minutes.to_f / 60.0).round + # 24 hours up to 42 hours + when 1440...2520 then locale.t :x_days, :count => 1 + # 42 hours up to 30 days + when 2520...43200 then locale.t :x_days, :count => (distance_in_minutes.to_f / 1440.0).round + # 30 days up to 60 days + when 43200...86400 then locale.t :about_x_months, :count => (distance_in_minutes.to_f / 43200.0).round + # 60 days up to 365 days + when 86400...525600 then locale.t :x_months, :count => (distance_in_minutes.to_f / 43200.0).round else - fyear = from_time.year - fyear += 1 if from_time.month >= 3 - tyear = to_time.year - tyear -= 1 if to_time.month < 3 - leap_years = (fyear > tyear) ? 0 : (fyear..tyear).count{|x| Date.leap?(x)} - minute_offset_for_leap_year = leap_years * 1440 - # Discount the leap year days when calculating year distance. - # e.g. if there are 20 leap year days between 2 dates having the same day - # and month then the based on 365 days calculation - # the distance in years will come out to over 80 years when in written - # english it would read better as about 80 years. - minutes_with_offset = distance_in_minutes - minute_offset_for_leap_year + if from_time.acts_like?(:time) && to_time.acts_like?(:time) + fyear = from_time.year + fyear += 1 if from_time.month >= 3 + tyear = to_time.year + tyear -= 1 if to_time.month < 3 + leap_years = (fyear > tyear) ? 0 : (fyear..tyear).count{|x| Date.leap?(x)} + minute_offset_for_leap_year = leap_years * 1440 + # Discount the leap year days when calculating year distance. + # e.g. if there are 20 leap year days between 2 dates having the same day + # and month then the based on 365 days calculation + # the distance in years will come out to over 80 years when in written + # english it would read better as about 80 years. + minutes_with_offset = distance_in_minutes - minute_offset_for_leap_year + else + minutes_with_offset = distance_in_minutes + end remainder = (minutes_with_offset % 525600) distance_in_years = (minutes_with_offset / 525600) if remainder < 131400 @@ -121,16 +139,22 @@ module ActionView # Like <tt>distance_of_time_in_words</tt>, but where <tt>to_time</tt> is fixed to <tt>Time.now</tt>. # - # ==== Examples - # time_ago_in_words(3.minutes.from_now) # => 3 minutes - # time_ago_in_words(Time.now - 15.hours) # => about 15 hours - # time_ago_in_words(Time.now) # => less than a minute + # time_ago_in_words(3.minutes.from_now) # => 3 minutes + # time_ago_in_words(3.minutes.ago) # => 3 minutes + # time_ago_in_words(Time.now - 15.hours) # => about 15 hours + # time_ago_in_words(Time.now) # => less than a minute + # time_ago_in_words(Time.now, :include_seconds => true) # => less than 5 seconds # # from_time = Time.now - 3.days - 14.minutes - 25.seconds # time_ago_in_words(from_time) # => 3 days # - def time_ago_in_words(from_time, include_seconds = false) - distance_of_time_in_words(from_time, Time.now, include_seconds) + # from_time = (3.days + 14.minutes + 25.seconds).ago + # time_ago_in_words(from_time) # => 3 days + # + # Note that you cannot pass a <tt>Numeric</tt> value to <tt>time_ago_in_words</tt>. + # + def time_ago_in_words(from_time, include_seconds_or_options = {}) + distance_of_time_in_words(from_time, Time.now, include_seconds_or_options) end alias_method :distance_of_time_in_words_to_now, :time_ago_in_words @@ -177,7 +201,6 @@ module ActionView # # NOTE: Discarded selects will default to 1. So if no month select is available, January will be assumed. # - # ==== Examples # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute. # date_select("article", "written_on") # @@ -233,7 +256,6 @@ module ActionView # # If anything is passed in the html_options hash it will be applied to every select tag in the set. # - # ==== Examples # # Creates a time select tag that, when POSTed, will be stored in the article variable in the sunrise attribute. # time_select("article", "sunrise") # @@ -266,7 +288,6 @@ module ActionView # # If anything is passed in the html_options hash it will be applied to every select tag in the set. # - # ==== Examples # # Generates a datetime select that, when POSTed, will be stored in the article variable in the written_on # # attribute. # datetime_select("article", "written_on") @@ -305,7 +326,6 @@ module ActionView # # If anything is passed in the html_options hash it will be applied to every select tag in the set. # - # ==== Examples # my_date_time = Time.now + 4.days # # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today). @@ -342,7 +362,6 @@ module ActionView # select_datetime(my_date_time, :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'}) # select_datetime(my_date_time, :prompt => {:hour => true}) # generic prompt for hours # select_datetime(my_date_time, :prompt => true) # generic prompts for all - # def select_datetime(datetime = Time.current, options = {}, html_options = {}) DateTimeSelector.new(datetime, options, html_options).select_datetime end @@ -354,7 +373,6 @@ module ActionView # # If anything is passed in the html_options hash it will be applied to every select tag in the set. # - # ==== Examples # my_date = Time.now + 6.days # # # Generates a date select that defaults to the date in my_date (six days after today). @@ -383,7 +401,6 @@ module ActionView # select_date(my_date, :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'}) # select_date(my_date, :prompt => {:hour => true}) # generic prompt for hours # select_date(my_date, :prompt => true) # generic prompts for all - # def select_date(date = Date.current, options = {}, html_options = {}) DateTimeSelector.new(date, options, html_options).select_date end @@ -394,7 +411,6 @@ module ActionView # # If anything is passed in the html_options hash it will be applied to every select tag in the set. # - # ==== Examples # my_time = Time.now + 5.days + 7.hours + 3.minutes + 14.seconds # # # Generates a time select that defaults to the time in my_time. @@ -418,11 +434,13 @@ 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 # select_time(my_time, :prompt => true) # generic prompts for all - # def select_time(datetime = Time.current, options = {}, html_options = {}) DateTimeSelector.new(datetime, options, html_options).select_time end @@ -431,7 +449,6 @@ module ActionView # The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer. # Override the field name using the <tt>:field_name</tt> option, 'second' by default. # - # ==== Examples # my_time = Time.now + 16.minutes # # # Generates a select field for seconds that defaults to the seconds for the time in my_time. @@ -447,7 +464,6 @@ module ActionView # # Generates a select field for seconds with a custom prompt. Use <tt>:prompt => true</tt> for a # # generic prompt. # select_second(14, :prompt => 'Choose seconds') - # def select_second(datetime, options = {}, html_options = {}) DateTimeSelector.new(datetime, options, html_options).select_second end @@ -457,7 +473,6 @@ module ActionView # selected. The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer. # Override the field name using the <tt>:field_name</tt> option, 'minute' by default. # - # ==== Examples # my_time = Time.now + 6.hours # # # Generates a select field for minutes that defaults to the minutes for the time in my_time. @@ -473,7 +488,6 @@ module ActionView # # Generates a select field for minutes with a custom prompt. Use <tt>:prompt => true</tt> for a # # generic prompt. # select_minute(14, :prompt => 'Choose minutes') - # def select_minute(datetime, options = {}, html_options = {}) DateTimeSelector.new(datetime, options, html_options).select_minute end @@ -482,7 +496,6 @@ module ActionView # The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer. # Override the field name using the <tt>:field_name</tt> option, 'hour' by default. # - # ==== Examples # my_time = Time.now + 6.hours # # # Generates a select field for hours that defaults to the hour for the time in my_time. @@ -502,6 +515,8 @@ 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 @@ -511,7 +526,6 @@ module ActionView # If you want to display days with a leading zero set the <tt>:use_two_digit_numbers</tt> key in +options+ to true. # Override the field name using the <tt>:field_name</tt> option, 'day' by default. # - # ==== Examples # my_date = Time.now + 2.days # # # Generates a select field for days that defaults to the day for the date in my_date. @@ -530,7 +544,6 @@ module ActionView # # Generates a select field for days with a custom prompt. Use <tt>:prompt => true</tt> for a # # generic prompt. # select_day(5, :prompt => 'Choose day') - # def select_day(date, options = {}, html_options = {}) DateTimeSelector.new(date, options, html_options).select_day end @@ -545,7 +558,6 @@ module ActionView # If you want to display months with a leading zero set the <tt>:use_two_digit_numbers</tt> key in +options+ to true. # Override the field name using the <tt>:field_name</tt> option, 'month' by default. # - # ==== Examples # # Generates a select field for months that defaults to the current month that # # will use keys like "January", "March". # select_month(Date.today) @@ -577,7 +589,6 @@ module ActionView # # Generates a select field for months with a custom prompt. Use <tt>:prompt => true</tt> for a # # generic prompt. # select_month(14, :prompt => 'Choose month') - # def select_month(date, options = {}, html_options = {}) DateTimeSelector.new(date, options, html_options).select_month end @@ -588,7 +599,6 @@ module ActionView # greater than <tt>:end_year</tt>. The <tt>date</tt> can also be substituted for a year given as a number. # Override the field name using the <tt>:field_name</tt> option, 'year' by default. # - # ==== Examples # # Generates a select field for years that defaults to the current year that # # has ascending year values. # select_year(Date.today, :start_year => 1992, :end_year => 2007) @@ -608,14 +618,12 @@ module ActionView # # Generates a select field for years with a custom prompt. Use <tt>:prompt => true</tt> for a # # generic prompt. # select_year(14, :prompt => 'Choose year') - # def select_year(date, options = {}, html_options = {}) DateTimeSelector.new(date, options, html_options).select_year end # Returns an html time tag for the given date or time. # - # ==== Examples # time_tag Date.today # => # <time datetime="2010-11-04">November 04, 2010</time> # time_tag Time.now # => @@ -625,13 +633,17 @@ module ActionView # time_tag Date.today, :pubdate => true # => # <time datetime="2010-11-04" pubdate="pubdate">November 04, 2010</time> # - def time_tag(date_or_time, *args) + # <%= time_tag Time.now do %> + # <span>Right now</span> + # <% end %> + # # => <time datetime="2010-11-04T17:55:45+01:00"><span>Right now</span></time> + def time_tag(date_or_time, *args, &block) options = args.extract_options! format = options.delete(:format) || :long content = args.first || I18n.l(date_or_time, :format => format) datetime = date_or_time.acts_like?(:time) ? date_or_time.xmlschema : date_or_time.rfc3339 - content_tag(:time, content, options.reverse_merge(:datetime => datetime)) + content_tag(:time, content, options.reverse_merge(:datetime => datetime), &block) end end @@ -669,11 +681,7 @@ module ActionView @options[:discard_minute] ||= true if @options[:discard_hour] @options[:discard_second] ||= true unless @options[:include_seconds] && !@options[:discard_minute] - # If the day is hidden and the month is visible, the day should be set to the 1st so all month choices are - # valid (otherwise it could be 31 and February wouldn't be a valid date) - if @datetime && @options[:discard_day] && !@options[:discard_month] - @datetime = @datetime.change(:day => 1) - end + set_day_if_discarded if @options[:tag] && @options[:ignore_date] select_time @@ -696,11 +704,7 @@ module ActionView @options[:discard_month] ||= true unless order.include?(:month) @options[:discard_day] ||= true if @options[:discard_month] || !order.include?(:day) - # If the day is hidden and the month is visible, the day should be set to the 1st so all month choices are - # valid (otherwise it could be 31 and February wouldn't be a valid date) - if @datetime && @options[:discard_day] && !@options[:discard_month] - @datetime = @datetime.change(:day => 1) - end + set_day_if_discarded [:day, :month, :year].each { |o| order.unshift(o) unless order.include?(o) } @@ -743,7 +747,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 @@ -798,7 +806,15 @@ module ActionView private %w( sec min hour day month year ).each do |method| define_method(method) do - @datetime.kind_of?(Fixnum) ? @datetime : @datetime.send(method) if @datetime + @datetime.kind_of?(Numeric) ? @datetime : @datetime.send(method) if @datetime + end + end + + # If the day is hidden, the day should be set to the 1st so all month and year choices are + # valid. Otherwise, February 31st or February 29th, 2011 can be selected, which are invalid. + def set_day_if_discarded + if @datetime && @options[:discard_day] + @datetime = @datetime.change(:day => 1) end end @@ -947,12 +963,15 @@ module ActionView # build_hidden(:year, 2008) # => "<input id="post_written_on_1i" name="post[written_on(1i)]" type="hidden" value="2008" />" def build_hidden(type, value) - (tag(:input, { + select_options = { :type => "hidden", :id => input_id_from_type(type), :name => input_name_from_type(type), :value => value - }.merge(@html_options.slice(:disabled))) + "\n").html_safe + }.merge(@html_options.slice(:disabled)) + select_options.merge!(:disabled => 'disabled') if @options[:disabled] + + tag(:input, select_options) + "\n".html_safe end # Returns the name attribute for the input tag. @@ -972,7 +991,10 @@ module ActionView # Returns the id attribute for the input tag. # => "post_written_on_1i" def input_id_from_type(type) - input_name_from_type(type).gsub(/([\[\(])|(\]\[)/, '_').gsub(/[\]\)]/, '') + id = input_name_from_type(type).gsub(/([\[\(])|(\]\[)/, '_').gsub(/[\]\)]/, '') + id = @options[:namespace] + '_' + id if @options[:namespace] + + id end # Given an ordering of datetime components, create the selection HTML @@ -989,6 +1011,8 @@ module ActionView # Returns the separator for a given datetime component. def separator(type) + return "" if @options[:use_hidden] + case type when :year, :month, :day @options[:"discard_#{type}"] ? "" : @options[:date_separator] diff --git a/actionpack/lib/action_view/helpers/debug_helper.rb b/actionpack/lib/action_view/helpers/debug_helper.rb index c0cc7d347c..d8b92c5cab 100644 --- a/actionpack/lib/action_view/helpers/debug_helper.rb +++ b/actionpack/lib/action_view/helpers/debug_helper.rb @@ -4,12 +4,13 @@ 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. # - # ==== Example - # # @user = User.new({ :username => 'testing', :password => 'xyz', :age => 42}) %> # debug(@user) # # => @@ -25,14 +26,14 @@ module ActionView # # new_record: true # </pre> - def debug(object) begin Marshal::dump(object) - "<pre class='debug_dump'>#{h(object.to_yaml).gsub(" ", " ")}</pre>".html_safe + object = ERB::Util.html_escape(object.to_yaml).gsub(" ", " ").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 bdfef920c5..17fe7dc1b4 100644 --- a/actionpack/lib/action_view/helpers/form_helper.rb +++ b/actionpack/lib/action_view/helpers/form_helper.rb @@ -4,11 +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 'action_view/model_naming' +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/core_ext/string/inflections' module ActionView # = Action View Form Helpers @@ -16,17 +17,28 @@ module ActionView # Form helpers are designed to make working with resources much easier # compared to using vanilla HTML. # - # Forms for models are created with +form_for+. That method yields a form - # builder that knows the model the form is about. The form builder is thus - # able to generate default values for input fields that correspond to model - # attributes, and also convenient names, IDs, endpoints, etc. + # Typically, a form designed to create or update a resource reflects the + # identity of the resource in several ways: (i) the url that the form is + # sent to (the form element's +action+ attribute) should result in a request + # being routed to the appropriate controller action (with the appropriate <tt>:id</tt> + # parameter in the case of an existing resource), (ii) input fields should + # be named in such a way that in the controller their values appear in the + # appropriate places within the +params+ hash, and (iii) for an existing record, + # when the form is initially displayed, input fields corresponding to attributes + # of the resource should show the current values of those attributes. # - # Conventions in the generated field names allow controllers to receive form - # data nicely structured in +params+ with no effort on your side. + # In Rails, this is usually achieved by creating the form using +form_for+ and + # a number of related helper methods. +form_for+ generates an appropriate <tt>form</tt> + # tag and yields a form builder object that knows the model the form is about. + # Input fields are created by calling methods defined on the form builder, which + # means they are able to generate the appropriate names and default values + # corresponding to the model attributes, as well as convenient IDs, etc. + # Conventions in the generated field names allow controllers to receive form data + # nicely structured in +params+ with no effort on your side. # # For example, to create a new person you typically set up a new instance of # +Person+ in the <tt>PeopleController#new</tt> action, <tt>@person</tt>, and - # pass it to +form_for+: + # in the view template pass that object to +form_for+: # # <%= form_for @person do |f| %> # <%= f.label :first_name %>: @@ -45,10 +57,10 @@ module ActionView # <input name="authenticity_token" type="hidden" value="NrOp5bsjoLRuK8IW5+dQEYjKGUJDe7TQoZVvq95Wteg=" /> # </div> # <label for="person_first_name">First name</label>: - # <input id="person_first_name" name="person[first_name]" size="30" type="text" /><br /> + # <input id="person_first_name" name="person[first_name]" type="text" /><br /> # # <label for="person_last_name">Last name</label>: - # <input id="person_last_name" name="person[last_name]" size="30" type="text" /><br /> + # <input id="person_last_name" name="person[last_name]" type="text" /><br /> # # <input name="commit" type="submit" value="Create Person" /> # </form> @@ -76,10 +88,10 @@ module ActionView # <input name="authenticity_token" type="hidden" value="NrOp5bsjoLRuK8IW5+dQEYjKGUJDe7TQoZVvq95Wteg=" /> # </div> # <label for="person_first_name">First name</label>: - # <input id="person_first_name" name="person[first_name]" size="30" type="text" value="John" /><br /> + # <input id="person_first_name" name="person[first_name]" type="text" value="John" /><br /> # # <label for="person_last_name">Last name</label>: - # <input id="person_last_name" name="person[last_name]" size="30" type="text" value="Smith" /><br /> + # <input id="person_last_name" name="person[last_name]" type="text" value="Smith" /><br /> # # <input name="commit" type="submit" value="Update Person" /> # </form> @@ -103,35 +115,16 @@ module ActionView include FormTagHelper include UrlHelper + include 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 - - # Creates a form and a scope around a specific model object that is used - # as a base for questioning about values for the fields. - # - # Rails provides succinct resource-oriented form generation with +form_for+ - # like this: - # - # <%= form_for @offer do |f| %> - # <%= f.label :version, 'Version' %>: - # <%= f.text_field :version %><br /> - # <%= f.label :author, 'Author' %>: - # <%= f.text_field :author %><br /> - # <%= f.submit %> - # <% end %> - # - # There, +form_for+ is able to generate the rest of RESTful form - # parameters based on introspection on the record, but to understand what - # it does we need to dig first into the alternative generic usage it is - # based upon. - # - # === Generic form_for + # Creates a form that allows the user to create or update the attributes + # of a specific model object. # - # The generic way to call +form_for+ yields a form builder around a - # model: + # The method can be used in several slightly different ways, depending on + # how much you wish to rely on Rails to infer automatically from the model + # how the form should be constructed. For a generic model object, a form + # can be created by passing +form_for+ a string or symbol representing + # the object we are concerned with: # # <%= form_for :person do |f| %> # First name: <%= f.text_field :first_name %><br /> @@ -141,24 +134,39 @@ module ActionView # <%= f.submit %> # <% end %> # - # There, the argument is a symbol or string with the name of the - # object the form is about. - # - # The form builder acts as a regular form helper that somehow carries the - # model. Thus, the idea is that + # The variable +f+ yielded to the block is a FormBuilder object that + # incorporates the knowledge about the model object represented by + # <tt>:person</tt> passed to +form_for+. Methods defined on the FormBuilder + # are used to generate fields bound to this model. Thus, for example, # # <%= f.text_field :first_name %> # - # gets expanded to + # will get expanded to # # <%= text_field :person, :first_name %> + # which results in an html <tt><input></tt> tag whose +name+ attribute is + # <tt>person[first_name]</tt>. This means that when the form is submitted, + # the value entered by the user will be available in the controller as + # <tt>params[:person][:first_name]</tt>. + # + # For fields generated in this way using the FormBuilder, + # if <tt>:person</tt> also happens to be the name of an instance variable + # <tt>@person</tt>, the default value of the field shown when the form is + # initially displayed (e.g. in the situation where you are editing an + # existing record) will be the value of the corresponding attribute of + # <tt>@person</tt>. # # The rightmost argument to +form_for+ is an - # optional hash of options: - # - # * <tt>:url</tt> - The URL the form is submitted to. It takes the same - # fields you pass to +url_for+ or +link_to+. In particular you may pass - # here a named route directly as well. Defaults to the current action. + # optional hash of options - + # + # * <tt>:url</tt> - The URL the form is to be submitted to. This may be + # represented in the same way as values passed to +url_for+ or +link_to+. + # So for example you may use a named route directly. When the model is + # represented by a string or symbol, as in the example above, if the + # <tt>:url</tt> option is not specified, by default the form will be + # sent back to the current url (We will describe below an alternative + # resource-oriented usage of +form_for+ in which the URL does not need + # to be specified explicitly). # * <tt>:namespace</tt> - A namespace for your form to ensure uniqueness of # id attributes on form elements. The namespace attribute will be prefixed # with underscore on the generated HTML id. @@ -168,11 +176,11 @@ module ActionView # possible to use both the stand-alone FormHelper methods and methods # from FormTagHelper. For example: # - # <%= form_for @person do |f| %> + # <%= form_for :person do |f| %> # First name: <%= f.text_field :first_name %> # Last name : <%= f.text_field :last_name %> # Biography : <%= text_area :person, :biography %> - # Admin? : <%= check_box_tag "person[admin]", @person.company.admin? %> + # Admin? : <%= check_box_tag "person[admin]", "1", @person.company.admin? %> # <%= f.submit %> # <% end %> # @@ -180,26 +188,65 @@ module ActionView # are designed to work with an object as base, like # FormOptionHelper#collection_select and DateHelper#datetime_select. # - # === Resource-oriented style + # === #form_for with a model object # - # As we said above, in addition to manually configuring the +form_for+ - # call, you can rely on automated resource identification, which will use - # the conventions and named routes of that approach. This is the - # preferred way to use +form_for+ nowadays. + # In the examples above, the object to be created or edited was + # represented by a symbol passed to +form_for+, and we noted that + # a string can also be used equivalently. It is also possible, however, + # to pass a model object itself to +form_for+. For example, if <tt>@post</tt> + # is an existing record you wish to edit, you can create the form using + # + # <%= form_for @post do |f| %> + # ... + # <% end %> # - # For example, if <tt>@post</tt> is an existing record you want to edit + # This behaves in almost the same way as outlined previously, with a + # couple of small exceptions. First, the prefix used to name the input + # elements within the form (hence the key that denotes them in the +params+ + # hash) is actually derived from the object's _class_, e.g. <tt>params[:post]</tt> + # if the object's class is +Post+. However, this can be overwritten using + # the <tt>:as</tt> option, e.g. - + # + # <%= form_for(@person, :as => :client) do |f| %> + # ... + # <% end %> + # + # would result in <tt>params[:client]</tt>. + # + # Secondly, the field values shown when the form is initially displayed + # are taken from the attributes of the object passed to +form_for+, + # regardless of whether the object is an instance + # variable. So, for example, if we had a _local_ variable +post+ + # representing an existing record, + # + # <%= form_for post do |f| %> + # ... + # <% end %> + # + # would produce a form with fields whose initial state reflect the current + # values of the attributes of +post+. + # + # === Resource-oriented style + # + # In the examples just shown, although not indicated explicitly, we still + # need to use the <tt>:url</tt> option in order to specify where the + # form is going to be sent. However, further simplification is possible + # if the record passed to +form_for+ is a _resource_, i.e. it corresponds + # to a set of RESTful routes, e.g. defined using the +resources+ method + # in <tt>config/routes.rb</tt>. In this case Rails will simply infer the + # appropriate URL from the record itself. For example, # # <%= form_for @post do |f| %> # ... # <% end %> # - # is equivalent to something like: + # is then equivalent to something like: # # <%= form_for @post, :as => :post, :url => post_path(@post), :method => :put, :html => { :class => "edit_post", :id => "edit_post_45" } do |f| %> # ... # <% end %> # - # And for new records + # And for a new record # # <%= form_for(Post.new) do |f| %> # ... @@ -211,7 +258,7 @@ module ActionView # ... # <% end %> # - # You can also overwrite the individual conventions, like this: + # However you can still overwrite individual conventions, such as: # # <%= form_for(@post, :url => super_posts_path) do |f| %> # ... @@ -223,13 +270,6 @@ module ActionView # ... # <% end %> # - # If you have an object that needs to be represented as a different - # parameter, like a Person that acts as a Client: - # - # <%= form_for(@person, :as => :client) do |f| %> - # ... - # <% end %> - # # For namespaced routes, like +admin_post_url+: # # <%= form_for([:admin, @post]) do |f| %> @@ -250,11 +290,11 @@ module ActionView # # You can force the form to use the full array of HTTP verbs by setting # - # :method => (:get|:post|:put|:delete) + # :method => (:get|:post|:patch|:put|:delete) # - # in the options hash. If the verb is not GET or POST, which are natively supported by HTML forms, the - # form will be set to POST and a hidden input called _method will carry the intended verb for the server - # to interpret. + # in the options hash. If the verb is not GET or POST, which are natively + # supported by HTML forms, the form will be set to POST and a hidden input + # called _method will carry the intended verb for the server to interpret. # # === Unobtrusive JavaScript # @@ -283,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. @@ -296,7 +354,7 @@ module ActionView # Example: # # <%= form_for(@post) do |f| %> - # <% f.fields_for(:comments, :include_id => false) do |cf| %> + # <%= f.fields_for(:comments, :include_id => false) do |cf| %> # ... # <% end %> # <% end %> @@ -365,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) @@ -385,7 +445,7 @@ module ActionView object = convert_to_model(object) as = options[:as] - action, method = object.respond_to?(:persisted?) && object.persisted? ? [:edit, :put] : [:new, :post] + action, method = object.respond_to?(:persisted?) && object.persisted? ? [:edit, :patch] : [:new, :post] options[:html].reverse_merge!( :class => as ? "#{action}_#{as}" : dom_class(object, action), :id => as ? "#{action}_#{as}" : [options[:namespace], dom_id(object, action)].compact.join("_").presence, @@ -402,30 +462,59 @@ module ActionView # # === Generic Examples # + # Although the usage and purpose of +field_for+ is similar to +form_for+'s, + # its method signature is slightly different. Like +form_for+, it yields + # a FormBuilder object associated with a particular model object to a block, + # and within the block allows methods to be called on the builder to + # generate fields associated with the model object. Fields may reflect + # a model object in two ways - how they are named (hence how submitted + # values appear within the +params+ hash in the controller) and what + # default values are shown when the form the fields appear in is first + # displayed. In order for both of these features to be specified independently, + # both an object name (represented by either a symbol or string) and the + # object itself can be passed to the method separately - + # # <%= form_for @person do |person_form| %> # First name: <%= person_form.text_field :first_name %> # Last name : <%= person_form.text_field :last_name %> # - # <%= fields_for @person.permission do |permission_fields| %> + # <%= fields_for :permission, @person.permission do |permission_fields| %> # Admin? : <%= permission_fields.check_box :admin %> # <% end %> # # <%= f.submit %> # <% end %> # - # ...or if you have an object that needs to be represented as a different - # parameter, like a Client that acts as a Person: + # In this case, the checkbox field will be represented by an HTML +input+ + # tag with the +name+ attribute <tt>permission[admin]</tt>, and the submitted + # value will appear in the controller as <tt>params[:permission][:admin]</tt>. + # If <tt>@person.permission</tt> is an existing record with an attribute + # +admin+, the initial state of the checkbox when first displayed will + # reflect the value of <tt>@person.permission.admin</tt>. # - # <%= fields_for :person, @client do |permission_fields| %> + # Often this can be simplified by passing just the name of the model + # object to +fields_for+ - + # + # <%= fields_for :permission do |permission_fields| %> # Admin?: <%= permission_fields.check_box :admin %> # <% end %> # - # ...or if you don't have an object, just a name of the parameter: + # ...in which case, if <tt>:permission</tt> also happens to be the name of an + # instance variable <tt>@permission</tt>, the initial state of the input + # field will reflect the value of that variable's attribute <tt>@permission.admin</tt>. + # + # Alternatively, you can pass just the model object itself (if the first + # argument isn't a string or symbol +fields_for+ will realize that the + # name has been omitted) - # - # <%= fields_for :person do |permission_fields| %> + # <%= fields_for @person.permission do |permission_fields| %> # Admin?: <%= permission_fields.check_box :admin %> # <% end %> # + # and +fields_for+ will derive the required name of the field from the + # _class_ of the model object, e.g. if <tt>@person.permission</tt>, is + # of class +Permission+, the field will still be named <tt>permission[admin]</tt>. + # # Note: This also works for the methods in FormOptionHelper and # DateHelper that are designed to work with an object as base, like # FormOptionHelper#collection_select and DateHelper#datetime_select. @@ -600,6 +689,19 @@ module ActionView # <% end %> # ... # <% end %> + # + # When a collection is used you might want to know the index of each + # object into the array. For this purpose, the <tt>index</tt> method + # is available in the FormBuilder object. + # + # <%= form_for @person do |person_form| %> + # ... + # <%= person_form.fields_for :projects do |project_fields| %> + # Project #<%= project_fields.index %> + # ... + # <% end %> + # ... + # <% end %> def fields_for(record_name, record_object = nil, options = {}, &block) builder = instantiate_builder(record_name, record_object, options) output = capture(builder, &block) @@ -618,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> @@ -812,11 +914,10 @@ module ActionView # In that case it is preferable to either use +check_box_tag+ or to use # hashes instead of arrays. # - # ==== Examples # # Let's say that @post.validated? is 1: # check_box("post", "validated") # # => <input name="post[validated]" type="hidden" value="0" /> - # # <input type="checkbox" id="post_validated" name="post[validated]" value="1" /> + # # <input checked="checked" type="checkbox" id="post_validated" name="post[validated]" value="1" /> # # # Let's say that @puppy.gooddog is "no": # check_box("puppy", "gooddog", {}, "yes", "no") @@ -838,7 +939,6 @@ module ActionView # To force the radio button to be checked pass <tt>:checked => true</tt> in the # +options+ hash. You may pass HTML options there as well. # - # ==== Examples # # Let's say that @post.category returns "rails": # radio_button("post", "category", "rails") # radio_button("post", "category", "java") @@ -853,28 +953,34 @@ module ActionView Tags::RadioButton.new(object_name, method, self, tag_value, options).render end + # Returns a text_field of type "color". + # + # color_field("car", "color") + # # => <input id="car_color" name="car[color]" type="color" value="#000000" /> + # + def color_field(object_name, method, options = {}) + Tags::ColorField.new(object_name, method, self, options).render + end + # Returns an input of type "search" for accessing a specified attribute (identified by +method+) on an object # assigned to the template (identified by +object_name+). Inputs of type "search" may be styled differently by # some browsers. # - # ==== Examples - # # search_field(:user, :name) - # # => <input id="user_name" name="user[name]" size="30" type="search" /> + # # => <input id="user_name" name="user[name]" type="search" /> # search_field(:user, :name, :autosave => false) - # # => <input autosave="false" id="user_name" name="user[name]" size="30" type="search" /> + # # => <input autosave="false" id="user_name" name="user[name]" type="search" /> # search_field(:user, :name, :results => 3) - # # => <input id="user_name" name="user[name]" results="3" size="30" type="search" /> + # # => <input id="user_name" name="user[name]" results="3" type="search" /> # # Assume request.host returns "www.example.com" # search_field(:user, :name, :autosave => true) - # # => <input autosave="com.example.www" id="user_name" name="user[name]" results="10" size="30" type="search" /> + # # => <input autosave="com.example.www" id="user_name" name="user[name]" results="10" type="search" /> # search_field(:user, :name, :onsearch => true) - # # => <input id="user_name" incremental="true" name="user[name]" onsearch="true" size="30" type="search" /> + # # => <input id="user_name" incremental="true" name="user[name]" onsearch="true" type="search" /> # search_field(:user, :name, :autosave => false, :onsearch => true) - # # => <input autosave="false" id="user_name" incremental="true" name="user[name]" onsearch="true" size="30" type="search" /> + # # => <input autosave="false" id="user_name" incremental="true" name="user[name]" onsearch="true" type="search" /> # search_field(:user, :name, :autosave => true, :onsearch => true) - # # => <input autosave="com.example.www" id="user_name" incremental="true" name="user[name]" onsearch="true" results="10" size="30" type="search" /> - # + # # => <input autosave="com.example.www" id="user_name" incremental="true" name="user[name]" onsearch="true" results="10" type="search" /> def search_field(object_name, method, options = {}) Tags::SearchField.new(object_name, method, self, options).render end @@ -882,17 +988,121 @@ module ActionView # Returns a text_field of type "tel". # # telephone_field("user", "phone") - # # => <input id="user_phone" name="user[phone]" size="30" type="tel" /> + # # => <input id="user_phone" name="user[phone]" type="tel" /> # 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". + # + # date_field("user", "born_on") + # # => <input id="user_born_on" name="user[born_on]" type="date" /> + # + # The default value is generated by trying to call "to_date" + # on the object's value, which makes it behave as expected for instances + # of DateTime and ActiveSupport::TimeWithZone. You can still override that + # by passing the "value" option explicitly, e.g. + # + # @user.born_on = Date.new(1984, 1, 27) + # date_field("user", "born_on", value: "1984-05-12") + # # => <input id="user_born_on" name="user[born_on]" type="date" value="1984-05-12" /> + # + def date_field(object_name, method, options = {}) + Tags::DateField.new(object_name, method, self, options).render + end + + # Returns a text_field of type "time". + # + # The default value is generated by trying to call +strftime+ with "%T.%L" + # on the objects's value. It is still possible to override that + # by passing the "value" option. + # + # === Options + # * Accepts same options as time_field_tag + # + # === Example + # time_field("task", "started_at") + # # => <input id="task_started_at" name="task[started_at]" type="time" /> + # + def time_field(object_name, method, options = {}) + Tags::TimeField.new(object_name, method, self, options).render + end + + # Returns a text_field of type "datetime". + # + # datetime_field("user", "born_on") + # # => <input id="user_born_on" name="user[born_on]" type="datetime" /> + # + # The default value is generated by trying to call +strftime+ with "%Y-%m-%dT%T.%L%z" + # on the object's value, which makes it behave as expected for instances + # of DateTime and ActiveSupport::TimeWithZone. + # + # @user.born_on = Date.new(1984, 1, 12) + # datetime_field("user", "born_on") + # # => <input id="user_born_on" name="user[born_on]" type="datetime" value="1984-01-12T00:00:00.000+0000" /> + # + def datetime_field(object_name, method, options = {}) + Tags::DatetimeField.new(object_name, method, self, options).render + end + + # Returns a text_field of type "datetime-local". + # + # datetime_local_field("user", "born_on") + # # => <input id="user_born_on" name="user[born_on]" type="datetime-local" /> + # + # The default value is generated by trying to call +strftime+ with "%Y-%m-%dT%T" + # on the object's value, which makes it behave as expected for instances + # of DateTime and ActiveSupport::TimeWithZone. + # + # @user.born_on = Date.new(1984, 1, 12) + # datetime_local_field("user", "born_on") + # # => <input id="user_born_on" name="user[born_on]" type="datetime-local" value="1984-01-12T00:00:00" /> + # + def datetime_local_field(object_name, method, options = {}) + Tags::DatetimeLocalField.new(object_name, method, self, options).render + end + + # Returns a text_field of type "month". + # + # month_field("user", "born_on") + # # => <input id="user_born_on" name="user[born_on]" type="month" /> + # + # The default value is generated by trying to call +strftime+ with "%Y-%m" + # on the object's value, which makes it behave as expected for instances + # of DateTime and ActiveSupport::TimeWithZone. + # + # @user.born_on = Date.new(1984, 1, 27) + # month_field("user", "born_on") + # # => <input id="user_born_on" name="user[born_on]" type="date" value="1984-01" /> + # + def month_field(object_name, method, options = {}) + Tags::MonthField.new(object_name, method, self, options).render + end + + # Returns a text_field of type "week". + # + # week_field("user", "born_on") + # # => <input id="user_born_on" name="user[born_on]" type="week" /> + # + # The default value is generated by trying to call +strftime+ with "%Y-W%W" + # on the object's value, which makes it behave as expected for instances + # of DateTime and ActiveSupport::TimeWithZone. + # + # @user.born_on = Date.new(1984, 5, 12) + # week_field("user", "born_on") + # # => <input id="user_born_on" name="user[born_on]" type="date" value="1984-W19" /> + # + def week_field(object_name, method, options = {}) + Tags::WeekField.new(object_name, method, self, options).render + end + # Returns a text_field of type "url". # # url_field("user", "homepage") - # # => <input id="user_homepage" size="30" name="user[homepage]" type="url" /> + # # => <input id="user_homepage" name="user[homepage]" type="url" /> # def url_field(object_name, method, options = {}) Tags::UrlField.new(object_name, method, self, options).render @@ -901,7 +1111,7 @@ module ActionView # Returns a text_field of type "email". # # email_field("user", "address") - # # => <input id="user_address" size="30" name="user[address]" type="email" /> + # # => <input id="user_address" name="user[address]" type="email" /> # def email_field(object_name, method, options = {}) Tags::EmailField.new(object_name, method, self, options).render @@ -932,22 +1142,29 @@ 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] || ActionView::Base.default_form_builder + builder = options[:builder] || default_form_builder builder.new(object_name, object, self, options) end + + def default_form_builder + builder = ActionView::Base.default_form_builder + builder.respond_to?(:constantize) ? builder.constantize : builder + end end class FormBuilder + include 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 - attr_reader :multipart, :parent_builder + attr_reader :multipart, :parent_builder, :index alias :multipart? :multipart def multipart=(multipart) @@ -967,7 +1184,12 @@ module ActionView self end - def initialize(object_name, object, template, options) + def initialize(object_name, object, template, options, block=nil) + if block + ActiveSupport::Deprecation.warn( + "Giving a block to FormBuilder is deprecated and has no effect anymore.") + end + @nested_child_index = {} @object_name, @object, @template, @options = object_name, object, template, options @parent_builder = options[:parent_builder] @@ -980,6 +1202,7 @@ module ActionView end end @multipart = nil + @index = options[:index] || options[:child_index] end (field_helpers - [:label, :check_box, :radio_button, :fields_for, :hidden_field, :file_field]).each do |selector| @@ -998,7 +1221,7 @@ module ActionView fields_options, record_object = record_object, nil if record_object.is_a?(Hash) && record_object.extractable_options? fields_options[:builder] ||= options[:builder] fields_options[:parent_builder] = self - fields_options[:namespace] = fields_options[:parent_builder].options[:namespace] + fields_options[:namespace] = options[:namespace] case record_name when String, Symbol @@ -1007,16 +1230,18 @@ 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) - "[#{options[:index]}]" + options[:index] elsif defined?(@auto_index) self.object_name = @object_name.to_s.sub(/\[\]$/,"") - "[#{@auto_index}]" + @auto_index end - record_name = "#{object_name}#{index}[#{record_name}]" + + record_name = index ? "#{object_name}[#{index}][#{record_name}]" : "#{object_name}[#{record_name}]" + fields_options[:child_index] = index @template.fields_for(record_name, record_object, fields_options, &block) end @@ -1084,14 +1309,14 @@ module ActionView # <% end %> # # In the example above, if @post is a new record, it will use "Create Post" as - # submit button label, otherwise, it uses "Update Post". + # button label, otherwise, it uses "Update Post". # - # Those labels can be customized using I18n, under the helpers.submit key and accept - # the %{model} as translation interpolation: + # Those labels can be customized using I18n, under the helpers.submit key + # (the same as submit helper) and accept the %{model} as translation interpolation: # # en: # helpers: - # button: + # submit: # create: "Create a %{model}" # update: "Confirm changes to %{model}" # @@ -1099,14 +1324,25 @@ module ActionView # # en: # helpers: - # button: + # submit: # 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? @@ -1154,7 +1390,8 @@ module ActionView explicit_child_index = options[:child_index] output = ActiveSupport::SafeBuffer.new association.each do |child| - output << fields_for_nested_model("#{name}[#{explicit_child_index || nested_child_index(name)}]", child, options, block) + options[:child_index] = nested_child_index(name) unless explicit_child_index + output << fields_for_nested_model("#{name}[#{options[:child_index]}]", child, options, block) end output elsif association @@ -1175,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 bc03a1cf83..2bb526a539 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 @@ -153,6 +152,8 @@ module ActionView # form, and parameters extraction gets the last occurrence of any repeated # key in the query string, that works for ordinary forms. # + # In case if you don't want the helper to generate this hidden field you can specify <tt>:include_blank => false</tt> option. + # def select(object, method, choices, options = {}, html_options = {}) Tags::Select.new(object, method, self, choices, options, html_options).render end @@ -262,7 +263,6 @@ module ActionView # Finally, this method supports a <tt>:default</tt> option, which selects # a default ActiveSupport::TimeZone if the object's time zone is +nil+. # - # Examples: # time_zone_select( "user", "time_zone", nil, :include_blank => true) # # time_zone_select( "user", "time_zone", nil, :default => "Pacific Time (US & Canada)" ) @@ -286,38 +286,55 @@ module ActionView # # Examples (call, result): # options_for_select([["Dollar", "$"], ["Kroner", "DKK"]]) - # <option value="$">Dollar</option>\n<option value="DKK">Kroner</option> + # # <option value="$">Dollar</option> + # # <option value="DKK">Kroner</option> # # options_for_select([ "VISA", "MasterCard" ], "MasterCard") - # <option>VISA</option>\n<option selected="selected">MasterCard</option> + # # <option>VISA</option> + # # <option selected="selected">MasterCard</option> # # options_for_select({ "Basic" => "$20", "Plus" => "$40" }, "$40") - # <option value="$20">Basic</option>\n<option value="$40" selected="selected">Plus</option> + # # <option value="$20">Basic</option> + # # <option value="$40" selected="selected">Plus</option> # # options_for_select([ "VISA", "MasterCard", "Discover" ], ["VISA", "Discover"]) - # <option selected="selected">VISA</option>\n<option>MasterCard</option>\n<option selected="selected">Discover</option> + # # <option selected="selected">VISA</option> + # # <option>MasterCard</option> + # # <option selected="selected">Discover</option> # # You can optionally provide html attributes as the last element of the array. # # Examples: # options_for_select([ "Denmark", ["USA", {:class => 'bold'}], "Sweden" ], ["USA", "Sweden"]) - # <option value="Denmark">Denmark</option>\n<option value="USA" class="bold" selected="selected">USA</option>\n<option value="Sweden" selected="selected">Sweden</option> + # # <option value="Denmark">Denmark</option> + # # <option value="USA" class="bold" selected="selected">USA</option> + # # <option value="Sweden" selected="selected">Sweden</option> # # options_for_select([["Dollar", "$", {:class => "bold"}], ["Kroner", "DKK", {:onclick => "alert('HI');"}]]) - # <option value="$" class="bold">Dollar</option>\n<option value="DKK" onclick="alert('HI');">Kroner</option> + # # <option value="$" class="bold">Dollar</option> + # # <option value="DKK" onclick="alert('HI');">Kroner</option> # # If you wish to specify disabled option tags, set +selected+ to be a hash, with <tt>:disabled</tt> being either a value # or array of values to be disabled. In this case, you can use <tt>:selected</tt> to specify selected option tags. # # Examples: # options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], :disabled => "Super Platinum") - # <option value="Free">Free</option>\n<option value="Basic">Basic</option>\n<option value="Advanced">Advanced</option>\n<option value="Super Platinum" disabled="disabled">Super Platinum</option> + # # <option value="Free">Free</option> + # # <option value="Basic">Basic</option> + # # <option value="Advanced">Advanced</option> + # # <option value="Super Platinum" disabled="disabled">Super Platinum</option> # # options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], :disabled => ["Advanced", "Super Platinum"]) - # <option value="Free">Free</option>\n<option value="Basic">Basic</option>\n<option value="Advanced" disabled="disabled">Advanced</option>\n<option value="Super Platinum" disabled="disabled">Super Platinum</option> + # # <option value="Free">Free</option> + # # <option value="Basic">Basic</option> + # # <option value="Advanced" disabled="disabled">Advanced</option> + # # <option value="Super Platinum" disabled="disabled">Super Platinum</option> # # options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], :selected => "Free", :disabled => "Super Platinum") - # <option value="Free" selected="selected">Free</option>\n<option value="Basic">Basic</option>\n<option value="Advanced">Advanced</option>\n<option value="Super Platinum" disabled="disabled">Super Platinum</option> + # # <option value="Free" selected="selected">Free</option> + # # <option value="Basic">Basic</option> + # # <option value="Advanced">Advanced</option> + # # <option value="Super Platinum" disabled="disabled">Super Platinum</option> # # NOTE: Only the option tags are returned, you have to wrap this call in a regular HTML select tag. def options_for_select(container, selected = nil) @@ -330,9 +347,12 @@ module ActionView container.map do |element| html_attributes = option_html_attributes(element) text, value = option_text_and_value(element).map { |item| item.to_s } - selected_attribute = ' selected="selected"' if option_value_selected?(value, selected) - disabled_attribute = ' disabled="disabled"' if disabled && option_value_selected?(value, disabled) - %(<option value="#{ERB::Util.html_escape(value)}"#{selected_attribute}#{disabled_attribute}#{html_attributes}>#{ERB::Util.html_escape(text)}</option>) + + html_attributes[:selected] = 'selected' if option_value_selected?(value, selected) + html_attributes[:disabled] = 'disabled' if disabled && option_value_selected?(value, disabled) + html_attributes[:value] = value + + content_tag_string(:option, text, html_attributes) end.join("\n").html_safe end @@ -439,8 +459,11 @@ module ActionView # * +selected_key+ - A value equal to the +value+ attribute for one of the <tt><option></tt> tags, # which will have the +selected+ attribute set. Note: It is possible for this value to match multiple options # as you might have the same option in multiple groups. Each will then get <tt>selected="selected"</tt>. - # * +prompt+ - set to true or a prompt string. When the select element doesn't have a value yet, this + # + # Options: + # * <tt>:prompt</tt> - set to true or a prompt string. When the select element doesn't have a value yet, this # prepends an option with a generic prompt - "Please select" - or the given prompt string. + # * <tt>:divider</tt> - the divider for the options groups. # # Sample usage (Array): # grouped_options = [ @@ -453,8 +476,8 @@ module ActionView # # Sample usage (Hash): # grouped_options = { - # 'North America' => [['United States','US'], 'Canada'], - # 'Europe' => ['Denmark','Germany','France'] + # 'North America' => [['United States','US'], 'Canada'], + # 'Europe' => ['Denmark','Germany','France'] # } # grouped_options_for_select(grouped_options) # @@ -469,19 +492,54 @@ module ActionView # <option value="Canada">Canada</option> # </optgroup> # + # Sample usage (divider): + # grouped_options = [ + # [['United States','US'], 'Canada'], + # ['Denmark','Germany','France'] + # ] + # grouped_options_for_select(grouped_options, nil, divider: '---------') + # + # Possible output: + # <optgroup label="---------"> + # <option value="US">United States</option> + # <option value="Canada">Canada</option> + # </optgroup> + # <optgroup label="---------"> + # <option value="Denmark">Denmark</option> + # <option value="Germany">Germany</option> + # <option value="France">France</option> + # </optgroup> + # # <b>Note:</b> Only the <tt><optgroup></tt> and <tt><option></tt> tags are returned, so you still have to # wrap the output in an appropriate <tt><select></tt> tag. - def grouped_options_for_select(grouped_options, selected_key = nil, prompt = nil) - body = '' - body << content_tag(:option, prompt, { :value => "" }, true) if prompt + def grouped_options_for_select(grouped_options, selected_key = nil, options = {}) + if options.is_a?(Hash) + prompt = options[:prompt] + divider = options[:divider] + else + prompt = options + options = {} + ActiveSupport::Deprecation.warn "Passing the prompt to grouped_options_for_select as an argument is deprecated. Please use an options hash like `{ prompt: #{prompt.inspect} }`." + end + + body = "".html_safe + + if prompt + body.safe_concat content_tag(:option, prompt_text(prompt), :value => "") + end grouped_options = grouped_options.sort if grouped_options.is_a?(Hash) - grouped_options.each do |group| - body << content_tag(:optgroup, options_for_select(group[1], selected_key), :label => group[0]) + grouped_options.each do |container| + if divider + label = divider + else + label, container = container + end + body.safe_concat content_tag(:optgroup, options_for_select(container, selected_key), :label => label) end - body.html_safe + body end # Returns a string of option tags for pretty much any time zone in the @@ -503,23 +561,24 @@ module ActionView # NOTE: Only the option tags are returned, you have to wrap this call in # a regular HTML select tag. def time_zone_options_for_select(selected = nil, priority_zones = nil, model = ::ActiveSupport::TimeZone) - zone_options = "" + zone_options = "".html_safe zones = model.all convert_zones = lambda { |list| list.map { |z| [ z.to_s, z.name ] } } if priority_zones if priority_zones.is_a?(Regexp) - priority_zones = model.all.find_all {|z| z =~ priority_zones} + priority_zones = zones.select { |z| z =~ priority_zones } end - zone_options += options_for_select(convert_zones[priority_zones], selected) - zone_options += "<option value=\"\" disabled=\"disabled\">-------------</option>\n" - zones = zones.reject { |z| priority_zones.include?( z ) } + zone_options.safe_concat options_for_select(convert_zones[priority_zones], selected) + zone_options.safe_concat content_tag(:option, '-------------', :value => '', :disabled => 'disabled') + zone_options.safe_concat "\n" + + zones.reject! { |z| priority_zones.include?(z) } end - zone_options += options_for_select(convert_zones[zones], selected) - zone_options.html_safe + zone_options.safe_concat options_for_select(convert_zones[zones], selected) end # Returns radio button tags for the collection of existing return values @@ -574,9 +633,9 @@ module ActionView # b.label(:class => "radio_button") { b.radio_button(:class => "radio_button") } # end # - # There are also two special methods available: <tt>text</tt> and - # <tt>value</tt>, which are the current text and value methods for the - # item being rendered, respectively. You can use them like this: + # There are also three special methods available: <tt>object</tt>, <tt>text</tt> and + # <tt>value</tt>, which are the current item being rendered, its text and value methods, + # respectively. You can use them like this: # collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial) do |b| # b.label(:"data-value" => b.value) { b.radio_button + b.text } # end @@ -637,9 +696,9 @@ module ActionView # b.label(:class => "check_box") { b.check_box(:class => "check_box") } # end # - # There are also two special methods available: <tt>text</tt> and - # <tt>value</tt>, which are the current text and value methods for the - # item being rendered, respectively. You can use them like this: + # There are also three special methods available: <tt>object</tt>, <tt>text</tt> and + # <tt>value</tt>, which are the current item being rendered, its text and value methods, + # respectively. You can use them like this: # collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b| # b.label(:"data-value" => b.value) { b.check_box + b.text } # end @@ -649,20 +708,17 @@ module ActionView private def option_html_attributes(element) - return "" unless Array === element - - element.select { |e| Hash === e }.reduce({}, :merge).map do |k, v| - " #{k}=\"#{ERB::Util.html_escape(v.to_s)}\"" - end.join + if Array === element + element.select { |e| Hash === e }.reduce({}, :merge!) + else + {} + end end def option_text_and_value(option) # Options are [text, value] pairs or strings used for both. - case - when Array === option - option = option.reject { |e| Hash === e } - [option.first, option.last] - when !option.is_a?(String) && option.respond_to?(:first) && option.respond_to?(:last) + if !option.is_a?(String) && option.respond_to?(:first) && option.respond_to?(:last) + option = option.reject { |e| Hash === e } if Array === option [option.first, option.last] else [option, option] @@ -670,11 +726,7 @@ module ActionView end def option_value_selected?(value, selected) - if selected.respond_to?(:include?) && !selected.is_a?(String) - selected.include? value - else - value == selected - end + Array(selected).include? value end def extract_selected_and_disabled(selected) @@ -701,6 +753,10 @@ module ActionView def value_for_collection(item, value) value.respond_to?(:call) ? value.call(item) : item.send(value) end + + def prompt_text(prompt) + prompt = prompt.kind_of?(String) ? prompt : I18n.translate('helpers.select.prompt', :default => 'Please select') + end end class FormBuilder diff --git a/actionpack/lib/action_view/helpers/form_tag_helper.rb b/actionpack/lib/action_view/helpers/form_tag_helper.rb index e97f602728..f16e33d08d 100644 --- a/actionpack/lib/action_view/helpers/form_tag_helper.rb +++ b/actionpack/lib/action_view/helpers/form_tag_helper.rb @@ -1,12 +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 @@ -17,6 +17,9 @@ module ActionView include UrlHelper include TextHelper + mattr_accessor :embed_authenticity_token_in_remote_forms + self.embed_authenticity_token_in_remote_forms = false + # Starts a form tag that points the action to an url configured with <tt>url_for_options</tt> just like # ActionController::Base#url_for. The method for the form defaults to POST. # @@ -27,7 +30,11 @@ module ActionView # is added to simulate the verb over post. # * <tt>:authenticity_token</tt> - Authenticity token to use in the form. Use only if you need to # pass custom authenticity token string, or to not add authenticity_token field at all - # (by passing <tt>false</tt>). + # (by passing <tt>false</tt>). Remote forms may omit the embedded authenticity token + # by setting <tt>config.action_view.embed_authenticity_token_in_remote_forms = false</tt>. + # This is helpful when you're fragment-caching the form. Remote forms get the + # authenticity from the <tt>meta</tt> tag, so embedding is unnecessary unless you + # support browsers without JavaScript. # * A list of parameters to feed to the URL the form will be posted to. # * <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. @@ -37,7 +44,7 @@ module ActionView # # => <form action="/posts" method="post"> # # form_tag('/posts/1', :method => :put) - # # => <form action="/posts/1" method="put"> + # # => <form action="/posts/1" method="post"> ... <input name="_method" type="hidden" value="put" /> ... # # form_tag('/upload', :multipart => true) # # => <form action="/upload" method="post" enctype="multipart/form-data"> @@ -93,7 +100,7 @@ module ActionView # # => <select id="colors" multiple="multiple" name="colors[]"><option>Red</option> # # <option>Green</option><option>Blue</option></select> # - # select_tag "locations", "<option>Home</option><option selected="selected">Work</option><option>Out</option>".html_safe + # select_tag "locations", "<option>Home</option><option selected='selected'>Work</option><option>Out</option>".html_safe # # => <select id="locations" name="locations"><option>Home</option><option selected='selected'>Work</option> # # <option>Out</option></select> # @@ -110,15 +117,20 @@ module ActionView # select_tag "destination", "<option>NYC</option><option>Paris</option><option>Rome</option>".html_safe, :disabled => true # # => <select disabled="disabled" id="destination" name="destination"><option>NYC</option> # # <option>Paris</option><option>Rome</option></select> + # + # select_tag "credit_card", options_for_select([ "VISA", "MasterCard" ], "MasterCard") + # # => <select id="credit_card" name="credit_card"><option>VISA</option> + # # <option selected="selected">MasterCard</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) - option_tags = "<option value=\"\"></option>".html_safe + option_tags + option_tags = content_tag(:option, '', :value => '').safe_concat(option_tags) end if prompt = options.delete(:prompt) - option_tags = "<option value=\"\">#{prompt}</option>".html_safe + option_tags + option_tags = content_tag(:option, prompt, :value => '').safe_concat(option_tags) end content_tag :select, option_tags, { "name" => html_name, "id" => sanitize_to_id(name) }.update(options.stringify_keys) @@ -313,7 +325,7 @@ module ActionView options["cols"], options["rows"] = size.split("x") if size.respond_to?(:split) end - escape = options.key?("escape") ? options.delete("escape") : true + escape = options.delete("escape") { true } content = ERB::Util.html_escape(content) if escape content_tag :textarea, content.to_s.html_safe, { "name" => name, "id" => sanitize_to_id(name) }.update(options) @@ -374,14 +386,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. # * <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. - # * Any other key creates standard HTML options for the tag. # # ==== Examples # submit_tag @@ -393,26 +409,30 @@ module ActionView # submit_tag "Save edits", :disabled => true # # => <input disabled="disabled" name="commit" type="submit" value="Save edits" /> # - # submit_tag "Complete sale", :disable_with => "Please wait..." + # submit_tag "Complete sale", :data => { :disable_with => "Please wait..." } # # => <input name="commit" data-disable-with="Please wait..." type="submit" value="Complete sale" /> # # submit_tag nil, :class => "form_submit" # # => <input class="form_submit" name="commit" type="submit" /> # - # submit_tag "Edit", :disable_with => "Editing...", :class => "edit_button" - # # => <input class="edit_button" data-disable_with="Editing..." name="commit" type="submit" value="Edit" /> + # 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 @@ -427,17 +447,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. # * <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. - # * Any other key creates standard HTML options for the tag. # # ==== Examples # button_tag @@ -450,7 +474,7 @@ module ActionView # # <strong>Ask me!</strong> # # </button> # - # button_tag "Checkout", :disable_with => "Please wait..." + # 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) @@ -459,10 +483,14 @@ module ActionView 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 @@ -476,11 +504,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") @@ -494,10 +526,15 @@ 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", :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 @@ -525,13 +562,20 @@ module ActionView # <% end %> # # => <fieldset class="format"><p><input id="name" name="name" type="text" /></p></fieldset> def field_set_tag(legend = nil, options = nil, &block) - content = capture(&block) output = tag(:fieldset, options, true) output.safe_concat(content_tag(:legend, legend)) unless legend.blank? - output.concat(content) + output.concat(capture(&block)) if block_given? output.safe_concat("</fieldset>") end + # Creates a text field of type "color". + # + # ==== Options + # * Accepts the same options as text_field_tag. + def color_field_tag(name, value = nil, options = {}) + text_field_tag(name, value, options.stringify_keys.update("type" => "color")) + end + # Creates a text field of type "search". # # ==== Options @@ -549,6 +593,69 @@ module ActionView end alias phone_field_tag telephone_field_tag + # Creates a text field of type "date". + # + # ==== Options + # * Accepts the same options as text_field_tag. + def date_field_tag(name, value = nil, options = {}) + text_field_tag(name, value, options.stringify_keys.update("type" => "date")) + end + + # Creates a text field of type "time". + # + # === Options + # * <tt>:min</tt> - The minimum acceptable value. + # * <tt>:max</tt> - The maximum acceptable value. + # * <tt>:step</tt> - The acceptable value granularity. + # * Otherwise accepts the same options as text_field_tag. + def time_field_tag(name, value = nil, options = {}) + text_field_tag(name, value, options.stringify_keys.update("type" => "time")) + end + + # Creates a text field of type "datetime". + # + # === Options + # * <tt>:min</tt> - The minimum acceptable value. + # * <tt>:max</tt> - The maximum acceptable value. + # * <tt>:step</tt> - The acceptable value granularity. + # * Otherwise accepts the same options as text_field_tag. + def datetime_field_tag(name, value = nil, options = {}) + text_field_tag(name, value, options.stringify_keys.update("type" => "datetime")) + end + + # Creates a text field of type "datetime-local". + # + # === Options + # * <tt>:min</tt> - The minimum acceptable value. + # * <tt>:max</tt> - The maximum acceptable value. + # * <tt>:step</tt> - The acceptable value granularity. + # * Otherwise accepts the same options as text_field_tag. + def datetime_local_field_tag(name, value = nil, options = {}) + text_field_tag(name, value, options.stringify_keys.update("type" => "datetime-local")) + end + + # Creates a text field of type "month". + # + # === Options + # * <tt>:min</tt> - The minimum acceptable value. + # * <tt>:max</tt> - The maximum acceptable value. + # * <tt>:step</tt> - The acceptable value granularity. + # * Otherwise accepts the same options as text_field_tag. + def month_field_tag(name, value = nil, options = {}) + text_field_tag(name, value, options.stringify_keys.update("type" => "month")) + end + + # Creates a text field of type "week". + # + # === Options + # * <tt>:min</tt> - The minimum acceptable value. + # * <tt>:max</tt> - The maximum acceptable value. + # * <tt>:step</tt> - The acceptable value granularity. + # * Otherwise accepts the same options as text_field_tag. + def week_field_tag(name, value = nil, options = {}) + text_field_tag(name, value, options.stringify_keys.update("type" => "week")) + end + # Creates a text field of type "url". # # ==== Options @@ -609,8 +716,19 @@ module ActionView # responsibility of the caller to escape all the values. html_options["action"] = url_for(url_for_options) html_options["accept-charset"] = "UTF-8" + html_options["data-remote"] = true if html_options.delete("remote") - html_options["authenticity_token"] = html_options.delete("authenticity_token") if html_options.has_key?("authenticity_token") + + if html_options["data-remote"] && + !embed_authenticity_token_in_remote_forms && + html_options["authenticity_token"].blank? + # The authenticity token is taken from the meta tag in this case + html_options["authenticity_token"] = false + elsif html_options["authenticity_token"] == true + # Include the default authenticity_token, which is only generated when its set to nil, + # but we needed the true value to override the default of no authenticity_token on data-remote. + html_options["authenticity_token"] = nil + end end end diff --git a/actionpack/lib/action_view/helpers/javascript_helper.rb b/actionpack/lib/action_view/helpers/javascript_helper.rb index 309923490c..9f8cd8caaa 100644 --- a/actionpack/lib/action_view/helpers/javascript_helper.rb +++ b/actionpack/lib/action_view/helpers/javascript_helper.rb @@ -1,5 +1,4 @@ require 'action_view/helpers/tag_helper' -require 'active_support/core_ext/string/encoding' module ActionView module Helpers @@ -15,6 +14,7 @@ module ActionView } JS_ESCAPE_MAP["\342\200\250".force_encoding('UTF-8').encode!] = '
' + JS_ESCAPE_MAP["\342\200\251".force_encoding('UTF-8').encode!] = '
' # Escapes carriage returns and single and double quotes for JavaScript segments. # @@ -23,7 +23,7 @@ module ActionView # $('some_element').replaceWith('<%=j render 'some/element_template' %>'); def escape_javascript(javascript) if javascript - result = javascript.gsub(/(\\|<\/|\r\n|\342\200\250|[\n\r"'])/u) {|match| JS_ESCAPE_MAP[match] } + result = javascript.gsub(/(\\|<\/|\r\n|\342\200\250|\342\200\251|[\n\r"'])/u) {|match| JS_ESCAPE_MAP[match] } javascript.html_safe? ? result.html_safe : result else '' @@ -36,7 +36,7 @@ module ActionView # javascript_tag "alert('All is good')" # # Returns: - # <script type="text/javascript"> + # <script> # //<![CDATA[ # alert('All is good') # //]]> @@ -45,7 +45,7 @@ module ActionView # +html_options+ may be a hash of attributes for the <tt>\<script></tt> # tag. Example: # javascript_tag "alert('All is good')", :defer => 'defer' - # # => <script defer="defer" type="text/javascript">alert('All is good')</script> + # # => <script defer="defer">alert('All is good')</script> # # Instead of passing the content as an argument, you can also use a block # in which case, you pass your +html_options+ as the first parameter. @@ -61,7 +61,7 @@ module ActionView content_or_options_with_block end - content_tag(:script, javascript_cdata_section(content), html_options.merge(:type => Mime::JS)) + content_tag(:script, javascript_cdata_section(content), html_options) end def javascript_cdata_section(content) #:nodoc: @@ -78,6 +78,9 @@ module ActionView # # => <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)) @@ -96,6 +99,9 @@ module ActionView # # => <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] || '#' diff --git a/actionpack/lib/action_view/helpers/number_helper.rb b/actionpack/lib/action_view/helpers/number_helper.rb index b0860f87c4..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 @@ -28,17 +25,20 @@ module ActionView end end - # Formats a +number+ into a US phone number (e.g., (555) 123-9876). You can customize the format - # in the +options+ hash. + # Formats a +number+ into a US phone number (e.g., (555) + # 123-9876). You can customize the format in the +options+ hash. # # ==== Options # - # * <tt>:area_code</tt> - Adds parentheses around the area code. - # * <tt>:delimiter</tt> - Specifies the delimiter to use (defaults to "-"). - # * <tt>:extension</tt> - Specifies an extension to add to the end of the - # generated number. - # * <tt>:country_code</tt> - Sets the country code for the phone number. - # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when the argument is invalid. + # * <tt>:area_code</tt> - Adds parentheses around the area code. + # * <tt>:delimiter</tt> - Specifies the delimiter to use + # (defaults to "-"). + # * <tt>:extension</tt> - Specifies an extension to add to the + # end of the generated number. + # * <tt>:country_code</tt> - Sets the country code for the phone + # number. + # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when + # the argument is invalid. # # ==== Examples # @@ -59,46 +59,35 @@ 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.join) + 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 can customize the format - # in the +options+ hash. + # Formats a +number+ into a currency string (e.g., $13.65). You + # can customize the format in the +options+ hash. # # ==== Options # - # * <tt>:locale</tt> - Sets the locale to be used for formatting (defaults to current locale). - # * <tt>:precision</tt> - Sets the level of precision (defaults to 2). - # * <tt>:unit</tt> - Sets the denomination of the currency (defaults to "$"). - # * <tt>:separator</tt> - Sets the separator between the units (defaults to "."). - # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to ","). - # * <tt>:format</tt> - Sets the format for non-negative numbers (defaults to "%u%n"). - # Fields are <tt>%u</tt> for the currency, and <tt>%n</tt> - # for the number. - # * <tt>:negative_format</tt> - Sets the format for negative numbers (defaults to prepending - # an hyphen to the formatted number given by <tt>:format</tt>). - # Accepts the same fields than <tt>:format</tt>, except - # <tt>%n</tt> is here the absolute value of the number. - # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when the argument is invalid. + # * <tt>:locale</tt> - Sets the locale to be used for formatting + # (defaults to current locale). + # * <tt>:precision</tt> - Sets the level of precision (defaults + # to 2). + # * <tt>:unit</tt> - Sets the denomination of the currency + # (defaults to "$"). + # * <tt>:separator</tt> - Sets the separator between the units + # (defaults to "."). + # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults + # to ","). + # * <tt>:format</tt> - Sets the format for non-negative numbers + # (defaults to "%u%n"). Fields are <tt>%u</tt> for the + # currency, and <tt>%n</tt> for the number. + # * <tt>:negative_format</tt> - Sets the format for negative + # numbers (defaults to prepending an hyphen to the formatted + # number given by <tt>:format</tt>). Accepts the same fields + # than <tt>:format</tt>, except <tt>%n</tt> is here the + # absolute value of the number. + # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when + # the argument is invalid. # # ==== Examples # @@ -118,53 +107,36 @@ module ActionView # # => 1234567890,50 £ def number_to_currency(number, options = {}) return unless number - options = options.symbolize_keys - - currency = translations_for('currency', options[:locale]) - currency[:negative_format] ||= "-" + currency[:format] if currency[:format] + options = escape_unsafe_delimiters_and_separators(options.symbolize_keys) - 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 customize the format in the +options+ hash. + # Formats a +number+ as a percentage string (e.g., 65%). You can + # customize the format in the +options+ hash. # # ==== Options # - # * <tt>:locale</tt> - Sets the locale to be used for formatting (defaults to current - # locale). - # * <tt>:precision</tt> - Sets the precision of the number (defaults to 3). - # * <tt>:significant</tt> - If +true+, precision will be the # of significant_digits. If +false+, - # the # of fractional digits (defaults to +false+). - # * <tt>:separator</tt> - Sets the separator between the fractional and integer digits (defaults - # to "."). - # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to ""). - # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes insignificant zeros after the decimal separator - # (defaults to +false+). - # * <tt>:format</tt> - Specifies the format of the percentage string - # The number field is <tt>%n</tt> (defaults to "%n%"). - # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when the argument is invalid. + # * <tt>:locale</tt> - Sets the locale to be used for formatting + # (defaults to current locale). + # * <tt>:precision</tt> - Sets the precision of the number + # (defaults to 3). + # * <tt>:significant</tt> - If +true+, precision will be the # + # of significant_digits. If +false+, the # of fractional + # digits (defaults to +false+). + # * <tt>:separator</tt> - Sets the separator between the + # fractional and integer digits (defaults to "."). + # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults + # to ""). + # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes + # insignificant zeros after the decimal separator (defaults to + # +false+). + # * <tt>:format</tt> - Specifies the format of the percentage + # string The number field is <tt>%n</tt> (defaults to "%n%"). + # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when + # the argument is invalid. # # ==== Examples # @@ -180,35 +152,27 @@ module ActionView # number_to_percentage("98a", :raise => true) # => InvalidNumberError def number_to_percentage(number, options = {}) return unless number - options = options.symbolize_keys - - defaults = format_translations('percentage', options[:locale]) - options = defaults.merge!(options) + options = escape_unsafe_delimiters_and_separators(options.symbolize_keys) - 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+ (e.g., 12,324). You can - # customize the format in the +options+ hash. + # Formats a +number+ with grouped thousands using +delimiter+ + # (e.g., 12,324). You can customize the format in the +options+ + # hash. # # ==== Options # - # * <tt>:locale</tt> - Sets the locale to be used for formatting (defaults to current locale). - # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to ","). - # * <tt>:separator</tt> - Sets the separator between the fractional and integer digits (defaults to "."). - # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when the argument is invalid. + # * <tt>:locale</tt> - Sets the locale to be used for formatting + # (defaults to current locale). + # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults + # to ","). + # * <tt>:separator</tt> - Sets the separator between the + # fractional and integer digits (defaults to "."). + # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when + # the argument is invalid. # # ==== Examples # @@ -225,34 +189,39 @@ 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]}") - parts.join(options[:separator]).html_safe + 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 <tt>:precision</tt> (e.g., 112.32 has a precision - # of 2 if +:significant+ is +false+, and 5 if +:significant+ is +true+). + # Formats a +number+ with the specified level of + # <tt>:precision</tt> (e.g., 112.32 has a precision of 2 if + # +:significant+ is +false+, and 5 if +:significant+ is +true+). # You can customize the format in the +options+ hash. # # ==== Options - # * <tt>:locale</tt> - Sets the locale to be used for formatting (defaults to current locale). - # * <tt>:precision</tt> - Sets the precision of the number (defaults to 3). - # * <tt>:significant</tt> - If +true+, precision will be the # of significant_digits. If +false+, - # the # of fractional digits (defaults to +false+). - # * <tt>:separator</tt> - Sets the separator between the fractional and integer digits (defaults - # to "."). - # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to ""). - # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes insignificant zeros after the decimal separator - # (defaults to +false+). - # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when the argument is invalid. + # + # * <tt>:locale</tt> - Sets the locale to be used for formatting + # (defaults to current locale). + # * <tt>:precision</tt> - Sets the precision of the number + # (defaults to 3). + # * <tt>:significant</tt> - If +true+, precision will be the # + # of significant_digits. If +false+, the # of fractional + # digits (defaults to +false+). + # * <tt>:separator</tt> - Sets the separator between the + # fractional and integer digits (defaults to "."). + # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults + # to ""). + # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes + # insignificant zeros after the decimal separator (defaults to + # +false+). + # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when + # the argument is invalid. # # ==== Examples + # # number_with_precision(111.2345) # => 111.235 # number_with_precision(111.2345, :precision => 2) # => 111.23 # number_with_precision(13, :precision => 5) # => 13.00000 @@ -269,58 +238,45 @@ module ActionView # number_with_precision(1111.2345, :precision => 2, :separator => ',', :delimiter => '.') # # => 1.111,23 def number_with_precision(number, options = {}) - options = 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 + options = escape_unsafe_delimiters_and_separators(options.symbolize_keys) - 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 - 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 method is useful for - # reporting file sizes to users. You can customize the - # format in the +options+ hash. + # Formats the bytes in +number+ into a more understandable + # representation (e.g., giving it 1500 yields 1.5 KB). This + # method is useful for reporting file sizes to users. You can + # customize the format in the +options+ hash. # - # See <tt>number_to_human</tt> if you want to pretty-print a generic number. + # See <tt>number_to_human</tt> if you want to pretty-print a + # generic number. # # ==== Options - # * <tt>:locale</tt> - Sets the locale to be used for formatting (defaults to current locale). - # * <tt>:precision</tt> - Sets the precision of the number (defaults to 3). - # * <tt>:significant</tt> - If +true+, precision will be the # of significant_digits. If +false+, the # of fractional digits (defaults to +true+) - # * <tt>:separator</tt> - Sets the separator between the fractional and integer digits (defaults to "."). - # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to ""). - # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes insignificant zeros after the decimal separator (defaults to +true+) - # * <tt>:prefix</tt> - If +:si+ formats the number using the SI prefix (defaults to :binary) - # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when the argument is invalid. + # + # * <tt>:locale</tt> - Sets the locale to be used for formatting + # (defaults to current locale). + # * <tt>:precision</tt> - Sets the precision of the number + # (defaults to 3). + # * <tt>:significant</tt> - If +true+, precision will be the # + # of significant_digits. If +false+, the # of fractional + # digits (defaults to +true+) + # * <tt>:separator</tt> - Sets the separator between the + # fractional and integer digits (defaults to "."). + # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults + # to ""). + # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes + # insignificant zeros after the decimal separator (defaults to + # +true+) + # * <tt>:prefix</tt> - If +:si+ formats the number using the SI + # prefix (defaults to :binary) + # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when + # the argument is invalid. + # # ==== Examples + # # number_to_human_size(123) # => 123 Bytes # number_to_human_size(1234) # => 1.21 KB # number_to_human_size(12345) # => 12.1 KB @@ -331,72 +287,69 @@ module ActionView # number_to_human_size(483989, :precision => 2) # => 470 KB # number_to_human_size(1234567, :precision => 2, :separator => ',') # => 1,2 MB # - # Non-significant zeros after the fractional separator are stripped out by default (set - # <tt>:strip_insignificant_zeros</tt> to +false+ to change that): + # Non-significant zeros after the fractional separator are + # stripped out by default (set + # <tt>:strip_insignificant_zeros</tt> to +false+ to change + # that): # 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) + options = escape_unsafe_delimiters_and_separators(options.symbolize_keys) - #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) - - 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 (and too hard to read). + # 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 + # (and too hard to read). # - # See <tt>number_to_human_size</tt> if you want to print a file size. + # See <tt>number_to_human_size</tt> if you want to print a file + # size. # - # You can also define you own unit-quantifier names if you want to use other decimal units - # (eg.: 1500 becomes "1.5 kilometers", 0.150 becomes "150 milliliters", etc). You may define - # a wide range of unit quantifiers, even fractional ones (centi, deci, mili, etc). + # You can also define you own unit-quantifier names if you want + # to use other decimal units (eg.: 1500 becomes "1.5 + # kilometers", 0.150 becomes "150 milliliters", etc). You may + # define a wide range of unit quantifiers, even fractional ones + # (centi, deci, mili, etc). # # ==== Options - # * <tt>:locale</tt> - Sets the locale to be used for formatting (defaults to current locale). - # * <tt>:precision</tt> - Sets the precision of the number (defaults to 3). - # * <tt>:significant</tt> - If +true+, precision will be the # of significant_digits. If +false+, the # of fractional digits (defaults to +true+) - # * <tt>:separator</tt> - Sets the separator between the fractional and integer digits (defaults to "."). - # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to ""). - # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes insignificant zeros after the decimal separator (defaults to +true+) - # * <tt>:units</tt> - A Hash of unit quantifier names. Or a string containing an i18n scope where to find this hash. It might have the following keys: - # * *integers*: <tt>:unit</tt>, <tt>:ten</tt>, <tt>:hundred</tt>, <tt>:thousand</tt>, <tt>:million</tt>, <tt>:billion</tt>, <tt>:trillion</tt>, <tt>:quadrillion</tt> - # * *fractionals*: <tt>:deci</tt>, <tt>:centi</tt>, <tt>:mili</tt>, <tt>:micro</tt>, <tt>:nano</tt>, <tt>:pico</tt>, <tt>:femto</tt> - # * <tt>:format</tt> - Sets the format of the output string (defaults to "%n %u"). The field types are: - # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when the argument is invalid. - # - # %u The quantifier (ex.: 'thousand') - # %n The number + # + # * <tt>:locale</tt> - Sets the locale to be used for formatting + # (defaults to current locale). + # * <tt>:precision</tt> - Sets the precision of the number + # (defaults to 3). + # * <tt>:significant</tt> - If +true+, precision will be the # + # of significant_digits. If +false+, the # of fractional + # digits (defaults to +true+) + # * <tt>:separator</tt> - Sets the separator between the + # fractional and integer digits (defaults to "."). + # * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults + # to ""). + # * <tt>:strip_insignificant_zeros</tt> - If +true+ removes + # insignificant zeros after the decimal separator (defaults to + # +true+) + # * <tt>:units</tt> - A Hash of unit quantifier names. Or a + # string containing an i18n scope where to find this hash. It + # might have the following keys: + # * *integers*: <tt>:unit</tt>, <tt>:ten</tt>, + # *<tt>:hundred</tt>, <tt>:thousand</tt>, <tt>:million</tt>, + # *<tt>:billion</tt>, <tt>:trillion</tt>, + # *<tt>:quadrillion</tt> + # * *fractionals*: <tt>:deci</tt>, <tt>:centi</tt>, + # *<tt>:mili</tt>, <tt>:micro</tt>, <tt>:nano</tt>, + # *<tt>:pico</tt>, <tt>:femto</tt> + # * <tt>:format</tt> - Sets the format of the output string + # (defaults to "%n %u"). The field types are: + # * %u - The quantifier (ex.: 'thousand') + # * %n - The number + # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when + # the argument is invalid. # # ==== Examples + # # number_to_human(123) # => "123" # number_to_human(1234) # => "1.23 Thousand" # number_to_human(12345) # => "12.3 Thousand" @@ -413,8 +366,9 @@ module ActionView # :separator => ',', # :significant => false) # => "1,2 Million" # - # Unsignificant zeros after the decimal separator are stripped out by default (set - # <tt>:strip_insignificant_zeros</tt> to +false+ to change that): + # Non-significant zeros after the decimal separator are stripped + # out by default (set <tt>:strip_insignificant_zeros</tt> to + # +false+ to change that): # number_to_human(12345012345, :significant_digits => 6) # => "12.345 Billion" # number_to_human(500000000, :precision => 5) # => "500 Million" # @@ -446,60 +400,36 @@ module ActionView # number_to_human(0.34, :units => :distance) # => "34 centimeters" # def number_to_human(number, options = {}) - options = options.symbolize_keys - - number = (parse_float(number, options[:raise]) or return number) + options = escape_unsafe_delimiters_and_separators(options.symbolize_keys) - defaults = format_translations('human', options[:locale]) - options = defaults.merge!(options) + wrap_with_output_safety_handling(number, options.delete(:raise)) { + ActiveSupport::NumberHelper.number_to_human(number, options) + } + end - #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) + private - inverted_du = DECIMAL_UNITS.invert + 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 - 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} + 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 - number_exponent = number != 0 ? Math.log10(number.abs).floor : 0 - display_exponent = unit_exponents.find{ |e| number_exponent >= e } || 0 - number /= 10 ** display_exponent + formatted_number = yield - 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/record_tag_helper.rb b/actionpack/lib/action_view/helpers/record_tag_helper.rb index 1a15459406..dded9aab7c 100644 --- a/actionpack/lib/action_view/helpers/record_tag_helper.rb +++ b/actionpack/lib/action_view/helpers/record_tag_helper.rb @@ -1,10 +1,8 @@ -require 'action_controller/record_identifier' - module ActionView # = Action View Record Tag Helpers module Helpers module RecordTagHelper - include ActionController::RecordIdentifier + include ActionView::RecordIdentifier # Produces a wrapper DIV element with id and class parameters that # relate to the specified Active Record object. Usage example: @@ -94,10 +92,10 @@ module ActionView # for each record. def content_tag_for_single_record(tag_name, record, prefix, options, &block) options = options ? options.dup : {} - options.merge!(:class => "#{dom_class(record, prefix)} #{options[:class]}".rstrip, :id => dom_id(record, prefix)) + options[:class] = "#{dom_class(record, prefix)} #{options[:class]}".rstrip + options[:id] = dom_id(record, prefix) - content = block.arity == 0 ? capture(&block) : capture(record, &block) - content_tag(tag_name, content, options) + content_tag(tag_name, capture(record, &block), options) end end end diff --git a/actionpack/lib/action_view/helpers/sanitize_helper.rb b/actionpack/lib/action_view/helpers/sanitize_helper.rb index 7768c8c151..9c76c26ace 100644 --- a/actionpack/lib/action_view/helpers/sanitize_helper.rb +++ b/actionpack/lib/action_view/helpers/sanitize_helper.rb @@ -1,5 +1,5 @@ require 'active_support/core_ext/object/try' -require 'action_controller/vendor/html-scanner' +require 'action_view/vendor/html-scanner' module ActionView # = Action View Sanitize Helpers @@ -69,8 +69,6 @@ module ActionView # html-scanner tokenizer and so its HTML parsing ability is limited by # that of html-scanner. # - # ==== Examples - # # strip_tags("Strip <i>these</i> tags!") # # => Strip these tags! # @@ -80,12 +78,11 @@ 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. # - # ==== Examples # strip_links('<a href="http://www.rubyonrails.org">Ruby on Rails</a>') # # => Ruby on Rails # diff --git a/actionpack/lib/action_view/helpers/tag_helper.rb b/actionpack/lib/action_view/helpers/tag_helper.rb index ecd26891d6..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' @@ -14,9 +13,13 @@ module ActionView BOOLEAN_ATTRIBUTES = %w(disabled readonly multiple checked autobuffer autoplay controls loop selected hidden scoped async defer reversed ismap seemless muted required - autofocus novalidate formnovalidate open pubdate).to_set + autofocus novalidate formnovalidate open pubdate itemscope).to_set BOOLEAN_ATTRIBUTES.merge(BOOLEAN_ATTRIBUTES.map {|attribute| attribute.to_sym }) + PRE_CONTENT_STRINGS = { + :textarea => "\n" + } + # Returns an empty HTML tag of type +name+ which by default is XHTML # compliant. Set +open+ to true to create an open tag compatible # with HTML 4.0 and below. Add HTML attributes by passing an attributes @@ -37,7 +40,7 @@ module ActionView # thus accessed as <tt>dataset.userId</tt>. # # Values are encoded to JSON, with the exception of strings and symbols. - # This may come in handy when using jQuery's HTML5-aware <tt>.data()<tt> + # This may come in handy when using jQuery's HTML5-aware <tt>.data()</tt> # from 1.4.3. # # ==== Examples @@ -99,19 +102,21 @@ module ActionView # otherwise be recognized as markup. CDATA sections begin with the string # <tt><![CDATA[</tt> and end with (and may not contain) the string <tt>]]></tt>. # - # ==== Examples # cdata_section("<hello world>") # # => <![CDATA[<hello world>]]> # # cdata_section(File.read("hello_world.txt")) # # => <![CDATA[<hello from a text file]]> + # + # cdata_section("hello]]>world") + # # => <![CDATA[hello]]]]><![CDATA[>world]]> def cdata_section(content) - "<![CDATA[#{content}]]>".html_safe + splitted = content.gsub(']]>', ']]]]><![CDATA[>') + "<![CDATA[#{splitted}]]>".html_safe end # Returns an escaped version of +html+ without affecting existing escaped entities. # - # ==== Examples # escape_once("1 < 2 & 3") # # => "1 < 2 & 3" # @@ -126,7 +131,7 @@ module ActionView def content_tag_string(name, content, options, escape = true) tag_options = tag_options(options, escape) if options content = ERB::Util.h(content) if escape - "<#{name}#{tag_options}>#{content}</#{name}>".html_safe + "<#{name}#{tag_options}>#{PRE_CONTENT_STRINGS[name.to_sym]}#{content}</#{name}>".html_safe end def tag_options(options, escape = true) @@ -148,8 +153,9 @@ module ActionView def data_tag_option(key, value, escape) key = "data-#{key.to_s.dasherize}" - value = value.to_json if !value.is_a?(String) && !value.is_a?(Symbol) - + unless value.is_a?(String) || value.is_a?(Symbol) || value.is_a?(BigDecimal) + value = value.to_json + end tag_option(key, value, escape) end diff --git a/actionpack/lib/action_view/helpers/tags.rb b/actionpack/lib/action_view/helpers/tags.rb index c480799fe3..a05e16979a 100644 --- a/actionpack/lib/action_view/helpers/tags.rb +++ b/actionpack/lib/action_view/helpers/tags.rb @@ -8,13 +8,18 @@ module ActionView autoload :CollectionCheckBoxes autoload :CollectionRadioButtons autoload :CollectionSelect + autoload :ColorField + autoload :DateField autoload :DateSelect + autoload :DatetimeField + autoload :DatetimeLocalField autoload :DatetimeSelect autoload :EmailField autoload :FileField autoload :GroupedCollectionSelect autoload :HiddenField autoload :Label + autoload :MonthField autoload :NumberField autoload :PasswordField autoload :RadioButton @@ -24,9 +29,11 @@ module ActionView autoload :TelField autoload :TextArea autoload :TextField + autoload :TimeField autoload :TimeSelect autoload :TimeZoneSelect autoload :UrlField + autoload :WeekField end end end diff --git a/actionpack/lib/action_view/helpers/tags/base.rb b/actionpack/lib/action_view/helpers/tags/base.rb index e22612ccd0..192f5eebaa 100644 --- a/actionpack/lib/action_view/helpers/tags/base.rb +++ b/actionpack/lib/action_view/helpers/tags/base.rb @@ -5,8 +5,6 @@ module ActionView include Helpers::ActiveModelInstanceTag, Helpers::TagHelper, Helpers::FormTagHelper include FormOptionsHelper - DEFAULT_FIELD_OPTIONS = { "size" => 30 } - attr_reader :object def initialize(object_name, method_name, template_object, options = {}) @@ -36,7 +34,7 @@ module ActionView object.respond_to?(method_before_type_cast) ? object.send(method_before_type_cast) : - object.send(@method_name) + value(object) end end @@ -75,14 +73,14 @@ module ActionView def add_default_name_and_id(options) if options.has_key?("index") - options["name"] ||= tag_name_with_index(options["index"]) + options["name"] ||= options.fetch("name"){ tag_name_with_index(options["index"]) } options["id"] = options.fetch("id"){ tag_id_with_index(options["index"]) } options.delete("index") elsif defined?(@auto_index) - options["name"] ||= tag_name_with_index(@auto_index) + options["name"] ||= options.fetch("name"){ tag_name_with_index(@auto_index) } options["id"] = options.fetch("id"){ tag_id_with_index(@auto_index) } else - options["name"] ||= options['multiple'] ? tag_name_multiple : tag_name + options["name"] ||= options.fetch("name"){ options['multiple'] ? tag_name_multiple : tag_name } options["id"] = options.fetch("id"){ tag_id } end options["id"] = [options.delete('namespace'), options["id"]].compact.join("_").presence @@ -123,23 +121,28 @@ module ActionView def select_content_tag(option_tags, options, html_options) html_options = html_options.stringify_keys add_default_name_and_id(html_options) + options[:include_blank] ||= true unless options[:prompt] || select_not_required?(html_options) select = content_tag("select", add_options(option_tags, options, value(object)), html_options) - if html_options["multiple"] + + if html_options["multiple"] && options.fetch(:include_hidden, true) tag("input", :disabled => html_options["disabled"], :name => html_options["name"], :type => "hidden", :value => "") + select else select end end + def select_not_required?(html_options) + !html_options["required"] || html_options["multiple"] || html_options["size"].to_i > 1 + end + def add_options(option_tags, options, value = nil) if options[:include_blank] - option_tags = "<option value=\"\">#{ERB::Util.html_escape(options[:include_blank]) if options[:include_blank].kind_of?(String)}</option>\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] - prompt = options[:prompt].kind_of?(String) ? options[:prompt] : I18n.translate('helpers.select.prompt', :default => 'Please select') - option_tags = "<option value=\"\">#{ERB::Util.html_escape(prompt)}</option>\n" + option_tags + option_tags = content_tag_string('option', prompt_text(options[:prompt]), :value => '') + "\n" + option_tags end - option_tags.html_safe + option_tags end end end diff --git a/actionpack/lib/action_view/helpers/tags/check_box.rb b/actionpack/lib/action_view/helpers/tags/check_box.rb index 579cdb9fc9..9d17a1dde3 100644 --- a/actionpack/lib/action_view/helpers/tags/check_box.rb +++ b/actionpack/lib/action_view/helpers/tags/check_box.rb @@ -25,9 +25,15 @@ module ActionView add_default_name_and_id(options) end - hidden = hidden_field_for_checkbox(options) + include_hidden = options.delete("include_hidden") { true } checkbox = tag("input", options) - hidden + checkbox + + if include_hidden + hidden = hidden_field_for_checkbox(options) + hidden + checkbox + else + checkbox + end end private @@ -35,17 +41,15 @@ module ActionView def checked?(value) case value when TrueClass, FalseClass - value + value == !!@checked_value when NilClass false - when Integer - value != 0 when String value == @checked_value when Array value.include?(@checked_value) else - value.to_i != 0 + value.to_i == @checked_value.to_i end end diff --git a/actionpack/lib/action_view/helpers/tags/collection_check_boxes.rb b/actionpack/lib/action_view/helpers/tags/collection_check_boxes.rb index 5f1e9ec026..e23f5113fb 100644 --- a/actionpack/lib/action_view/helpers/tags/collection_check_boxes.rb +++ b/actionpack/lib/action_view/helpers/tags/collection_check_boxes.rb @@ -14,9 +14,9 @@ module ActionView end def render - rendered_collection = render_collection do |value, text, default_html_options| + rendered_collection = render_collection do |item, value, text, default_html_options| default_html_options[:multiple] = true - builder = instantiate_builder(CheckBoxBuilder, value, text, default_html_options) + builder = instantiate_builder(CheckBoxBuilder, item, value, text, default_html_options) if block_given? yield builder diff --git a/actionpack/lib/action_view/helpers/tags/collection_helpers.rb b/actionpack/lib/action_view/helpers/tags/collection_helpers.rb index 1e2e77dde1..4e33e79a36 100644 --- a/actionpack/lib/action_view/helpers/tags/collection_helpers.rb +++ b/actionpack/lib/action_view/helpers/tags/collection_helpers.rb @@ -3,13 +3,14 @@ module ActionView module Tags module CollectionHelpers class Builder - attr_reader :text, :value + attr_reader :object, :text, :value - def initialize(template_object, object_name, method_name, + def initialize(template_object, object_name, method_name, object, sanitized_attribute_name, text, value, input_html_options) @template_object = template_object @object_name = object_name @method_name = method_name + @object = object @sanitized_attribute_name = sanitized_attribute_name @text = text @value = value @@ -32,8 +33,8 @@ module ActionView private - def instantiate_builder(builder_class, value, text, html_options) - builder_class.new(@template_object, @object_name, @method_name, + def instantiate_builder(builder_class, item, value, text, html_options) + builder_class.new(@template_object, @object_name, @method_name, item, sanitize_attribute_name(value), text, value, html_options) end @@ -48,7 +49,7 @@ module ActionView accept = if current_value.respond_to?(:call) current_value.call(item) else - Array(current_value).include?(value) + Array(current_value).map(&:to_s).include?(value.to_s) end if accept @@ -58,6 +59,7 @@ module ActionView end end + html_options[:object] = @object html_options end @@ -71,7 +73,7 @@ module ActionView text = value_for_collection(item, @text_method) default_html_options = default_html_options_for_collection(item, value) - yield value, text, default_html_options + yield item, value, text, default_html_options end.join.html_safe end end diff --git a/actionpack/lib/action_view/helpers/tags/collection_radio_buttons.rb b/actionpack/lib/action_view/helpers/tags/collection_radio_buttons.rb index 8e7aeeed63..ba2035f074 100644 --- a/actionpack/lib/action_view/helpers/tags/collection_radio_buttons.rb +++ b/actionpack/lib/action_view/helpers/tags/collection_radio_buttons.rb @@ -14,8 +14,8 @@ module ActionView end def render - render_collection do |value, text, default_html_options| - builder = instantiate_builder(RadioButtonBuilder, value, text, default_html_options) + render_collection do |item, value, text, default_html_options| + builder = instantiate_builder(RadioButtonBuilder, item, value, text, default_html_options) if block_given? yield builder diff --git a/actionpack/lib/action_view/helpers/tags/color_field.rb b/actionpack/lib/action_view/helpers/tags/color_field.rb new file mode 100644 index 0000000000..6f08f8483a --- /dev/null +++ b/actionpack/lib/action_view/helpers/tags/color_field.rb @@ -0,0 +1,25 @@ +module ActionView + module Helpers + module Tags + class ColorField < TextField #:nodoc: + def render + options = @options.stringify_keys + options["value"] = @options.fetch("value") { validate_color_string(value(object)) } + @options = options + super + end + + private + + def validate_color_string(string) + regex = /#[0-9a-fA-F]{6}/ + if regex.match(string) + string.downcase + else + "#000000" + end + end + end + end + end +end diff --git a/actionpack/lib/action_view/helpers/tags/date_field.rb b/actionpack/lib/action_view/helpers/tags/date_field.rb new file mode 100644 index 0000000000..64c29dea3d --- /dev/null +++ b/actionpack/lib/action_view/helpers/tags/date_field.rb @@ -0,0 +1,13 @@ +module ActionView + module Helpers + module Tags + class DateField < DatetimeField #:nodoc: + private + + def format_date(value) + value.try(:strftime, "%Y-%m-%d") + end + end + end + end +end diff --git a/actionpack/lib/action_view/helpers/tags/datetime_field.rb b/actionpack/lib/action_view/helpers/tags/datetime_field.rb new file mode 100644 index 0000000000..e407146e96 --- /dev/null +++ b/actionpack/lib/action_view/helpers/tags/datetime_field.rb @@ -0,0 +1,22 @@ +module ActionView + module Helpers + module Tags + class DatetimeField < TextField #:nodoc: + def render + options = @options.stringify_keys + options["value"] = @options.fetch("value") { format_date(value(object)) } + options["min"] = format_date(options["min"]) + options["max"] = format_date(options["max"]) + @options = options + super + end + + private + + def format_date(value) + value.try(:strftime, "%Y-%m-%dT%T.%L%z") + end + end + end + end +end diff --git a/actionpack/lib/action_view/helpers/tags/datetime_local_field.rb b/actionpack/lib/action_view/helpers/tags/datetime_local_field.rb new file mode 100644 index 0000000000..6668d6d718 --- /dev/null +++ b/actionpack/lib/action_view/helpers/tags/datetime_local_field.rb @@ -0,0 +1,19 @@ +module ActionView + module Helpers + module Tags + class DatetimeLocalField < DatetimeField #:nodoc: + class << self + def field_type + @field_type ||= "datetime-local" + end + end + + private + + def format_date(value) + value.try(:strftime, "%Y-%m-%dT%T") + end + end + end + end +end diff --git a/actionpack/lib/action_view/helpers/tags/file_field.rb b/actionpack/lib/action_view/helpers/tags/file_field.rb index 56442e1c14..59f2ff71b4 100644 --- a/actionpack/lib/action_view/helpers/tags/file_field.rb +++ b/actionpack/lib/action_view/helpers/tags/file_field.rb @@ -2,10 +2,6 @@ module ActionView module Helpers module Tags class FileField < TextField #:nodoc: - def render - @options.update(:size => nil) - super - end end end end diff --git a/actionpack/lib/action_view/helpers/tags/grouped_collection_select.rb b/actionpack/lib/action_view/helpers/tags/grouped_collection_select.rb index 507466a57a..507ba8835f 100644 --- a/actionpack/lib/action_view/helpers/tags/grouped_collection_select.rb +++ b/actionpack/lib/action_view/helpers/tags/grouped_collection_select.rb @@ -14,8 +14,13 @@ module ActionView end def render + option_tags_options = { + :selected => @options.fetch(:selected) { value(@object) }, + :disabled => @options[:disabled] + } + select_content_tag( - option_groups_from_collection_for_select(@collection, @group_method, @group_label_method, @option_key_method, @option_value_method, value(@object)), @options, @html_options + option_groups_from_collection_for_select(@collection, @group_method, @group_label_method, @option_key_method, @option_value_method, option_tags_options), @options, @html_options ) end end diff --git a/actionpack/lib/action_view/helpers/tags/hidden_field.rb b/actionpack/lib/action_view/helpers/tags/hidden_field.rb index ea86596e0b..a8d13dc1b1 100644 --- a/actionpack/lib/action_view/helpers/tags/hidden_field.rb +++ b/actionpack/lib/action_view/helpers/tags/hidden_field.rb @@ -2,10 +2,6 @@ module ActionView module Helpers module Tags class HiddenField < TextField #:nodoc: - def render - @options.update(:size => nil) - super - end end end end diff --git a/actionpack/lib/action_view/helpers/tags/label.rb b/actionpack/lib/action_view/helpers/tags/label.rb index 1bd71c2778..16135fcd5a 100644 --- a/actionpack/lib/action_view/helpers/tags/label.rb +++ b/actionpack/lib/action_view/helpers/tags/label.rb @@ -3,16 +3,16 @@ module ActionView module Tags class Label < Base #:nodoc: def initialize(object_name, method_name, template_object, content_or_options = nil, options = nil) + options ||= {} + content_is_options = content_or_options.is_a?(Hash) if content_is_options - options = content_or_options + options.merge! content_or_options @content = nil else @content = content_or_options end - options ||= {} - super(object_name, method_name, template_object, options) end @@ -33,7 +33,7 @@ module ActionView options["for"] = name_and_id["id"] unless options.key?("for") if block_given? - @template_object.label_tag(name_and_id["id"], options, &block) + content = @template_object.capture(&block) else content = if @content.blank? @object_name.gsub!(/\[(.*)_attributes\]\[\d\]/, '.\1') @@ -55,9 +55,9 @@ module ActionView end content ||= @method_name.humanize - - label_tag(name_and_id["id"], content, options) end + + label_tag(name_and_id["id"], content, options) end end end diff --git a/actionpack/lib/action_view/helpers/tags/month_field.rb b/actionpack/lib/action_view/helpers/tags/month_field.rb new file mode 100644 index 0000000000..3d3c32d847 --- /dev/null +++ b/actionpack/lib/action_view/helpers/tags/month_field.rb @@ -0,0 +1,13 @@ +module ActionView + module Helpers + module Tags + class MonthField < DatetimeField #:nodoc: + private + + def format_date(value) + value.try(:strftime, "%Y-%m") + end + end + end + end +end diff --git a/actionpack/lib/action_view/helpers/tags/number_field.rb b/actionpack/lib/action_view/helpers/tags/number_field.rb index e89fdbec46..9cd04434f0 100644 --- a/actionpack/lib/action_view/helpers/tags/number_field.rb +++ b/actionpack/lib/action_view/helpers/tags/number_field.rb @@ -4,7 +4,6 @@ module ActionView class NumberField < TextField #:nodoc: def render options = @options.stringify_keys - options['size'] ||= nil if range = options.delete("in") || options.delete("within") options.update("min" => range.min, "max" => range.max) diff --git a/actionpack/lib/action_view/helpers/tags/text_area.rb b/actionpack/lib/action_view/helpers/tags/text_area.rb index a7db8eb437..f74652c5e7 100644 --- a/actionpack/lib/action_view/helpers/tags/text_area.rb +++ b/actionpack/lib/action_view/helpers/tags/text_area.rb @@ -2,17 +2,15 @@ module ActionView module Helpers module Tags class TextArea < Base #:nodoc: - DEFAULT_TEXT_AREA_OPTIONS = { "cols" => 40, "rows" => 20 } - def render - options = DEFAULT_TEXT_AREA_OPTIONS.merge(@options.stringify_keys) + options = @options.stringify_keys add_default_name_and_id(options) if size = options.delete("size") options["cols"], options["rows"] = size.split("x") if size.respond_to?(:split) end - content_tag("textarea", ERB::Util.html_escape(options.delete('value') || value_before_type_cast(object)), options) + content_tag("textarea", options.delete('value') || value_before_type_cast(object), options) end end end diff --git a/actionpack/lib/action_view/helpers/tags/text_field.rb b/actionpack/lib/action_view/helpers/tags/text_field.rb index ce5182d20f..024a1a8af2 100644 --- a/actionpack/lib/action_view/helpers/tags/text_field.rb +++ b/actionpack/lib/action_view/helpers/tags/text_field.rb @@ -4,8 +4,7 @@ module ActionView class TextField < Base #:nodoc: def render options = @options.stringify_keys - options["size"] = options["maxlength"] || DEFAULT_FIELD_OPTIONS["size"] unless options.key?("size") - options = DEFAULT_FIELD_OPTIONS.merge(options) + options["size"] = options["maxlength"] unless options.key?("size") options["type"] ||= field_type options["value"] = options.fetch("value"){ value_before_type_cast(object) } unless field_type == "file" options["value"] &&= ERB::Util.html_escape(options["value"]) diff --git a/actionpack/lib/action_view/helpers/tags/time_field.rb b/actionpack/lib/action_view/helpers/tags/time_field.rb new file mode 100644 index 0000000000..a3941860c9 --- /dev/null +++ b/actionpack/lib/action_view/helpers/tags/time_field.rb @@ -0,0 +1,13 @@ +module ActionView + module Helpers + module Tags + class TimeField < DatetimeField #:nodoc: + private + + def format_date(value) + value.try(:strftime, "%T.%L") + end + end + end + end +end diff --git a/actionpack/lib/action_view/helpers/tags/week_field.rb b/actionpack/lib/action_view/helpers/tags/week_field.rb new file mode 100644 index 0000000000..1e13939a0a --- /dev/null +++ b/actionpack/lib/action_view/helpers/tags/week_field.rb @@ -0,0 +1,13 @@ +module ActionView + module Helpers + module Tags + class WeekField < DatetimeField #:nodoc: + private + + def format_date(value) + value.try(:strftime, "%Y-W%W") + end + end + end + end +end diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb index 3dc651501e..0f599d5f41 100644 --- a/actionpack/lib/action_view/helpers/text_helper.rb +++ b/actionpack/lib/action_view/helpers/text_helper.rb @@ -1,5 +1,5 @@ -require 'active_support/core_ext/object/blank' require 'active_support/core_ext/string/filters' +require 'active_support/core_ext/array/extract_options' module ActionView # = Action View Text Helpers @@ -36,7 +36,6 @@ module ActionView # do not operate as expected in an eRuby code block. If you absolutely must # output text within a non-output code block (i.e., <% %>), you can use the concat method. # - # ==== Examples # <% # concat "hello" # # is the equivalent of <%= "hello" %> @@ -44,7 +43,7 @@ module ActionView # if logged_in # concat "Logged in!" # else - # concat link_to('login', :action => login) + # concat link_to('login', :action => :login) # end # # will either display "Logged in!" or a login link # %> @@ -62,11 +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. # - # ==== Examples + # 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..." @@ -82,17 +81,25 @@ 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 = {}) - options.reverse_merge!(:length => 30) - text.truncate(options.delete(:length), 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 # a <tt>:highlighter</tt> string. The highlighter can be specialized by passing <tt>:highlighter</tt> - # as a single-quoted string with \1 where the phrase is to be inserted (defaults to + # as a single-quoted string with <tt>\1</tt> where the phrase is to be inserted (defaults to # '<mark>\1</mark>') # - # ==== Examples # highlight('You searched for: rails', 'rails') # # => You searched for: <mark>rails</mark> # @@ -104,23 +111,15 @@ module ActionView # # highlight('You searched for: rails', 'rails', :highlighter => '<a href="search?q=\1">\1</a>') # # => You searched for: <a href="search?q=rails">rails</a> - # - # You can still use <tt>highlight</tt> with the old API that accepts the - # +highlighter+ as its optional third parameter: - # highlight('You searched for: rails', 'rails', '<a href="search?q=\1">\1</a>') # => You searched for: <a href="search?q=rails">rails</a> - def highlight(text, phrases, *args) - options = args.extract_options! - unless args.empty? - options[:highlighter] = args[0] || '<mark>\1</mark>' - end - options.reverse_merge!(:highlighter => '<mark>\1</mark>') + def highlight(text, phrases, options = {}) + highlighter = options.fetch(:highlighter, '<mark>\1</mark>') - text = sanitize(text) unless options[:sanitize] == false + text = sanitize(text) if options.fetch(:sanitize, true) if text.blank? || phrases.blank? text else match = Array(phrases).map { |p| Regexp.escape(p) }.join('|') - text.gsub(/(#{match})(?![^<]*?>)/i, options[:highlighter]) + text.gsub(/(#{match})(?![^<]*?>)/i, highlighter) end.html_safe end @@ -130,7 +129,6 @@ module ActionView # then the <tt>:omission</tt> option (which defaults to "...") will be prepended/appended accordingly. The resulting string # will be stripped in any case. If the +phrase+ isn't found, nil is returned. # - # ==== Examples # excerpt('This is an example', 'an', :radius => 5) # # => ...s is an exam... # @@ -145,39 +143,27 @@ module ActionView # # excerpt('This is also an example', 'an', :radius => 8, :omission => '<chop> ') # # => <chop> is also an example - # - # You can still use <tt>excerpt</tt> with the old API that accepts the - # +radius+ as its optional third and the +ellipsis+ as its - # optional forth parameter: - # excerpt('This is an example', 'an', 5) # => ...s is an exam... - # excerpt('This is also an example', 'an', 8, '<chop> ') # => <chop> is also an example - def excerpt(text, phrase, *args) + def excerpt(text, phrase, options = {}) return unless text && phrase - - options = args.extract_options! - unless args.empty? - options[:radius] = args[0] || 100 - options[:omission] = args[1] || "..." - end - options.reverse_merge!(:radius => 100, :omission => "...") + radius = options.fetch(:radius, 100) + omission = options.fetch(:omission, "...") phrase = Regexp.escape(phrase) return unless found_pos = text =~ /(#{phrase})/i - start_pos = [ found_pos - options[:radius], 0 ].max - end_pos = [ [ found_pos + phrase.length + options[:radius] - 1, 0].max, text.length ].min + start_pos = [ found_pos - radius, 0 ].max + end_pos = [ [ found_pos + phrase.length + radius - 1, 0].max, text.length ].min - prefix = start_pos > 0 ? options[:omission] : "" - postfix = end_pos < text.length - 1 ? options[:omission] : "" + prefix = start_pos > 0 ? omission : "" + postfix = end_pos < text.length - 1 ? omission : "" prefix + text[start_pos..end_pos].strip + postfix end # Attempts to pluralize the +singular+ word unless +count+ is 1. If # +plural+ is supplied, it will use that when count is > 1, otherwise - # it will use the Inflector to determine the plural form + # it will use the Inflector to determine the plural form. # - # ==== Examples # pluralize(1, 'person') # # => 1 person # @@ -190,39 +176,35 @@ module ActionView # pluralize(0, 'person') # # => 0 people def pluralize(count, singular, plural = nil) - "#{count || 0} " + ((count == 1 || count =~ /^1(\.0+)?$/) ? singular : (plural || singular.pluralize)) + word = if (count == 1 || count =~ /^1(\.0+)?$/) + singular + else + plural || singular.pluralize + end + + "#{count || 0} #{word}" end # Wraps the +text+ into lines no longer than +line_width+ width. This method # breaks on the first whitespace character that does not exceed +line_width+ # (which is 80 by default). # - # ==== Examples - # # word_wrap('Once upon a time') # # => Once upon a time # # word_wrap('Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding a successor to the throne turned out to be more trouble than anyone could have imagined...') - # # => Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding\n a successor to the throne turned out to be more trouble than anyone could have\n imagined... + # # => Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding\na successor to the throne turned out to be more trouble than anyone could have\nimagined... # # word_wrap('Once upon a time', :line_width => 8) - # # => Once upon\na time + # # => Once\nupon a\ntime # # word_wrap('Once upon a time', :line_width => 1) # # => Once\nupon\na\ntime - # - # You can still use <tt>word_wrap</tt> with the old API that accepts the - # +line_width+ as its optional second parameter: - # word_wrap('Once upon a time', 8) # => Once upon\na time - def word_wrap(text, *args) - options = args.extract_options! - unless args.blank? - options[:line_width] = args[0] || 80 - end - options.reverse_merge!(:line_width => 80) + def word_wrap(text, options = {}) + line_width = options.fetch(:line_width, 80) text.split("\n").collect do |line| - line.length > options[:line_width] ? line.gsub(/(.{1,#{options[:line_width]}})(\s+|$)/, "\\1\n").strip : line + line.length > line_width ? line.gsub(/(.{1,#{line_width}})(\s+|$)/, "\\1\n").strip : line end * "\n" end @@ -237,6 +219,7 @@ module ActionView # # ==== Options # * <tt>:sanitize</tt> - If +false+, does not sanitize +text+. + # * <tt>:wrapper_tag</tt> - String representing the wrapper tag, defaults to <tt>"p"</tt> # # ==== Examples # my_text = "Here is some basic text...\n...with a line break." @@ -244,6 +227,9 @@ 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>" + # # more_text = "We want to put a paragraph...\n\n...right there." # # simple_format(more_text) @@ -254,17 +240,19 @@ module ActionView # # simple_format("<span>I'm allowed!</span> It's true.", {}, :sanitize => false) # # => "<p><span>I'm allowed!</span> It's true.</p>" - def simple_format(text, html_options={}, options={}) - text = '' if text.nil? - text = text.dup - start_tag = tag('p', html_options, true) - text = sanitize(text) unless options[:sanitize] == false - text = text.to_str - text.gsub!(/\r\n?/, "\n") # \r\n and \r -> \n - text.gsub!(/\n\n+/, "</p>\n\n#{start_tag}") # 2+ newline -> paragraph - text.gsub!(/([^\n]\n)(?=[^\n])/, '\1<br />') # 1 newline -> br - text.insert 0, start_tag - text.html_safe.safe_concat("</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) + + if paragraphs.empty? + content_tag(wrapper_tag, nil, html_options) + else + paragraphs.map { |paragraph| + content_tag(wrapper_tag, paragraph, html_options, options[:sanitize]) + }.join("\n\n").html_safe + end end # Creates a Cycle object whose _to_s_ method cycles through elements of an @@ -276,7 +264,6 @@ module ActionView # and passing the name of the cycle. The current cycle string can be obtained # anytime using the current_cycle method. # - # ==== Examples # # Alternate CSS classes for even and odd numbers... # @items = [1,2,3,4] # <table> @@ -306,12 +293,9 @@ module ActionView # </tr> # <% end %> def cycle(first_value, *values) - if (values.last.instance_of? Hash) - params = values.pop - name = params[:name] - else - name = "default" - end + options = values.extract_options! + name = options.fetch(:name, 'default') + values.unshift(first_value) cycle = get_cycle(name) @@ -325,7 +309,6 @@ module ActionView # for complex table highlighting or any other design need which requires # the current cycle string in more than one place. # - # ==== Example # # Alternate background colors # @items = [1,2,3,4] # <% @items.each do |item| %> @@ -341,7 +324,6 @@ module ActionView # Resets a cycle so that it starts from the first element the next time # it is called. Pass in +name+ to reset a named cycle. # - # ==== Example # # Alternate CSS classes for even and odd numbers... # @items = [[1,2,3,4], [5,6,3], [3,4,5,6,7,4]] # <table> @@ -412,6 +394,14 @@ module ActionView @_cycles = Hash.new unless defined?(@_cycles) @_cycles[name] = cycle_object end + + def split_paragraphs(text) + return [] if text.blank? + + text.to_str.gsub(/\r\n?/, "\n").split(/\n\n+/).map! do |t| + t.gsub!(/([^\n]\n)(?=[^\n])/, '\1<br />') || t + end + end end end end diff --git a/actionpack/lib/action_view/helpers/translation_helper.rb b/actionpack/lib/action_view/helpers/translation_helper.rb index cc74eff53a..552c9ba660 100644 --- a/actionpack/lib/action_view/helpers/translation_helper.rb +++ b/actionpack/lib/action_view/helpers/translation_helper.rb @@ -45,6 +45,7 @@ module ActionView # you know what kind of output to expect when you call translate in a template. def translate(key, options = {}) options.merge!(:rescue_format => :html) unless options.key?(:rescue_format) + options[:default] = wrap_translate_defaults(options[:default]) if options[:default] if html_safe_translation_key?(key) html_safe_options = options.dup options.except(*I18n::RESERVED_KEYS).each do |name, value| @@ -62,6 +63,9 @@ module ActionView alias :t :translate # Delegates to <tt>I18n.localize</tt> with no additional functionality. + # + # See http://rubydoc.info/github/svenfuchs/i18n/master/I18n/Backend/Base:localize + # for more information. def localize(*args) I18n.localize(*args) end @@ -83,6 +87,21 @@ module ActionView def html_safe_translation_key?(key) key.to_s =~ /(\b|_|\.)html$/ end + + def wrap_translate_defaults(defaults) + new_defaults = [] + defaults = Array(defaults) + while key = defaults.shift + if key.is_a?(Symbol) + new_defaults << lambda { |_, options| translate key, options.merge(:default => defaults) } + break + else + new_defaults << key + end + end + + new_defaults + end end end end diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb index b5fc882e31..3f65791aa0 100644 --- a/actionpack/lib/action_view/helpers/url_helper.rb +++ b/actionpack/lib/action_view/helpers/url_helper.rb @@ -2,7 +2,6 @@ require 'action_view/helpers/javascript_helper' require 'active_support/core_ext/array/access' require 'active_support/core_ext/hash/keys' require 'active_support/core_ext/string/output_safety' -require 'action_dispatch' module ActionView # = Action View URL Helpers @@ -20,98 +19,34 @@ module ActionView extend ActiveSupport::Concern - include ActionDispatch::Routing::UrlFor include TagHelper - def _routes_context - controller - end - - # Need to map default url options to controller one. - # def default_url_options(*args) #:nodoc: - # controller.send(:default_url_options, *args) - # end - # - def url_options - return super unless controller.respond_to?(:url_options) - controller.url_options + module ClassMethods + def _url_for_modules + ActionView::RoutingUrlFor + end end - # Returns the URL for the set of +options+ provided. This takes the - # same options as +url_for+ in Action Controller (see the - # documentation for <tt>ActionController::Base#url_for</tt>). Note that by default - # <tt>:only_path</tt> is <tt>true</tt> so you'll get the relative "/controller/action" - # instead of the fully qualified URL like "http://example.com/controller/action". - # - # ==== Options - # * <tt>:anchor</tt> - Specifies the anchor name to be appended to the path. - # * <tt>:only_path</tt> - If true, returns the relative URL (omitting the protocol, host name, and port) (<tt>true</tt> by default unless <tt>:host</tt> is specified). - # * <tt>:trailing_slash</tt> - If true, adds a trailing slash, as in "/archive/2005/". Note that this - # is currently not recommended since it breaks caching. - # * <tt>:host</tt> - Overrides the default (current) host if provided. - # * <tt>:protocol</tt> - Overrides the default (current) protocol if provided. - # * <tt>:user</tt> - Inline HTTP authentication (only plucked out if <tt>:password</tt> is also present). - # * <tt>:password</tt> - Inline HTTP authentication (only plucked out if <tt>:user</tt> is also present). - # - # ==== Relying on named routes - # - # Passing a record (like an Active Record or Active Resource) 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). - # - # ==== Examples - # <%= url_for(:action => 'index') %> - # # => /blog/ - # - # <%= url_for(:action => 'find', :controller => 'books') %> - # # => /books/find - # - # <%= url_for(:action => 'login', :controller => 'members', :only_path => false, :protocol => 'https') %> - # # => https://www.example.com/members/login/ - # - # <%= url_for(:action => 'play', :anchor => 'player') %> - # # => /messages/play/#player - # - # <%= url_for(:action => 'jump', :anchor => 'tax&ship') %> - # # => /testing/jump/#tax&ship - # - # <%= url_for(Workshop.new) %> - # # relies on Workshop answering a persisted? call (and in this case returning false) - # # => /workshops - # - # <%= url_for(@workshop) %> - # # calls @workshop.to_param which by default returns the id - # # => /workshops/5 - # - # # to_param can be re-defined in a model to provide different URL names: - # # => /workshops/1-workshop-name - # - # <%= url_for("http://www.example.com") %> - # # => http://www.example.com - # - # <%= url_for(:back) %> - # # if request.env["HTTP_REFERER"] is set to "http://www.example.com" - # # => http://www.example.com - # - # <%= url_for(:back) %> - # # if request.env["HTTP_REFERER"] is not set or is blank - # # => javascript:history.back() - def url_for(options = nil) + # Basic implementation of url_for to allow use helpers without routes existence + def url_for(options = nil) # :nodoc: case options when String options - when nil, Hash - options ||= {} - options = options.symbolize_keys.reverse_merge!(:only_path => options[:host].nil?) - super when :back - controller.request.env["HTTP_REFERER"] || 'javascript:history.back()' + _back_url else - polymorphic_path(options) + raise ArgumentError, "arguments passed to url_for can't be handled. Please require " + + "routes or provide your own implementation" end end + def _back_url # :nodoc: + referrer = controller.respond_to?(:request) && controller.request.env["HTTP_REFERER"] + referrer || 'javascript:history.back()' + end + protected :_back_url + + # Creates a link tag of the given +name+ using a URL created by the set of +options+. # See the valid options in the documentation for +url_for+. It's also possible to # pass a String instead of an options hash, which generates a link tag that uses the @@ -127,8 +62,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 @@ -139,25 +73,33 @@ 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 # in dangerous actions like deleting a record (which search bots can follow - # while spidering your site). Supported verbs are <tt>:post</tt>, <tt>:delete</tt> and <tt>:put</tt>. + # while spidering your site). Supported verbs are <tt>:post</tt>, <tt>:delete</tt>, <tt>:patch</tt>, and <tt>:put</tt>. # Note that if the user has JavaScript disabled, the request will fall back # to using GET. If <tt>:href => '#'</tt> is used and the user has JavaScript # disabled clicking the link will have no effect. If you are relying on the # POST behavior, you should check for it in your controller's action by using - # the request object's methods for <tt>post?</tt>, <tt>delete?</tt> or <tt>put?</tt>. + # the request object's methods for <tt>post?</tt>, <tt>delete?</tt>, <tt>:patch</tt>, or <tt>put?</tt>. # * <tt>:remote => true</tt> - This will allow the unobtrusive JavaScript # driver to make an Ajax request to the URL in question instead of following # the link. The drivers each provide mechanisms for listening for the # 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 @@ -221,32 +163,24 @@ module ActionView # link_to "Nonsense search", searches_path(:foo => "bar", :baz => "quux") # # => <a href="/searches?foo=bar&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 @@ -260,10 +194,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. # @@ -272,23 +205,41 @@ module ActionView # # There are a few special +html_options+: # * <tt>:method</tt> - Symbol of HTTP verb. Supported verbs are <tt>:post</tt>, <tt>:get</tt>, - # <tt>:delete</tt> and <tt>:put</tt>. By default it will be <tt>:post</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"> @@ -298,30 +249,39 @@ module ActionView # # <%= button_to "Create", :action => "create", :remote => true, :form => { "data-type" => "json" } %> # # => "<form method="post" action="/images/create" class="button_to" data-remote="true" data-type="json"> - # # <div><input value="Create" type="submit" /></div> + # # <div> + # # <input value="Create" type="submit" /> + # # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/> + # # </div> # # </form>" # # # <%= 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" /> - # # <input data-confirm='Are you sure?' value="Delete" type="submit" /> + # # <input data-confirm='Are you sure?' value="Delete Image" type="submit" /> + # # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/> # # </div> # # </form>" # # - # <%= button_to('Destroy', 'http://www.example.com', :confirm => 'Are you sure?', - # :method => "delete", :remote => true, :disable_with => 'loading...') %> + # <%= 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' disable_with='loading...' 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)) @@ -329,7 +289,7 @@ module ActionView remote = html_options.delete('remote') method = html_options.delete('method').to_s - method_tag = %w{put delete}.include?(method) ? method_tag(method) : "" + method_tag = %w{patch put delete}.include?(method) ? method_tag(method) : ''.html_safe form_method = method == 'get' ? 'get' : 'post' form_options = html_options.delete('form') || {} @@ -340,9 +300,17 @@ 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' - "#{tag(:form, form_options, true)}<div>#{method_tag}#{tag("input", html_options)}#{request_token_tag}</div></form>".html_safe + 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(button).safe_concat(request_token_tag) + content_tag('form', content_tag('div', inner_tags), form_options) end @@ -475,7 +443,7 @@ module ActionView # # => <a href="mailto:me@domain.com">me@domain.com</a> # # mail_to "me@domain.com", "My email", :encode => "javascript" - # # => <script type="text/javascript">eval(decodeURIComponent('%64%6f%63...%27%29%3b'))</script> + # # => <script>eval(decodeURIComponent('%64%6f%63...%27%29%3b'))</script> # # mail_to "me@domain.com", "My email", :encode => "hex" # # => <a href="mailto:%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">My email</a> @@ -509,7 +477,7 @@ module ActionView "document.write('#{html}');".each_byte do |c| string << sprintf("%%%x", c) end - "<script type=\"#{Mime::JS}\">eval(decodeURIComponent('#{string}'))</script>".html_safe + "<script>eval(decodeURIComponent('#{string}'))</script>".html_safe when "hex" email_address_encoded = email_address_obfuscated.unpack('C*').map {|c| sprintf("&#%d;", c) @@ -609,10 +577,20 @@ module ActionView confirm = html_options.delete('confirm') method = html_options.delete('method') - html_options["data-disable-with"] = disable_with if disable_with - 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'} : {} @@ -659,11 +637,11 @@ module ActionView end def token_tag(token=nil) - if token == false || !protect_against_forgery? - '' - else + if token != false && protect_against_forgery? token ||= form_authenticity_token tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => token) + else + '' end end diff --git a/actionpack/lib/action_view/locale/en.yml b/actionpack/lib/action_view/locale/en.yml index 7cca7d969a..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: @@ -147,15 +49,8 @@ # Default value for :prompt => true in FormOptionsHelper prompt: "Please select" - # Default translation keys for submit FormHelper + # Default translation keys for submit and button FormHelper submit: create: 'Create %{model}' update: 'Update %{model}' submit: 'Save %{model}' - - # Default translation keys for button FormHelper - button: - create: 'Create %{model}' - update: 'Update %{model}' - submit: 'Save %{model}' - diff --git a/actionpack/lib/action_view/lookup_context.rb b/actionpack/lib/action_view/lookup_context.rb index 90c4a2759a..af367ac28d 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 @@ -9,7 +8,7 @@ module ActionView # generate a key, given to view paths, used in the resolver cache lookup. Since # this key is generated just once during the request, it speeds up all cache accesses. class LookupContext #:nodoc: - attr_accessor :prefixes + attr_accessor :prefixes, :rendered_format mattr_accessor :fallbacks @@fallbacks = FallbackFileSystemResolver.instances @@ -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) @@ -44,7 +43,7 @@ module ActionView end register_detail(:locale) { [I18n.locale, I18n.default_locale].uniq } - register_detail(:formats) { Mime::SET.symbols } + register_detail(:formats) { ActionView::Base.default_formats || [:html, :text, :js, :css, :xml, :json] } register_detail(:handlers){ Template::Handlers.extensions } class DetailsKey #:nodoc: @@ -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. @@ -170,29 +169,24 @@ module ActionView def initialize(view_paths, details = {}, prefixes = []) @details, @details_key = {}, nil - @frozen_formats, @skip_default_locale = false, false + @skip_default_locale = false @cache = true @prefixes = prefixes + @rendered_format = nil self.view_paths = view_paths initialize_details(details) end - # Freeze the current formats in the lookup context. By freezing them, you - # that next template lookups are not going to modify the formats. The con - # use this, to ensure that formats won't be further modified (as it does - def freeze_formats(formats, unless_frozen=false) #:nodoc: - return if unless_frozen && @frozen_formats - self.formats = formats - @frozen_formats = true - end - # Override formats= to expand ["*/*"] values and automatically # add :html as fallback to :js. 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/model_naming.rb b/actionpack/lib/action_view/model_naming.rb new file mode 100644 index 0000000000..e09ebd60df --- /dev/null +++ b/actionpack/lib/action_view/model_naming.rb @@ -0,0 +1,12 @@ +module ActionView + 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_view/railtie.rb b/actionpack/lib/action_view/railtie.rb index 43371a1c49..2d36deaa78 100644 --- a/actionpack/lib/action_view/railtie.rb +++ b/actionpack/lib/action_view/railtie.rb @@ -7,6 +7,16 @@ module ActionView config.action_view = ActiveSupport::OrderedOptions.new config.action_view.stylesheet_expansions = {} config.action_view.javascript_expansions = { :defaults => %w(jquery jquery_ujs) } + config.action_view.embed_authenticity_token_in_remote_forms = false + + config.eager_load_namespaces << ActionView + + initializer "action_view.embed_authenticity_token_in_remote_forms" do |app| + ActiveSupport.on_load(:action_view) do + ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = + app.config.action_view.delete(:embed_authenticity_token_in_remote_forms) + end + end initializer "action_view.logger" do ActiveSupport.on_load(:action_view) { self.logger ||= Rails.logger } diff --git a/actionpack/lib/action_view/record_identifier.rb b/actionpack/lib/action_view/record_identifier.rb new file mode 100644 index 0000000000..2953654972 --- /dev/null +++ b/actionpack/lib/action_view/record_identifier.rb @@ -0,0 +1,84 @@ +require 'active_support/core_ext/module' +require 'action_view/model_naming' + +module ActionView + # The record identifier encapsulates a number of naming conventions for dealing with records, like Active Records or + # pretty much any other model type that has an id. These patterns are then used to try elevate the view actions to + # a higher logical level. + # + # # routes + # resources :posts + # + # # view + # <%= div_for(post) do %> <div id="post_45" class="post"> + # <%= post.body %> What a wonderful world! + # <% end %> </div> + # + # # controller + # def update + # post = Post.find(params[:id]) + # post.update_attributes(params[:post]) + # + # redirect_to(post) # Calls polymorphic_url(post) which in turn calls post_url(post) + # end + # + # As the example above shows, you can stop caring to a large extent what the actual id of the post is. + # You just know that one is being assigned and that the subsequent calls in redirect_to expect that + # same naming convention and allows you to write less code if you follow it. + module RecordIdentifier + extend self + extend ModelNaming + + include ModelNaming + + JOIN = '_'.freeze + NEW = 'new'.freeze + + # The DOM class convention is to use the singular form of an object or class. + # + # dom_class(post) # => "post" + # dom_class(Person) # => "person" + # + # If you need to address multiple instances of the same class in the same view, you can prefix the dom_class: + # + # dom_class(post, :edit) # => "edit_post" + # dom_class(Person, :edit) # => "edit_person" + def dom_class(record_or_class, prefix = nil) + singular = model_name_from_record_or_class(record_or_class).param_key + prefix ? "#{prefix}#{JOIN}#{singular}" : singular + end + + # The DOM id convention is to use the singular form of an object or class with the id following an underscore. + # If no id is found, prefix with "new_" instead. + # + # dom_id(Post.find(45)) # => "post_45" + # dom_id(Post.new) # => "new_post" + # + # If you need to address multiple instances of the same class in the same view, you can prefix the dom_id: + # + # dom_id(Post.find(45), :edit) # => "edit_post_45" + # dom_id(Post.new, :custom) # => "custom_post" + def dom_id(record, prefix = nil) + if record_id = record_key_for_dom_id(record) + "#{dom_class(record, prefix)}#{JOIN}#{record_id}" + else + dom_class(record, prefix || NEW) + end + end + + protected + + # Returns a string representation of the key attribute(s) that is suitable for use in an HTML DOM id. + # This can be overwritten to customize the default generated string representation if desired. + # If you need to read back a key from a dom_id in order to query for the underlying database record, + # you should write a helper like 'person_record_from_dom_id' that will extract the key either based + # on the default implementation (which just joins all key attributes with '_') or on your own + # overwritten version of the method. By default, this implementation passes the key string through a + # 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) + key = convert_to_model(record).to_key + key ? key.join('_') : key + end + end +end diff --git a/actionpack/lib/action_view/renderer/abstract_renderer.rb b/actionpack/lib/action_view/renderer/abstract_renderer.rb index a588abcee3..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, :freeze_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 @@ -14,16 +13,20 @@ module ActionView protected def extract_details(options) - details = {} - @lookup_context.registered_details.each do |key| + @lookup_context.registered_details.each_with_object({}) do |key, details| next unless value = options[key] details[key] = Array(value) end - details end 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 3033294883..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 @@ -32,7 +31,7 @@ module ActionView # # <%= render :partial => "account", :object => @buyer %> # - # would provide the +@buyer+ object to the partial, available under the local variable +account+ and is + # would provide the <tt>@buyer</tt> object to the partial, available under the local variable +account+ and is # equivalent to: # # <%= render :partial => "account", :locals => { :account => @buyer } %> @@ -158,6 +157,47 @@ module ActionView # Name: <%= user.name %> # </div> # + # If a collection is given, the layout will be rendered once for each item in + # the collection. Just think these two snippets have the same output: + # + # <%# app/views/users/_user.html.erb %> + # Name: <%= user.name %> + # + # <%# app/views/users/index.html.erb %> + # <%# This does not use layouts %> + # <ul> + # <% users.each do |user| -%> + # <li> + # <%= render :partial => "user", :locals => { :user => user } %> + # </li> + # <% end -%> + # </ul> + # + # <%# app/views/users/_li_layout.html.erb %> + # <li> + # <%= yield %> + # </li> + # + # <%# app/views/users/index.html.erb %> + # <ul> + # <%= render :partial => "user", :layout => "li_layout", :collection => users %> + # </ul> + # + # Given two users whose names are Alice and Bob, these snippets return: + # + # <ul> + # <li> + # Name: Alice + # </li> + # <li> + # Name: Bob + # </li> + # </ul> + # + # The current object being rendered, as well as the object_counter, will be + # available as local variables inside the layout template under the same names + # as available in the partial. + # # You can also apply a layout to a block within any template: # # <%# app/views/users/_chief.html.erb &> @@ -208,18 +248,25 @@ module ActionView # <%- end -%> # <% end %> class PartialRenderer < AbstractRenderer - PARTIAL_NAMES = Hash.new { |h,k| h[k] = {} } + PREFIXED_PARTIAL_NAMES = Hash.new { |h,k| h[k] = {} } def initialize(*) super @context_prefix = @lookup_context.prefixes.first - @partial_names = PARTIAL_NAMES[@context_prefix] end def render(context, options, block) setup(context, options, block) identifier = (@template = find_partial) ? @template.identifier : @path + @lookup_context.rendered_format ||= begin + if @template && @template.formats.present? + @template.formats.first + else + formats.first + end + end + if @collection instrument(:collection, :identifier => identifier || "collection", :count => @collection.size) do render_collection @@ -235,7 +282,7 @@ module ActionView return nil if @collection.blank? if @options.key?(:spacer_template) - spacer = find_template(@options[:spacer_template]).render(@view, @locals) + spacer = find_template(@options[:spacer_template], @locals.keys).render(@view, @locals) end result = @template ? collection_with_template : collection_without_template @@ -243,11 +290,11 @@ module ActionView end def render_partial - locals, view, block = @locals, @view, @block + view, locals, block = @view, @locals, @block object, as = @object, @variable if !block && (layout = @options[:layout]) - layout = find_template(layout) + layout = find_template(layout, @template_keys) end object ||= locals[as] @@ -272,6 +319,8 @@ module ActionView @block = block @details = extract_details(options) + prepend_formats(options[:formats]) + if String === partial @object = options[:object] @path = partial @@ -287,16 +336,16 @@ module ActionView end end - if @path - @variable, @variable_counter = retrieve_variable(@path) - else - paths.map! { |path| retrieve_variable(path).unshift(path) } + if as = options[:as] + raise_invalid_identifier(as) unless as.to_s =~ /\A[a-z_]\w*\z/ + as = as.to_sym 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 letter or underscore, " + - "and is followed by any combinations of letters, numbers, or underscores.") + if @path + @variable, @variable_counter = retrieve_variable(@path, as) + @template_keys = retrieve_template_keys + else + paths.map! { |path| retrieve_variable(path, as).unshift(path) } end self @@ -310,55 +359,55 @@ module ActionView end def collection_from_object - if @object.respond_to?(:to_ary) - @object.to_ary - end + @object.to_ary if @object.respond_to?(:to_ary) end def find_partial if path = @path - locals = @locals.keys - locals << @variable - locals << @variable_counter if @collection - find_template(path, locals) + find_template(path, @template_keys) end end - def find_template(path=@path, locals=@locals.keys) + def find_template(path, locals) prefixes = path.include?(?/) ? [] : @lookup_context.prefixes @lookup_context.find_template(path, prefixes, true, locals, @details) end def collection_with_template - segments, locals, template = [], @locals, @template + view, locals, template = @view, @locals, @template as, counter = @variable, @variable_counter - locals[counter] = -1 - - @collection.each do |object| - locals[counter] += 1 - locals[as] = object - segments << template.render(@view, locals) + if layout = @options[:layout] + layout = find_template(layout, @template_keys) end - segments + index = -1 + @collection.map do |object| + locals[as] = object + locals[counter] = (index += 1) + + content = template.render(view, locals) + content = layout.render(view, locals) { content } if layout + content + end end def collection_without_template - segments, locals, collection_data = [], @locals, @collection_data - index, template, cache = -1, nil, {} - keys = @locals.keys + view, locals, collection_data = @view, @locals, @collection_data + cache = {} + keys = @locals.keys - @collection.each_with_index do |object, i| - path, *data = collection_data[i] - template = (cache[path] ||= find_template(path, keys + data)) - locals[data[0]] = object - locals[data[1]] = (index += 1) - segments << template.render(@view, locals) - end + index = -1 + @collection.map do |object| + index += 1 + path, as, counter = collection_data[index] - @template = template - segments + locals[as] = object + locals[counter] = index + + template = (cache[path] ||= find_template(path, keys + [as, counter])) + template.render(view, locals) + end end def partial_path(object = @object) @@ -370,7 +419,15 @@ module ActionView raise ArgumentError.new("'#{object.inspect}' is not an ActiveModel-compatible object. It must implement :to_partial_path.") end - @partial_names[path] ||= merge_prefix_into_object_path(@context_prefix, path.dup) + if @view.prefix_partial_path_with_controller_namespace + prefixed_partial_names[path] ||= merge_prefix_into_object_path(@context_prefix, path.dup) + else + path + end + end + + def prefixed_partial_names + @prefixed_partial_names ||= PREFIXED_PARTIAL_NAMES[@context_prefix] end def merge_prefix_into_object_path(prefix, object_path) @@ -390,10 +447,29 @@ module ActionView end end - def retrieve_variable(path) - variable = @options[:as].try(:to_sym) || path[%r'_?(\w+)(\.\w+)*$', 1].to_sym + def retrieve_template_keys + keys = @locals.keys + keys << @variable + keys << @variable_counter if @collection + keys + end + + 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/streaming_template_renderer.rb b/actionpack/lib/action_view/renderer/streaming_template_renderer.rb index f46aabd2be..9cf6eb0c65 100644 --- a/actionpack/lib/action_view/renderer/streaming_template_renderer.rb +++ b/actionpack/lib/action_view/renderer/streaming_template_renderer.rb @@ -30,7 +30,7 @@ module ActionView # This is the same logging logic as in ShowExceptions middleware. # TODO Once "exceptron" is in, refactor this piece to simply re-use exceptron. def log_error(exception) #:nodoc: - logger = ActionController::Base.logger + logger = ActionView::Base.logger return unless logger message = "\n#{exception.class} (#{exception.message}):\n" diff --git a/actionpack/lib/action_view/renderer/template_renderer.rb b/actionpack/lib/action_view/renderer/template_renderer.rb index f3abc6d533..156ad4e547 100644 --- a/actionpack/lib/action_view/renderer/template_renderer.rb +++ b/actionpack/lib/action_view/renderer/template_renderer.rb @@ -6,16 +6,23 @@ module ActionView @view = context @details = extract_details(options) template = determine_template(options) - freeze_formats(template.formats, true) + context = @lookup_context + + prepend_formats(template.formats) + + unless context.rendered_format + context.rendered_format = template.formats.first || formats.last + end + render_template(template, options[:layout], options[:locals]) end # 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) @@ -29,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/routing_url_for.rb b/actionpack/lib/action_view/routing_url_for.rb new file mode 100644 index 0000000000..d1488e2332 --- /dev/null +++ b/actionpack/lib/action_view/routing_url_for.rb @@ -0,0 +1,107 @@ +module ActionView + module RoutingUrlFor + + # Returns the URL for the set of +options+ provided. This takes the + # same options as +url_for+ in Action Controller (see the + # documentation for <tt>ActionController::Base#url_for</tt>). Note that by default + # <tt>:only_path</tt> is <tt>true</tt> so you'll get the relative "/controller/action" + # instead of the fully qualified URL like "http://example.com/controller/action". + # + # ==== Options + # * <tt>:anchor</tt> - Specifies the anchor name to be appended to the path. + # * <tt>:only_path</tt> - If true, returns the relative URL (omitting the protocol, host name, and port) (<tt>true</tt> by default unless <tt>:host</tt> is specified). + # * <tt>:trailing_slash</tt> - If true, adds a trailing slash, as in "/archive/2005/". Note that this + # is currently not recommended since it breaks caching. + # * <tt>:host</tt> - Overrides the default (current) host if provided. + # * <tt>:protocol</tt> - Overrides the default (current) protocol if provided. + # * <tt>:user</tt> - Inline HTTP authentication (only plucked out if <tt>:password</tt> is also present). + # * <tt>:password</tt> - Inline HTTP authentication (only plucked out if <tt>:user</tt> is also present). + # + # ==== Relying on named routes + # + # 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/ + # + # <%= url_for(:action => 'find', :controller => 'books') %> + # # => /books/find + # + # <%= url_for(:action => 'login', :controller => 'members', :only_path => false, :protocol => 'https') %> + # # => https://www.example.com/members/login/ + # + # <%= url_for(:action => 'play', :anchor => 'player') %> + # # => /messages/play/#player + # + # <%= url_for(:action => 'jump', :anchor => 'tax&ship') %> + # # => /testing/jump/#tax&ship + # + # <%= url_for(Workshop.new) %> + # # relies on Workshop answering a persisted? call (and in this case returning false) + # # => /workshops + # + # <%= url_for(@workshop) %> + # # calls @workshop.to_param which by default returns the id + # # => /workshops/5 + # + # # to_param can be re-defined in a model to provide different URL names: + # # => /workshops/1-workshop-name + # + # <%= url_for("http://www.example.com") %> + # # => http://www.example.com + # + # <%= url_for(:back) %> + # # if request.env["HTTP_REFERER"] is set to "http://www.example.com" + # # => http://www.example.com + # + # <%= 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 + options + when nil, Hash + options ||= {} + options = { :only_path => options[:host].nil? }.merge!(options.symbolize_keys) + super + when :back + _back_url + else + polymorphic_path(options) + end + end + + def url_options #:nodoc: + return super unless controller.respond_to?(:url_options) + controller.url_options + end + + def _routes_context #:nodoc: + controller + end + protected :_routes_context + + def optimize_routes_generation? #:nodoc: + controller.respond_to?(:optimize_routes_generation?, true) ? + controller.optimize_routes_generation? : super + end + protected :optimize_routes_generation? + end +end diff --git a/actionpack/lib/action_view/template.rb b/actionpack/lib/action_view/template.rb index edb3d427d5..379cdc8a25 100644 --- a/actionpack/lib/action_view/template.rb +++ b/actionpack/lib/action_view/template.rb @@ -1,6 +1,7 @@ -require 'active_support/core_ext/object/blank' require 'active_support/core_ext/object/try' require 'active_support/core_ext/kernel/singleton_class' +require 'active_support/deprecation' +require 'thread' module ActionView # = Action View Template @@ -92,6 +93,7 @@ module ActionView autoload :Error autoload :Handlers autoload :Text + autoload :Types end extend Template::Handlers @@ -121,7 +123,8 @@ module ActionView @locals = details[:locals] || [] @virtual_path = details[:virtual_path] @updated_at = details[:updated_at] || Time.now - @formats = Array(format).map { |f| f.is_a?(Mime::Type) ? f.ref : f } + @formats = Array(format).map { |f| f.respond_to?(:ref) ? f.ref : f } + @compile_mutex = Mutex.new end # Returns if the underlying handler supports streaming. If so, @@ -146,9 +149,14 @@ module ActionView end def mime_type + ActiveSupport::Deprecation.warn 'Template#mime_type is deprecated and will be removed in Rails 4.1. Please use type method instead.' @mime_type ||= Mime::Type.lookup_by_extension(@formats.first.to_s) if @formats.first end + def type + @type ||= Types[@formats.first] if @formats.first + end + # Receives a view object and return a template similar to self by using @virtual_path. # # This method is useful if you have a template object but it does not contain its source @@ -223,18 +231,28 @@ module ActionView def compile!(view) #:nodoc: return if @compiled - if view.is_a?(ActionView::CompiledTemplates) - mod = ActionView::CompiledTemplates - else - mod = view.singleton_class - end + # Templates can be used concurrently in threaded environments + # so compilation and any instance variable modification must + # be synchronized + @compile_mutex.synchronize do + # Any thread holding this lock will be compiling the template needed + # by the threads waiting. So re-check the @compiled flag to avoid + # re-compilation + return if @compiled + + if view.is_a?(ActionView::CompiledTemplates) + mod = ActionView::CompiledTemplates + else + mod = view.singleton_class + end - compile(view, mod) + compile(view, mod) - # Just discard the source if we have a virtual path. This - # means we can get the template back. - @source = nil if @virtual_path - @compiled = true + # Just discard the source if we have a virtual path. This + # means we can get the template back. + @source = nil if @virtual_path + @compiled = true + end end # Among other things, this method is responsible for properly setting diff --git a/actionpack/lib/action_view/template/error.rb b/actionpack/lib/action_view/template/error.rb index d8258f7b11..e00056781d 100644 --- a/actionpack/lib/action_view/template/error.rb +++ b/actionpack/lib/action_view/template/error.rb @@ -8,6 +8,9 @@ module ActionView class EncodingError < StandardError #:nodoc: end + class MissingRequestError < StandardError #:nodoc: + end + class WrongEncodingError < EncodingError #:nodoc: def initialize(string, encoding) @string, @encoding = string, encoding @@ -84,13 +87,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.rb b/actionpack/lib/action_view/template/handlers.rb index 67978ada7e..41b14373a3 100644 --- a/actionpack/lib/action_view/template/handlers.rb +++ b/actionpack/lib/action_view/template/handlers.rb @@ -4,10 +4,12 @@ module ActionView #:nodoc: module Handlers #:nodoc: autoload :ERB, 'action_view/template/handlers/erb' autoload :Builder, 'action_view/template/handlers/builder' + autoload :Raw, 'action_view/template/handlers/raw' def self.extended(base) base.register_default_template_handler :erb, ERB.new base.register_template_handler :builder, Builder.new + base.register_template_handler :raw, Raw.new end @@template_handlers = {} @@ -23,6 +25,7 @@ module ActionView #:nodoc: # and should return the rendered template as a String. def register_template_handler(extension, handler) @@template_handlers[extension.to_sym] = handler + @@template_extensions = nil end def template_handler_extensions diff --git a/actionpack/lib/action_view/template/handlers/builder.rb b/actionpack/lib/action_view/template/handlers/builder.rb index 34397c3bcf..d90b0c6378 100644 --- a/actionpack/lib/action_view/template/handlers/builder.rb +++ b/actionpack/lib/action_view/template/handlers/builder.rb @@ -3,7 +3,7 @@ module ActionView class Builder # Default format used by Builder. class_attribute :default_format - self.default_format = Mime::XML + self.default_format = :xml def call(template) require_engine diff --git a/actionpack/lib/action_view/template/handlers/erb.rb b/actionpack/lib/action_view/template/handlers/erb.rb index 323df67c97..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 @@ -44,10 +43,6 @@ module ActionView class_attribute :erb_trim_mode self.erb_trim_mode = '-' - # Default format used by ERB. - class_attribute :default_format - self.default_format = Mime::HTML - # Default implementation used. class_attribute :erb_implementation self.erb_implementation = Erubis diff --git a/actionpack/lib/action_view/template/handlers/raw.rb b/actionpack/lib/action_view/template/handlers/raw.rb new file mode 100644 index 0000000000..0c0d1fffcb --- /dev/null +++ b/actionpack/lib/action_view/template/handlers/raw.rb @@ -0,0 +1,11 @@ +module ActionView + module Template::Handlers + class Raw + def call(template) + escaped = template.source.gsub(':', '\:') + + '%q:' + escaped + ':;' + end + end + end +end diff --git a/actionpack/lib/action_view/template/resolver.rb b/actionpack/lib/action_view/template/resolver.rb index 7fa86866a7..25c6fd4aa8 100644 --- a/actionpack/lib/action_view/template/resolver.rb +++ b/actionpack/lib/action_view/template/resolver.rb @@ -1,12 +1,15 @@ 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 @@ -18,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 @@ -31,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. @@ -64,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 @@ -170,13 +232,15 @@ module ActionView def extract_handler_and_format(path, default_formats) pieces = File.basename(path).split(".") pieces.shift - handler = Template.handler_for_extension(pieces.pop) - format = pieces.last && Mime[pieces.last] + extension = pieces.pop + ActiveSupport::Deprecation.warn "The file #{path} did not specify a template handler. The default is currently ERB, but will change to RAW in the future." unless extension + handler = Template.handler_for_extension(extension) + format = pieces.last && Template::Types[pieces.last] [handler, format] end end - # A resolver that loads files from the filesystem. It allows to set your own + # A resolver that loads files from the filesystem. It allows setting your own # resolving pattern. Such pattern can be a glob string supported by some variables. # # ==== Examples @@ -192,7 +256,7 @@ module ActionView # # FileSystemResolver.new("/path/to/views", ":prefix/{:formats/,}:action{.:locale,}{.:formats,}{.:handlers,}") # - # If you don't specify pattern then the default will be used. + # If you don't specify a pattern then the default will be used. # # In order to use any of the customized resolvers above in a Rails application, you just need # to configure ActionController::Base.view_paths in an initializer, for example: @@ -204,10 +268,10 @@ module ActionView # # ==== Pattern format and variables # - # Pattern have to be a valid glob string, and it allows you to use the + # Pattern has to be a valid glob string, and it allows you to use the # following variables: # - # * <tt>:prefix</tt> - usualy the controller path + # * <tt>:prefix</tt> - usually the controller path # * <tt>:action</tt> - name of the action # * <tt>:locale</tt> - possible locale versions # * <tt>:formats</tt> - possible request formats (for example html, json, xml...) diff --git a/actionpack/lib/action_view/template/text.rb b/actionpack/lib/action_view/template/text.rb index 4261c3b5e2..859c7bc3ce 100644 --- a/actionpack/lib/action_view/template/text.rb +++ b/actionpack/lib/action_view/template/text.rb @@ -1,13 +1,13 @@ module ActionView #:nodoc: # = Action View Text Template class Template - class Text < String #:nodoc: - attr_accessor :mime_type + class Text #:nodoc: + attr_accessor :type - def initialize(string, mime_type = nil) - super(string.to_s) - @mime_type = Mime[mime_type] || mime_type if mime_type - @mime_type ||= Mime::TEXT + def initialize(string, type = nil) + @string = string.to_s + @type = Types[type] || type if type + @type ||= Types[:text] end def identifier @@ -18,12 +18,16 @@ module ActionView #:nodoc: 'text template' end + def to_str + @string + end + def render(*args) - to_s + to_str end def formats - [@mime_type.to_sym] + [@type.to_sym] end end end diff --git a/actionpack/lib/action_view/template/types.rb b/actionpack/lib/action_view/template/types.rb new file mode 100644 index 0000000000..7611c9e708 --- /dev/null +++ b/actionpack/lib/action_view/template/types.rb @@ -0,0 +1,58 @@ +require 'set' +require 'active_support/core_ext/class/attribute_accessors' +require 'active_support/core_ext/object/blank' + +module ActionView + class Template + class Types + class Type + cattr_accessor :types + self.types = Set.new + + def self.register(*t) + types.merge(t.map { |type| type.to_s }) + end + + register :html, :text, :js, :css, :xml, :json + + def self.[](type) + return type if type.is_a?(self) + + if type.is_a?(Symbol) || types.member?(type.to_s) + new(type) + end + end + + attr_reader :symbol + + def initialize(symbol) + @symbol = symbol.to_sym + end + + delegate :to_s, :to_sym, :to => :symbol + alias to_str to_s + + def ref + to_sym || to_s + end + + def ==(type) + return false if type.blank? + symbol.to_sym == type.to_sym + end + end + + cattr_accessor :type_klass + + def self.delegate_to(klass) + self.type_klass = klass + end + + delegate_to Type + + def self.[](type) + type_klass[type] + end + end + end +end diff --git a/actionpack/lib/action_view/test_case.rb b/actionpack/lib/action_view/test_case.rb index fece499c94..434fc8cc14 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' @@ -40,10 +38,11 @@ module ActionView include ActionView::Context include ActionDispatch::Routing::PolymorphicRoutes - include ActionController::RecordIdentifier include AbstractController::Helpers include ActionView::Helpers + include ActionView::RecordIdentifier + include ActionView::RoutingUrlFor delegate :lookup_context, :to => :controller attr_accessor :controller, :output_buffer, :rendered @@ -229,7 +228,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 diff --git a/actionpack/lib/action_view/vendor/html-scanner.rb b/actionpack/lib/action_view/vendor/html-scanner.rb new file mode 100644 index 0000000000..879b31e60e --- /dev/null +++ b/actionpack/lib/action_view/vendor/html-scanner.rb @@ -0,0 +1,20 @@ +$LOAD_PATH << "#{File.dirname(__FILE__)}/html-scanner" + +module HTML + extend ActiveSupport::Autoload + + eager_autoload do + autoload :CDATA, 'html/node' + autoload :Document, 'html/document' + autoload :FullSanitizer, 'html/sanitizer' + autoload :LinkSanitizer, 'html/sanitizer' + autoload :Node, 'html/node' + autoload :Sanitizer, 'html/sanitizer' + autoload :Selector, 'html/selector' + autoload :Tag, 'html/node' + autoload :Text, 'html/node' + autoload :Tokenizer, 'html/tokenizer' + autoload :Version, 'html/version' + autoload :WhiteListSanitizer, 'html/sanitizer' + end +end diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/document.rb b/actionpack/lib/action_view/vendor/html-scanner/html/document.rb index 386820300a..386820300a 100644 --- a/actionpack/lib/action_controller/vendor/html-scanner/html/document.rb +++ b/actionpack/lib/action_view/vendor/html-scanner/html/document.rb diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/node.rb b/actionpack/lib/action_view/vendor/html-scanner/html/node.rb index 4e1f016431..4e1f016431 100644 --- a/actionpack/lib/action_controller/vendor/html-scanner/html/node.rb +++ b/actionpack/lib/action_view/vendor/html-scanner/html/node.rb diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb b/actionpack/lib/action_view/vendor/html-scanner/html/sanitizer.rb index 24ffc28710..6b4ececda2 100644 --- a/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb +++ b/actionpack/lib/action_view/vendor/html-scanner/html/sanitizer.rb @@ -1,10 +1,11 @@ require 'set' require 'cgi' -require 'active_support/core_ext/class/attribute' +require 'active_support/core_ext/class/attribute_accessors' module HTML class Sanitizer def sanitize(text, options = {}) + validate_options(options) return text unless sanitizeable?(text) tokenize(text, options).join end @@ -27,6 +28,16 @@ module HTML def process_node(node, result, options) result << node.to_s end + + def validate_options(options) + if options[:tags] && !options[:tags].is_a?(Enumerable) + raise ArgumentError, "You should pass :tags as an Enumerable" + end + + if options[:attributes] && !options[:attributes].is_a?(Enumerable) + raise ArgumentError, "You should pass :attributes as an Enumerable" + end + end end class FullSanitizer < Sanitizer @@ -88,7 +99,7 @@ module HTML self.allowed_protocols = Set.new(%w(ed2k ftp http https irc mailto news gopher nntp telnet webcal xmpp callto feed svn urn aim rsync tag ssh sftp rtsp afs)) - # Specifies the default Set of acceptable css keywords that #sanitize and #sanitize_css will accept. + # Specifies the default Set of acceptable css properties that #sanitize and #sanitize_css will accept. self.allowed_css_properties = Set.new(%w(azimuth background-color border-bottom-color border-collapse border-color border-left-color border-right-color border-top-color clear color cursor direction display elevation float font font-family font-size font-style font-variant font-weight height letter-spacing line-height diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/selector.rb b/actionpack/lib/action_view/vendor/html-scanner/html/selector.rb index 1eadfc0390..1eadfc0390 100644 --- a/actionpack/lib/action_controller/vendor/html-scanner/html/selector.rb +++ b/actionpack/lib/action_view/vendor/html-scanner/html/selector.rb diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/tokenizer.rb b/actionpack/lib/action_view/vendor/html-scanner/html/tokenizer.rb index 8ac8d34430..8ac8d34430 100644 --- a/actionpack/lib/action_controller/vendor/html-scanner/html/tokenizer.rb +++ b/actionpack/lib/action_view/vendor/html-scanner/html/tokenizer.rb diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/version.rb b/actionpack/lib/action_view/vendor/html-scanner/html/version.rb index 6d645c3e14..6d645c3e14 100644 --- a/actionpack/lib/action_controller/vendor/html-scanner/html/version.rb +++ b/actionpack/lib/action_view/vendor/html-scanner/html/version.rb diff --git a/actionpack/lib/sprockets/assets.rake b/actionpack/lib/sprockets/assets.rake deleted file mode 100644 index 2e92fe416b..0000000000 --- a/actionpack/lib/sprockets/assets.rake +++ /dev/null @@ -1,105 +0,0 @@ -require "fileutils" - -namespace :assets do - def ruby_rake_task(task, fork = true) - env = ENV['RAILS_ENV'] || 'production' - groups = ENV['RAILS_GROUPS'] || 'assets' - args = [$0, task,"RAILS_ENV=#{env}","RAILS_GROUPS=#{groups}"] - args << "--trace" if Rake.application.options.trace - if $0 =~ /rake\.bat\Z/i - Kernel.exec $0, *args - else - fork ? ruby(*args) : Kernel.exec(FileUtils::RUBY, *args) - end - end - - # We are currently running with no explicit bundler group - # and/or no explicit environment - we have to reinvoke rake to - # execute this task. - def invoke_or_reboot_rake_task(task) - if ENV['RAILS_GROUPS'].to_s.empty? || ENV['RAILS_ENV'].to_s.empty? - ruby_rake_task task - else - Rake::Task[task].invoke - end - end - - desc "Compile all the assets named in config.assets.precompile" - task :precompile do - invoke_or_reboot_rake_task "assets:precompile:all" - end - - namespace :precompile do - def internal_precompile(digest=nil) - unless Rails.application.config.assets.enabled - warn "Cannot precompile assets if sprockets is disabled. Please set config.assets.enabled to true" - exit - end - - # Ensure that action view is loaded and the appropriate - # sprockets hooks get executed - _ = ActionView::Base - - config = Rails.application.config - config.assets.compile = true - config.assets.digest = digest unless digest.nil? - config.assets.digests = {} - - env = Rails.application.assets - target = File.join(Rails.public_path, config.assets.prefix) - compiler = Sprockets::StaticCompiler.new(env, - target, - config.assets.precompile, - :manifest_path => config.assets.manifest, - :digest => config.assets.digest, - :manifest => digest.nil?) - compiler.compile - end - - task :all do - Rake::Task["assets:precompile:primary"].invoke - # We need to reinvoke in order to run the secondary digestless - # asset compilation run - a fresh Sprockets environment is - # required in order to compile digestless assets as the - # environment has already cached the assets on the primary - # run. - ruby_rake_task("assets:precompile:nondigest", false) if Rails.application.config.assets.digest - end - - task :primary => ["assets:cache:clean"] do - internal_precompile - end - - task :nondigest => ["assets:cache:clean"] do - internal_precompile(false) - end - end - - desc "Remove compiled assets" - task :clean do - invoke_or_reboot_rake_task "assets:clean:all" - end - - namespace :clean do - task :all => ["assets:cache:clean"] do - config = Rails.application.config - public_asset_path = File.join(Rails.public_path, config.assets.prefix) - rm_rf public_asset_path, :secure => true - end - end - - namespace :cache do - task :clean => ["assets:environment"] do - Rails.application.assets.cache.clear - end - end - - task :environment do - if Rails.application.config.assets.initialize_on_precompile - Rake::Task["environment"].invoke - else - Rails.application.initialize!(:assets) - Sprockets::Bootstrap.new(Rails.application).run - end - end -end diff --git a/actionpack/lib/sprockets/bootstrap.rb b/actionpack/lib/sprockets/bootstrap.rb deleted file mode 100644 index 395b264fe7..0000000000 --- a/actionpack/lib/sprockets/bootstrap.rb +++ /dev/null @@ -1,37 +0,0 @@ -module Sprockets - class Bootstrap - def initialize(app) - @app = app - end - - # TODO: Get rid of config.assets.enabled - def run - app, config = @app, @app.config - return unless app.assets - - config.assets.paths.each { |path| app.assets.append_path(path) } - - if config.assets.compress - # temporarily hardcode default JS compressor to uglify. Soon, it will work - # the same as SCSS, where a default plugin sets the default. - unless config.assets.js_compressor == false - app.assets.js_compressor = LazyCompressor.new { Sprockets::Compressors.registered_js_compressor(config.assets.js_compressor || :uglifier) } - end - - unless config.assets.css_compressor == false - app.assets.css_compressor = LazyCompressor.new { Sprockets::Compressors.registered_css_compressor(config.assets.css_compressor) } - end - end - - if config.assets.compile - app.routes.prepend do - mount app.assets => config.assets.prefix - end - end - - if config.assets.digest - app.assets = app.assets.index - end - end - end -end diff --git a/actionpack/lib/sprockets/compressors.rb b/actionpack/lib/sprockets/compressors.rb deleted file mode 100644 index cb3e13314b..0000000000 --- a/actionpack/lib/sprockets/compressors.rb +++ /dev/null @@ -1,83 +0,0 @@ -module Sprockets - module Compressors - @@css_compressors = {} - @@js_compressors = {} - @@default_css_compressor = nil - @@default_js_compressor = nil - - def self.register_css_compressor(name, klass, options = {}) - @@default_css_compressor = name.to_sym if options[:default] || @@default_css_compressor.nil? - @@css_compressors[name.to_sym] = {:klass => klass.to_s, :require => options[:require]} - end - - def self.register_js_compressor(name, klass, options = {}) - @@default_js_compressor = name.to_sym if options[:default] || @@default_js_compressor.nil? - @@js_compressors[name.to_sym] = {:klass => klass.to_s, :require => options[:require]} - end - - def self.registered_css_compressor(name) - if name.respond_to?(:to_sym) - compressor = @@css_compressors[name.to_sym] || @@css_compressors[@@default_css_compressor] - require compressor[:require] if compressor[:require] - compressor[:klass].constantize.new - else - name - end - end - - def self.registered_js_compressor(name) - if name.respond_to?(:to_sym) - compressor = @@js_compressors[name.to_sym] || @@js_compressors[@@default_js_compressor] - require compressor[:require] if compressor[:require] - compressor[:klass].constantize.new - else - name - end - end - - # The default compressors must be registered in default plugins (ex. Sass-Rails) - register_css_compressor(:scss, 'Sass::Rails::Compressor', :require => 'sass/rails/compressor', :default => true) - register_js_compressor(:uglifier, 'Uglifier', :require => 'uglifier', :default => true) - - # Automaticaly register some compressors - register_css_compressor(:yui, 'YUI::CssCompressor', :require => 'yui/compressor') - register_js_compressor(:closure, 'Closure::Compiler', :require => 'closure-compiler') - register_js_compressor(:yui, 'YUI::JavaScriptCompressor', :require => 'yui/compressor') - end - - # An asset compressor which does nothing. - # - # This compressor simply returns the asset as-is, without any compression - # whatsoever. It is useful in development mode, when compression isn't - # needed but using the same asset pipeline as production is desired. - class NullCompressor #:nodoc: - def compress(content) - content - end - end - - # An asset compressor which only initializes the underlying compression - # engine when needed. - # - # This postpones the initialization of the compressor until - # <code>#compress</code> is called the first time. - class LazyCompressor #:nodoc: - # Initializes a new LazyCompressor. - # - # The block should return a compressor when called, i.e. an object - # which responds to <code>#compress</code>. - def initialize(&block) - @block = block - end - - def compress(content) - compressor.compress(content) - end - - private - - def compressor - @compressor ||= (@block.call || NullCompressor.new) - end - end -end diff --git a/actionpack/lib/sprockets/helpers.rb b/actionpack/lib/sprockets/helpers.rb deleted file mode 100644 index fee48386e0..0000000000 --- a/actionpack/lib/sprockets/helpers.rb +++ /dev/null @@ -1,6 +0,0 @@ -module Sprockets - module Helpers - autoload :RailsHelper, "sprockets/helpers/rails_helper" - autoload :IsolatedHelper, "sprockets/helpers/isolated_helper" - end -end diff --git a/actionpack/lib/sprockets/helpers/isolated_helper.rb b/actionpack/lib/sprockets/helpers/isolated_helper.rb deleted file mode 100644 index 3adb928c45..0000000000 --- a/actionpack/lib/sprockets/helpers/isolated_helper.rb +++ /dev/null @@ -1,13 +0,0 @@ -module Sprockets - module Helpers - module IsolatedHelper - def controller - nil - end - - def config - Rails.application.config.action_controller - end - end - end -end diff --git a/actionpack/lib/sprockets/helpers/rails_helper.rb b/actionpack/lib/sprockets/helpers/rails_helper.rb deleted file mode 100644 index 976ae5a76d..0000000000 --- a/actionpack/lib/sprockets/helpers/rails_helper.rb +++ /dev/null @@ -1,167 +0,0 @@ -require "action_view" - -module Sprockets - module Helpers - module RailsHelper - extend ActiveSupport::Concern - include ActionView::Helpers::AssetTagHelper - - def asset_paths - @asset_paths ||= begin - paths = RailsHelper::AssetPaths.new(config, controller) - paths.asset_environment = asset_environment - paths.asset_digests = asset_digests - paths.compile_assets = compile_assets? - paths.digest_assets = digest_assets? - paths - end - end - - def javascript_include_tag(*sources) - options = sources.extract_options! - debug = options.key?(:debug) ? options.delete(:debug) : debug_assets? - body = options.key?(:body) ? options.delete(:body) : false - digest = options.key?(:digest) ? options.delete(:digest) : digest_assets? - - sources.collect do |source| - if debug && asset = asset_paths.asset_for(source, 'js') - asset.to_a.map { |dep| - super(dep.pathname.to_s, { :src => path_to_asset(dep, :ext => 'js', :body => true, :digest => digest) }.merge!(options)) - } - else - super(source.to_s, { :src => path_to_asset(source, :ext => 'js', :body => body, :digest => digest) }.merge!(options)) - end - end.join("\n").html_safe - end - - def stylesheet_link_tag(*sources) - options = sources.extract_options! - debug = options.key?(:debug) ? options.delete(:debug) : debug_assets? - body = options.key?(:body) ? options.delete(:body) : false - digest = options.key?(:digest) ? options.delete(:digest) : digest_assets? - - sources.collect do |source| - if debug && asset = asset_paths.asset_for(source, 'css') - asset.to_a.map { |dep| - super(dep.pathname.to_s, { :href => path_to_asset(dep, :ext => 'css', :body => true, :protocol => :request, :digest => digest) }.merge!(options)) - } - else - super(source.to_s, { :href => path_to_asset(source, :ext => 'css', :body => body, :protocol => :request, :digest => digest) }.merge!(options)) - end - end.join("\n").html_safe - end - - def asset_path(source, options = {}) - source = source.logical_path if source.respond_to?(:logical_path) - path = asset_paths.compute_public_path(source, asset_prefix, options.merge(:body => true)) - options[:body] ? "#{path}?body=1" : path - end - alias_method :path_to_asset, :asset_path # aliased to avoid conflicts with an asset_path named route - - def image_path(source) - path_to_asset(source) - end - alias_method :path_to_image, :image_path # aliased to avoid conflicts with an image_path named route - - def font_path(source) - path_to_asset(source) - end - alias_method :path_to_font, :font_path # aliased to avoid conflicts with an font_path named route - - def javascript_path(source) - path_to_asset(source, :ext => 'js') - end - alias_method :path_to_javascript, :javascript_path # aliased to avoid conflicts with an javascript_path named route - - def stylesheet_path(source) - path_to_asset(source, :ext => 'css') - end - alias_method :path_to_stylesheet, :stylesheet_path # aliased to avoid conflicts with an stylesheet_path named route - - private - def debug_assets? - compile_assets? && (Rails.application.config.assets.debug || params[:debug_assets]) - rescue NoMethodError - false - end - - # Override to specify an alternative prefix for asset path generation. - # When combined with a custom +asset_environment+, this can be used to - # implement themes that can take advantage of the asset pipeline. - # - # If you only want to change where the assets are mounted, refer to - # +config.assets.prefix+ instead. - def asset_prefix - Rails.application.config.assets.prefix - end - - def asset_digests - Rails.application.config.assets.digests - end - - def compile_assets? - Rails.application.config.assets.compile - end - - def digest_assets? - Rails.application.config.assets.digest - end - - # Override to specify an alternative asset environment for asset - # path generation. The environment should already have been mounted - # at the prefix returned by +asset_prefix+. - def asset_environment - Rails.application.assets - end - - class AssetPaths < ::ActionView::AssetPaths #:nodoc: - attr_accessor :asset_environment, :asset_prefix, :asset_digests, :compile_assets, :digest_assets - - class AssetNotPrecompiledError < StandardError; end - - def asset_for(source, ext) - source = source.to_s - return nil if is_uri?(source) - source = rewrite_extension(source, nil, ext) - asset_environment[source] - rescue Sprockets::FileOutsidePaths - nil - end - - def digest_for(logical_path) - if digest_assets && asset_digests && (digest = asset_digests[logical_path]) - return digest - end - - if compile_assets - if digest_assets && asset = asset_environment[logical_path] - return asset.digest_path - end - return logical_path - else - raise AssetNotPrecompiledError.new("#{logical_path} isn't precompiled") - end - end - - def rewrite_asset_path(source, dir, options = {}) - if source[0] == ?/ - source - else - source = digest_for(source) unless options[:digest] == false - source = File.join(dir, source) - source = "/#{source}" unless source =~ /^\// - source - end - end - - def rewrite_extension(source, dir, ext) - if ext && File.extname(source) != ".#{ext}" - "#{source}.#{ext}" - else - source - end - end - end - end - end -end diff --git a/actionpack/lib/sprockets/railtie.rb b/actionpack/lib/sprockets/railtie.rb deleted file mode 100644 index 44ddab0950..0000000000 --- a/actionpack/lib/sprockets/railtie.rb +++ /dev/null @@ -1,62 +0,0 @@ -require "action_controller/railtie" - -module Sprockets - autoload :Bootstrap, "sprockets/bootstrap" - autoload :Helpers, "sprockets/helpers" - autoload :Compressors, "sprockets/compressors" - autoload :LazyCompressor, "sprockets/compressors" - autoload :NullCompressor, "sprockets/compressors" - autoload :StaticCompiler, "sprockets/static_compiler" - - # TODO: Get rid of config.assets.enabled - class Railtie < ::Rails::Railtie - rake_tasks do - load "sprockets/assets.rake" - end - - initializer "sprockets.environment", :group => :all do |app| - config = app.config - next unless config.assets.enabled - - require 'sprockets' - - app.assets = Sprockets::Environment.new(app.root.to_s) do |env| - env.version = ::Rails.env + "-#{config.assets.version}" - - if config.assets.logger != false - env.logger = config.assets.logger || ::Rails.logger - end - - if config.assets.cache_store != false - env.cache = ActiveSupport::Cache.lookup_store(config.assets.cache_store) || ::Rails.cache - end - end - - if config.assets.manifest - path = File.join(config.assets.manifest, "manifest.yml") - else - path = File.join(Rails.public_path, config.assets.prefix, "manifest.yml") - end - - if File.exist?(path) - config.assets.digests = YAML.load_file(path) - end - - ActiveSupport.on_load(:action_view) do - include ::Sprockets::Helpers::RailsHelper - app.assets.context_class.instance_eval do - include ::Sprockets::Helpers::IsolatedHelper - include ::Sprockets::Helpers::RailsHelper - end - end - end - - # We need to configure this after initialization to ensure we collect - # paths from all engines. This hook is invoked exactly before routes - # are compiled, and so that other Railties have an opportunity to - # register compressors. - config.after_initialize do |app| - Sprockets::Bootstrap.new(app).run - end - end -end diff --git a/actionpack/lib/sprockets/static_compiler.rb b/actionpack/lib/sprockets/static_compiler.rb deleted file mode 100644 index 719df0bd51..0000000000 --- a/actionpack/lib/sprockets/static_compiler.rb +++ /dev/null @@ -1,62 +0,0 @@ -require 'fileutils' - -module Sprockets - class StaticCompiler - attr_accessor :env, :target, :paths - - def initialize(env, target, paths, options = {}) - @env = env - @target = target - @paths = paths - @digest = options.key?(:digest) ? options.delete(:digest) : true - @manifest = options.key?(:manifest) ? options.delete(:manifest) : true - @manifest_path = options.delete(:manifest_path) || target - @zip_files = options.delete(:zip_files) || /\.(?:css|html|js|svg|txt|xml)$/ - end - - def compile - manifest = {} - env.each_logical_path do |logical_path| - next unless compile_path?(logical_path) - if asset = env.find_asset(logical_path) - manifest[logical_path] = write_asset(asset) - end - end - write_manifest(manifest) if @manifest - end - - def write_manifest(manifest) - FileUtils.mkdir_p(@manifest_path) - File.open("#{@manifest_path}/manifest.yml", 'wb') do |f| - YAML.dump(manifest, f) - end - end - - def write_asset(asset) - path_for(asset).tap do |path| - filename = File.join(target, path) - FileUtils.mkdir_p File.dirname(filename) - asset.write_to(filename) - asset.write_to("#{filename}.gz") if filename.to_s =~ @zip_files - end - end - - def compile_path?(logical_path) - paths.each do |path| - case path - when Regexp - return true if path.match(logical_path) - when Proc - return true if path.call(logical_path) - else - return true if File.fnmatch(path.to_s, logical_path) - end - end - false - end - - def path_for(asset) - @digest ? asset.digest_path : asset.logical_path - end - end -end |