diff options
Diffstat (limited to 'actionpack/lib')
65 files changed, 558 insertions, 336 deletions
diff --git a/actionpack/lib/abstract_controller/layouts.rb b/actionpack/lib/abstract_controller/layouts.rb index bc9f6fc3e8..c1b3994035 100644 --- a/actionpack/lib/abstract_controller/layouts.rb +++ b/actionpack/lib/abstract_controller/layouts.rb @@ -203,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 diff --git a/actionpack/lib/action_controller/caching/actions.rb b/actionpack/lib/action_controller/caching/actions.rb index 80901b8bf3..0238135bc1 100644 --- a/actionpack/lib/action_controller/caching/actions.rb +++ b/actionpack/lib/action_controller/caching/actions.rb @@ -47,7 +47,7 @@ module ActionController #:nodoc: # 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: @@ -178,8 +178,9 @@ module ActionController #:nodoc: private def normalize!(path) + ext = URI.parser.escape(extension) if extension path << 'index' if path[-1] == ?/ - path << ".#{extension}" if extension and !path.split('?', 2).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/pages.rb b/actionpack/lib/action_controller/caching/pages.rb index 307594d54a..dd4eddbe9a 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,8 +95,6 @@ module ActionController #:nodoc: # # You can also pass a :gzip option to override the class configuration one. # - # Usage: - # # # cache the index action # caches_page :index # @@ -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/log_subscriber.rb b/actionpack/lib/action_controller/log_subscriber.rb index 11aa393bf9..0fb419f941 100644 --- a/actionpack/lib/action_controller/log_subscriber.rb +++ b/actionpack/lib/action_controller/log_subscriber.rb @@ -33,9 +33,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/conditional_get.rb b/actionpack/lib/action_controller/metal/conditional_get.rb index 5b25a0d303..2193dde667 100644 --- a/actionpack/lib/action_controller/metal/conditional_get.rb +++ b/actionpack/lib/action_controller/metal/conditional_get.rb @@ -108,7 +108,6 @@ 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, :public => true, :must_revalidate => true diff --git a/actionpack/lib/action_controller/metal/exceptions.rb b/actionpack/lib/action_controller/metal/exceptions.rb index 90648c37ad..8fd8f4797c 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 @@ -38,7 +41,7 @@ module ActionController class UnknownHttpMethod < ActionControllerError #:nodoc: end - + class UnknownFormat < ActionControllerError #:nodoc: end end diff --git a/actionpack/lib/action_controller/metal/helpers.rb b/actionpack/lib/action_controller/metal/helpers.rb index 1a4bca12d2..86d061e3b7 100644 --- a/actionpack/lib/action_controller/metal/helpers.rb +++ b/actionpack/lib/action_controller/metal/helpers.rb @@ -16,7 +16,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: # diff --git a/actionpack/lib/action_controller/metal/mime_responds.rb b/actionpack/lib/action_controller/metal/mime_responds.rb index 7917926978..0b800c3c62 100644 --- a/actionpack/lib/action_controller/metal/mime_responds.rb +++ b/actionpack/lib/action_controller/metal/mime_responds.rb @@ -16,8 +16,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 @@ -185,7 +183,6 @@ module ActionController #:nodoc: # end # # Be sure to check respond_with and respond_to documentation 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? @@ -323,7 +320,6 @@ module ActionController #:nodoc: # 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? @@ -339,7 +335,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 @@ -362,7 +357,6 @@ module ActionController #:nodoc: # # 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) @@ -401,7 +395,6 @@ module ActionController #:nodoc: # 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 1f52c164de..aa67fa7f23 100644 --- a/actionpack/lib/action_controller/metal/params_wrapper.rb +++ b/actionpack/lib/action_controller/metal/params_wrapper.rb @@ -193,7 +193,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/redirecting.rb b/actionpack/lib/action_controller/metal/redirecting.rb index 5e7bd44562..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 @@ -51,14 +49,12 @@ module ActionController # around this you can return a <tt>303 See Other</tt> status code which will be # followed using a GET request. # - # Examples: # 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 } @@ -69,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) diff --git a/actionpack/lib/action_controller/metal/renderers.rb b/actionpack/lib/action_controller/metal/renderers.rb index 4a0c1c7dd7..1927c8bdc7 100644 --- a/actionpack/lib/action_controller/metal/renderers.rb +++ b/actionpack/lib/action_controller/metal/renderers.rb @@ -49,7 +49,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| diff --git a/actionpack/lib/action_controller/metal/request_forgery_protection.rb b/actionpack/lib/action_controller/metal/request_forgery_protection.rb index 0bff1825d9..95b0e99ed5 100644 --- a/actionpack/lib/action_controller/metal/request_forgery_protection.rb +++ b/actionpack/lib/action_controller/metal/request_forgery_protection.rb @@ -51,8 +51,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 # diff --git a/actionpack/lib/action_controller/metal/url_for.rb b/actionpack/lib/action_controller/metal/url_for.rb index 8e7b56dbcc..e28c05cc2d 100644 --- a/actionpack/lib/action_controller/metal/url_for.rb +++ b/actionpack/lib/action_controller/metal/url_for.rb @@ -6,8 +6,6 @@ module ActionController # 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 @@ -19,7 +17,6 @@ module ActionController # @url = root_path # named route from the application. # end # end - # module UrlFor extend ActiveSupport::Concern diff --git a/actionpack/lib/action_controller/record_identifier.rb b/actionpack/lib/action_controller/record_identifier.rb index e7af3f5b8d..16a5decc62 100644 --- a/actionpack/lib/action_controller/record_identifier.rb +++ b/actionpack/lib/action_controller/record_identifier.rb @@ -3,7 +3,7 @@ require 'active_support/core_ext/module' module ActionController # 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. Example: + # a higher logical level. # # # routes # resources :posts @@ -30,7 +30,7 @@ module ActionController JOIN = '_'.freeze NEW = 'new'.freeze - # The DOM class convention is to use the singular form of an object or class. Examples: + # The DOM class convention is to use the singular form of an object or class. # # dom_class(post) # => "post" # dom_class(Person) # => "person" @@ -45,7 +45,7 @@ module ActionController 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: + # If no id is found, prefix with "new_" instead. # # dom_id(Post.find(45)) # => "post_45" # dom_id(Post.new) # => "new_post" diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb index ad02375f12..028a8d3fba 100644 --- a/actionpack/lib/action_controller/test_case.rb +++ b/actionpack/lib/action_controller/test_case.rb @@ -56,8 +56,6 @@ 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" # @@ -84,7 +82,6 @@ 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 @@ -96,13 +93,13 @@ module ActionController rendered = @templates msg = message || sprintf("expecting <%s> but rendering with <%s>", options.inspect, rendered.keys) - assert_block(msg) do + matches_template = if options rendered.any? { |t,num| t.match(options) } else @templates.blank? end - end + assert matches_template, msg when Hash if options.key?(:layout) expected_layout = options[:layout] @@ -350,7 +347,6 @@ 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 @@ -369,12 +365,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 diff --git a/actionpack/lib/action_dispatch/http/filter_parameters.rb b/actionpack/lib/action_dispatch/http/filter_parameters.rb index 132b0c82bc..6413929be3 100644 --- a/actionpack/lib/action_dispatch/http/filter_parameters.rb +++ b/actionpack/lib/action_dispatch/http/filter_parameters.rb @@ -10,8 +10,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 +20,6 @@ module ActionDispatch # v.reverse! if k =~ /secret/i # end # => reverses the value to all keys matching /secret/i - # module FilterParameters extend ActiveSupport::Concern diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb index 9748956052..aa5ba3e8a5 100644 --- a/actionpack/lib/action_dispatch/http/request.rb +++ b/actionpack/lib/action_dispatch/http/request.rb @@ -6,7 +6,6 @@ require 'active_support/core_ext/hash/indifferent_access' require 'active_support/core_ext/string/access' require 'active_support/inflector' require 'action_dispatch/http/headers' -require 'action_dispatch/request/session' require 'action_controller/metal/exceptions' module ActionDispatch @@ -18,6 +17,8 @@ module ActionDispatch include ActionDispatch::Http::Upload include ActionDispatch::Http::URL + 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 @@ -230,17 +231,24 @@ module ActionDispatch # 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 diff --git a/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb index a8f49bd3bd..7349b578d2 100644 --- a/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb +++ b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb @@ -12,7 +12,8 @@ module ActionDispatch 'ActionController::MethodNotAllowed' => :method_not_allowed, 'ActionController::NotImplemented' => :not_implemented, 'ActionController::UnknownFormat' => :not_acceptable, - 'ActionController::InvalidAuthenticityToken' => :unprocessable_entity + 'ActionController::InvalidAuthenticityToken' => :unprocessable_entity, + 'ActionController::BadRequest' => :bad_request ) cattr_accessor :rescue_templates diff --git a/actionpack/lib/action_dispatch/middleware/flash.rb b/actionpack/lib/action_dispatch/middleware/flash.rb index 17776c2356..9928b7cc3a 100644 --- a/actionpack/lib/action_dispatch/middleware/flash.rb +++ b/actionpack/lib/action_dispatch/middleware/flash.rb @@ -11,7 +11,7 @@ module ActionDispatch # 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 diff --git a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb index dbcf703ec3..7efc094f98 100644 --- a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb +++ b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb @@ -27,7 +27,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 } diff --git a/actionpack/lib/action_dispatch/middleware/stack.rb b/actionpack/lib/action_dispatch/middleware/stack.rb index 12bc438be3..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 diff --git a/actionpack/lib/action_dispatch/request/session.rb b/actionpack/lib/action_dispatch/request/session.rb index 4ad7071820..d8bcc28613 100644 --- a/actionpack/lib/action_dispatch/request/session.rb +++ b/actionpack/lib/action_dispatch/request/session.rb @@ -87,6 +87,14 @@ module ActionDispatch 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 diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 7a22b65c44..67a208263b 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -495,8 +495,6 @@ module ActionDispatch # Define a route that only recognizes HTTP GET. # For supported arguments, see <tt>Base#match</tt>. # - # Example: - # # get 'bacon', :to => 'food#bacon' def get(*args, &block) map_method(:get, args, &block) @@ -505,8 +503,6 @@ module ActionDispatch # Define a route that only recognizes HTTP POST. # For supported arguments, see <tt>Base#match</tt>. # - # Example: - # # post 'bacon', :to => 'food#bacon' def post(*args, &block) map_method(:post, args, &block) @@ -515,8 +511,6 @@ module ActionDispatch # 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) @@ -525,8 +519,6 @@ module ActionDispatch # Define a route that only recognizes HTTP PUT. # For supported arguments, see <tt>Base#match</tt>. # - # Example: - # # put 'bacon', :to => 'food#bacon' def put(*args, &block) map_method(:put, args, &block) @@ -535,8 +527,6 @@ module ActionDispatch # Define a route that only recognizes HTTP DELETE. # For supported arguments, see <tt>Base#match</tt>. # - # Example: - # # delete 'broccoli', :to => 'food#broccoli' def delete(*args, &block) map_method(:delete, args, &block) @@ -681,7 +671,6 @@ module ActionDispatch # Scopes routes to a specific controller # - # Example: # controller "food" do # match "bacon", :action => "bacon" # end @@ -1336,10 +1325,11 @@ module ActionDispatch msg = "Your router tried to #draw the external file #{name}.rb,\n" \ "but the file was not found in:\n\n" msg += @draw_paths.map { |_path| " * #{_path}" }.join("\n") - raise msg + raise ArgumentError, msg end - - instance_eval(path.join("#{name}.rb").read) + + route_path = path.join("#{name}.rb") + instance_eval(route_path.read, route_path.to_s) end # match 'path' => 'controller#action' diff --git a/actionpack/lib/action_dispatch/routing/redirection.rb b/actionpack/lib/action_dispatch/routing/redirection.rb index 95c588c00a..205ff44b1c 100644 --- a/actionpack/lib/action_dispatch/routing/redirection.rb +++ b/actionpack/lib/action_dispatch/routing/redirection.rb @@ -2,6 +2,7 @@ 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 @@ -16,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 @@ -35,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: @@ -56,6 +84,10 @@ module ActionDispatch 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)] }] @@ -102,24 +134,15 @@ module ActionDispatch def redirect(*args, &block) 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 % escape(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 Redirect.new status, block end - - private - def escape(params) - Hash[params.map{ |k,v| [k, Rack::Utils.escape(v)] }] - end end end end diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 0ae668d42a..7872f4007e 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -26,6 +26,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. @@ -654,9 +663,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 diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb index ee02f4b531..fd3bed7e8f 100644 --- a/actionpack/lib/action_dispatch/routing/url_for.rb +++ b/actionpack/lib/action_dispatch/routing/url_for.rb @@ -132,8 +132,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 diff --git a/actionpack/lib/action_dispatch/testing/assertions/dom.rb b/actionpack/lib/action_dispatch/testing/assertions/dom.rb index edea6dab39..7dc3d0f97c 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/dom.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/dom.rb @@ -5,11 +5,8 @@ module ActionDispatch 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 8f6fff5d32..b4c8f839ac 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/response.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/response.rb @@ -15,14 +15,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}>" @@ -31,7 +28,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 @@ -42,8 +39,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,7 +50,6 @@ module ActionDispatch # # # 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 diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb index 1f4b905d18..41fa3a4b95 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') # @@ -57,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" # @@ -71,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 == '/' @@ -100,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' # @@ -192,14 +187,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 == "/" @@ -208,11 +201,21 @@ module ActionDispatch request.request_method = method if method - params = @routes.recognize_path(path, { :method => method, :extras => extras }) + 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 ea1ed20f3c..5f9c3bbf48 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/selector.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/selector.rb @@ -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 @@ -340,7 +338,6 @@ 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[xmlns='http://www.w3.org/2005/Atom']" do # # Select each entry item and then the title item @@ -401,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 @@ -413,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..68f1347e7c 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/tag.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/tag.rb @@ -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/test_request.rb b/actionpack/lib/action_dispatch/testing/test_request.rb index d04be2099c..a86b510719 100644 --- a/actionpack/lib/action_dispatch/testing/test_request.rb +++ b/actionpack/lib/action_dispatch/testing/test_request.rb @@ -11,7 +11,7 @@ module ActionDispatch end def initialize(env = {}) - env = Rails.application.env_config.merge(env) if defined?(Rails.application) + env = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application super(DEFAULT_ENV.merge(env)) self.host = 'test.host' diff --git a/actionpack/lib/action_view/asset_paths.rb b/actionpack/lib/action_view/asset_paths.rb index add8d94b70..4ce41d51f1 100644 --- a/actionpack/lib/action_view/asset_paths.rb +++ b/actionpack/lib/action_view/asset_paths.rb @@ -4,7 +4,7 @@ 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 diff --git a/actionpack/lib/action_view/context.rb b/actionpack/lib/action_view/context.rb index 083856b2ca..245849d706 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,7 +25,7 @@ module ActionView end # Encapsulates the interaction with the view flow so it - # returns the correct buffer on yield. This is usually + # returns the correct buffer on +yield+. This is usually # overwriten by helpers to add more behavior. # :api: plugin def _layout_for(name=nil) diff --git a/actionpack/lib/action_view/helpers/asset_tag_helper.rb b/actionpack/lib/action_view/helpers/asset_tag_helper.rb index a8d6213b13..02c1250c76 100644 --- a/actionpack/lib/action_view/helpers/asset_tag_helper.rb +++ b/actionpack/lib/action_view/helpers/asset_tag_helper.rb @@ -252,7 +252,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', @@ -275,7 +274,7 @@ 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 @@ -290,7 +289,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 @@ -312,7 +310,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 @@ -323,7 +320,7 @@ 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 @@ -333,7 +330,6 @@ module ActionView # Computes the path to a font asset. # Full paths from the document root will be passed through. # - # ==== Examples # font_path("font") # => /assets/font # font_path("font.ttf") # => /assets/font.ttf # font_path("dir/font.ttf") # => /assets/dir/font.ttf @@ -363,11 +359,7 @@ 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="/assets/icon" alt="Icon" /> # image_tag("icon.png") # => @@ -380,16 +372,12 @@ module ActionView # <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 => "/assets/mouse_over.png") # => - # <img src="/assets/mouse.png" onmouseover="this.src='/assets/mouse_over.png'" onmouseout="this.src='/assets/mouse.png'" alt="Mouse" /> - # image_tag("mouse.png", :mouseover => image_path("mouse_over.png")) # => - # <img src="/assets/mouse.png" onmouseover="this.src='/assets/mouse_over.png'" onmouseout="this.src='/assets/mouse.png'" alt="Mouse" /> def image_tag(source, options={}) 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 @@ -397,11 +385,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 @@ -425,7 +408,6 @@ 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") # => @@ -458,15 +440,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 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 7bff0c1149..4292d29f60 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 @@ -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 @@ -114,7 +113,6 @@ module ActionView # You can modify the HTML attributes of the script tag by passing a hash as the # last argument. # - # ==== Examples # javascript_include_tag "xmlhr" # # => <script src="/javascripts/xmlhr.js?1284139606"></script> # @@ -160,8 +158,6 @@ 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 src="/javascripts/jquery.js?1284139606"></script> 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 4bcb8b9718..57b0627225 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 @@ -54,7 +54,6 @@ module ActionView # 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,7 +78,6 @@ 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" /> # @@ -117,7 +115,6 @@ module ActionView # 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" /> # <link href="/stylesheets/styleB.css" media="screen" rel="stylesheet" /> diff --git a/actionpack/lib/action_view/helpers/cache_helper.rb b/actionpack/lib/action_view/helpers/cache_helper.rb index 850dd5f448..33799d7d71 100644 --- a/actionpack/lib/action_view/helpers/cache_helper.rb +++ b/actionpack/lib/action_view/helpers/cache_helper.rb @@ -10,7 +10,6 @@ module ActionView # # See ActionController::Caching::Fragments for usage instructions. # - # ==== Examples # If you want to cache a navigation menu, you can do following: # # <% cache do %> diff --git a/actionpack/lib/action_view/helpers/capture_helper.rb b/actionpack/lib/action_view/helpers/capture_helper.rb index d9d6f90211..397738dd98 100644 --- a/actionpack/lib/action_view/helpers/capture_helper.rb +++ b/actionpack/lib/action_view/helpers/capture_helper.rb @@ -13,7 +13,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 %> diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb index f0a593d2c1..659aacf6d7 100644 --- a/actionpack/lib/action_view/helpers/date_helper.rb +++ b/actionpack/lib/action_view/helpers/date_helper.rb @@ -64,7 +64,6 @@ module ActionView # 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 @@ -140,7 +139,6 @@ 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 @@ -148,7 +146,6 @@ module ActionView # # 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_or_options = {}) distance_of_time_in_words(from_time, Time.now, include_seconds_or_options) end @@ -197,7 +194,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") # @@ -253,7 +249,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") # @@ -286,7 +281,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") @@ -325,7 +319,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). @@ -362,7 +355,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 @@ -374,7 +366,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). @@ -403,7 +394,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 @@ -414,7 +404,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. @@ -442,7 +431,6 @@ module ActionView # 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 @@ -451,7 +439,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. @@ -467,7 +454,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 @@ -477,7 +463,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. @@ -493,7 +478,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 @@ -502,7 +486,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. @@ -521,7 +504,6 @@ module ActionView # # # Generate a select field for hours in the AM/PM format # select_hour(my_time, :ampm => true) - # def select_hour(datetime, options = {}, html_options = {}) DateTimeSelector.new(datetime, options, html_options).select_hour end @@ -531,7 +513,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. @@ -550,7 +531,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 @@ -565,7 +545,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) @@ -597,7 +576,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 @@ -608,7 +586,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) @@ -628,14 +605,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 # => @@ -649,7 +624,6 @@ module ActionView # <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 diff --git a/actionpack/lib/action_view/helpers/debug_helper.rb b/actionpack/lib/action_view/helpers/debug_helper.rb index c0cc7d347c..878a8734a4 100644 --- a/actionpack/lib/action_view/helpers/debug_helper.rb +++ b/actionpack/lib/action_view/helpers/debug_helper.rb @@ -8,8 +8,6 @@ module ActionView # 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,7 +23,6 @@ module ActionView # # new_record: true # </pre> - def debug(object) begin Marshal::dump(object) diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb index 0fbd6ac41b..ad8885b708 100644 --- a/actionpack/lib/action_view/helpers/form_helper.rb +++ b/actionpack/lib/action_view/helpers/form_helper.rb @@ -900,7 +900,6 @@ 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" /> @@ -926,7 +925,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") @@ -941,12 +939,19 @@ 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]" type="search" /> # search_field(:user, :name, :autosave => false) @@ -962,7 +967,6 @@ module ActionView # # => <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" type="search" /> - # def search_field(object_name, method, options = {}) Tags::SearchField.new(object_name, method, self, options).render end @@ -995,6 +999,91 @@ module ActionView 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") diff --git a/actionpack/lib/action_view/helpers/form_options_helper.rb b/actionpack/lib/action_view/helpers/form_options_helper.rb index cafcd93f58..eef426703d 100644 --- a/actionpack/lib/action_view/helpers/form_options_helper.rb +++ b/actionpack/lib/action_view/helpers/form_options_helper.rb @@ -264,7 +264,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)" ) @@ -461,8 +460,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 = [ @@ -475,8 +477,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) # @@ -491,15 +493,50 @@ 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="Denmark">Denmark</option> + # <option value="Germany">Germany</option> + # <option value="France">France</option> + # </optgroup> + # <optgroup label="---------"> + # <option value="US">United States</option> + # <option value="Canada">Canada</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) + 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 - body.safe_concat content_tag(:option, prompt, :value => "") if prompt + + 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 |label, container| + 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 @@ -715,6 +752,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 248cc2f6a3..1a0019a48c 100644 --- a/actionpack/lib/action_view/helpers/form_tag_helper.rb +++ b/actionpack/lib/action_view/helpers/form_tag_helper.rb @@ -386,9 +386,6 @@ module ActionView # 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 @@ -401,14 +398,14 @@ 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?" # # => <input name='commit' type='submit' value='Save' data-confirm="Are you sure?" /> @@ -416,10 +413,6 @@ module ActionView def submit_tag(value = "Save changes", options = {}) options = options.stringify_keys - if disable_with = options.delete("disable_with") - options["data-disable-with"] = disable_with - end - if confirm = options.delete("confirm") options["data-confirm"] = confirm end @@ -441,10 +434,6 @@ module ActionView # 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 @@ -458,18 +447,11 @@ module ActionView # # <strong>Ask me!</strong> # # </button> # - # button_tag "Checkout", :disable_with => "Please wait..." - # # => <button data-disable-with="Please wait..." name="button" type="submit">Checkout</button> - # def button_tag(content_or_options = nil, options = nil, &block) options = content_or_options if block_given? && content_or_options.is_a?(Hash) options ||= {} options = options.stringify_keys - if disable_with = options.delete("disable_with") - options["data-disable-with"] = disable_with - end - if confirm = options.delete("confirm") options["data-confirm"] = confirm end @@ -542,6 +524,14 @@ module ActionView 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 @@ -567,6 +557,61 @@ module ActionView 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 diff --git a/actionpack/lib/action_view/helpers/sanitize_helper.rb b/actionpack/lib/action_view/helpers/sanitize_helper.rb index 7768c8c151..a727b910e5 100644 --- a/actionpack/lib/action_view/helpers/sanitize_helper.rb +++ b/actionpack/lib/action_view/helpers/sanitize_helper.rb @@ -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! # @@ -85,7 +83,6 @@ module ActionView # 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 f7afa48256..9572f1c192 100644 --- a/actionpack/lib/action_view/helpers/tag_helper.rb +++ b/actionpack/lib/action_view/helpers/tag_helper.rb @@ -41,7 +41,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 @@ -103,7 +103,6 @@ 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>]]> # @@ -119,7 +118,6 @@ module ActionView # Returns an escaped version of +html+ without affecting existing escaped entities. # - # ==== Examples # escape_once("1 < 2 & 3") # # => "1 < 2 & 3" # @@ -156,8 +154,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 3cf762877f..a05e16979a 100644 --- a/actionpack/lib/action_view/helpers/tags.rb +++ b/actionpack/lib/action_view/helpers/tags.rb @@ -8,14 +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 @@ -25,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 380ebe4b65..e077cd5b3c 100644 --- a/actionpack/lib/action_view/helpers/tags/base.rb +++ b/actionpack/lib/action_view/helpers/tags/base.rb @@ -140,8 +140,7 @@ module ActionView option_tags = content_tag('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 = content_tag('option', prompt, :value => '') + "\n" + option_tags + option_tags = content_tag('option', prompt_text(options[:prompt]), :value => '') + "\n" + option_tags end option_tags end 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 index bb968e9f39..64c29dea3d 100644 --- a/actionpack/lib/action_view/helpers/tags/date_field.rb +++ b/actionpack/lib/action_view/helpers/tags/date_field.rb @@ -1,14 +1,12 @@ module ActionView module Helpers module Tags - class DateField < TextField #:nodoc: - def render - options = @options.stringify_keys - options["value"] = @options.fetch("value") { value(object).try(:to_date) } - options["size"] = nil - @options = options - super - end + class DateField < DatetimeField #:nodoc: + private + + def format_date(value) + value.try(:strftime, "%Y-%m-%d") + 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/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/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/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 698f4434ba..8cd7cf0052 100644 --- a/actionpack/lib/action_view/helpers/text_helper.rb +++ b/actionpack/lib/action_view/helpers/text_helper.rb @@ -37,7 +37,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" %> @@ -67,8 +66,6 @@ module ActionView # 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). # - # ==== Examples - # # truncate("Once upon a time in a world far far away") # # => "Once upon a time in a world..." # @@ -84,8 +81,7 @@ 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 + text.truncate(options.fetch(:length, 30), options) if text end # Highlights one or more +phrases+ everywhere in +text+ by inserting it into @@ -93,7 +89,6 @@ module ActionView # 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> # @@ -105,25 +100,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] - end - options[:highlighter] ||= '<mark>\1</mark>' - - text = sanitize(text) unless options[:sanitize] == false + def highlight(text, phrases, options = {}) + highlighter = options.fetch(:highlighter, '<mark>\1</mark>') + + text = sanitize(text) if options.fetch(:sanitize, true) if text.blank? || phrases.blank? text 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 @@ -133,7 +118,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... # @@ -148,22 +132,10 @@ 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] - options[:omission] = args[1] - end - radius = options[:radius] || 100 - omission = options[:omission] || "..." + radius = options.fetch(:radius, 100) + omission = options.fetch(:omission, "...") phrase = Regexp.escape(phrase) return unless found_pos = text =~ /(#{phrase})/i @@ -179,9 +151,8 @@ module ActionView # 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 # @@ -194,36 +165,32 @@ 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] - end - line_width = options[:line_width] || 80 + def word_wrap(text, options = {}) + line_width = options.fetch(:line_width, 80) text.split("\n").collect do |line| line.length > line_width ? line.gsub(/(.{1,#{line_width}})(\s+|$)/, "\\1\n").strip : line @@ -241,12 +208,16 @@ 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." # # 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." # @@ -258,17 +229,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 @@ -280,7 +253,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> @@ -311,7 +283,7 @@ module ActionView # <% end %> def cycle(first_value, *values) options = values.extract_options! - name = options.fetch(:name, "default") + name = options.fetch(:name, 'default') values.unshift(first_value) @@ -326,7 +298,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| %> @@ -342,7 +313,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> @@ -413,6 +383,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 8171bea8ed..552c9ba660 100644 --- a/actionpack/lib/action_view/helpers/translation_helper.rb +++ b/actionpack/lib/action_view/helpers/translation_helper.rb @@ -64,7 +64,7 @@ module ActionView # Delegates to <tt>I18n.localize</tt> with no additional functionality. # - # See http://rubydoc.info/github/svenfuchs/i18n/master/I18n/Backend/Base:localize + # See http://rubydoc.info/github/svenfuchs/i18n/master/I18n/Backend/Base:localize # for more information. def localize(*args) I18n.localize(*args) @@ -96,7 +96,7 @@ module ActionView new_defaults << lambda { |_, options| translate key, options.merge(:default => defaults) } break else - new_defautls << key + new_defaults << key end end diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb index 802bf9d29f..7e69547dab 100644 --- a/actionpack/lib/action_view/helpers/url_helper.rb +++ b/actionpack/lib/action_view/helpers/url_helper.rb @@ -108,7 +108,7 @@ module ActionView options when nil, Hash options ||= {} - options = options.symbolize_keys.reverse_merge!(:only_path => options[:host].nil?) + options = { :only_path => options[:host].nil? }.merge!(options.symbolize_keys) super when :back controller.request.env["HTTP_REFERER"] || 'javascript:history.back()' @@ -322,11 +322,11 @@ module ActionView # # # <%= button_to('Destroy', 'http://www.example.com', :confirm => 'Are you sure?', - # :method => "delete", :remote => true, :disable_with => 'loading...') %> + # :method => "delete", :remote => true) %> # # => "<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-confirm='Are you sure?' /> # # <input name="authenticity_token" type="hidden" value="10f2163b45388899ad4d5ae948988266befcb6c3d1b2451cf657a0c293d605a6"/> # # </div> # # </form>" @@ -616,11 +616,9 @@ module ActionView html_options = html_options.stringify_keys html_options['data-remote'] = 'true' if link_to_remote_options?(options) || link_to_remote_options?(html_options) - disable_with = html_options.delete("disable_with") confirm = html_options.delete('confirm') method = html_options.delete('method') - html_options["data-disable-with"] = disable_with if disable_with html_options["data-confirm"] = confirm if confirm add_method_to_attributes!(html_options, method) if method diff --git a/actionpack/lib/action_view/template.rb b/actionpack/lib/action_view/template.rb index edb3d427d5..cd79468502 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 'thread' module ActionView # = Action View Template @@ -122,6 +123,7 @@ module ActionView @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 } + @compile_mutex = Mutex.new end # Returns if the underlying handler supports streaming. If so, @@ -223,18 +225,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/handlers.rb b/actionpack/lib/action_view/template/handlers.rb index 4e22bec6cc..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 = {} 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 08155af013..fa2038f78d 100644 --- a/actionpack/lib/action_view/template/resolver.rb +++ b/actionpack/lib/action_view/template/resolver.rb @@ -171,7 +171,9 @@ module ActionView def extract_handler_and_format(path, default_formats) pieces = File.basename(path).split(".") pieces.shift - handler = Template.handler_for_extension(pieces.pop) + 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 && Mime[pieces.last] [handler, format] end |